Merge "Regenerate LocaleDataTables.cpp wtih Unicode 13 update" into rvc-dev
diff --git a/Android.bp b/Android.bp
index fb14f86..da5d624 100644
--- a/Android.bp
+++ b/Android.bp
@@ -281,17 +281,33 @@
filegroup {
name: "framework-updatable-sources",
srcs: [
- ":framework-sdkextensions-sources",
- ":framework-statsd-sources",
- ":framework-tethering-srcs",
- ":updatable-media-srcs",
":framework-mediaprovider-sources",
":framework-permission-sources",
- ":framework-wifi-updatable-sources",
+ ":framework-sdkextensions-sources",
+ ":framework-statsd-sources",
":framework-telephony-sources",
+ ":framework-tethering-srcs",
+ ":framework-wifi-updatable-sources",
+ ":updatable-media-srcs",
]
}
+java_library {
+ name: "framework-updatable-stubs-module_libs_api",
+ static_libs: [
+ "framework-media-stubs-module_libs_api",
+ "framework-mediaprovider-stubs-module_libs_api",
+ "framework-permission-stubs-module_libs_api",
+ "framework-sdkextensions-stubs-module_libs_api",
+ "framework-statsd-stubs-module_libs_api",
+ "framework-telephony-stubs", // TODO: Update to module_libs_api when there is one.
+ "framework-tethering-stubs-module_libs_api",
+ "framework-wifi-stubs-module_libs_api",
+ ],
+ sdk_version: "module_current",
+ visibility: [":__pkg__"],
+}
+
filegroup {
name: "framework-all-sources",
srcs: [
@@ -307,7 +323,6 @@
name: "framework-aidl-export-defaults",
aidl: {
export_include_dirs: [
- "apex/media/framework/java",
"core/java",
"drm/java",
"graphics/java",
@@ -324,6 +339,12 @@
"rs/java",
"sax/java",
"telecomm/java",
+
+ // TODO(b/148660295): remove this
+ "apex/media/framework/java",
+
+ // TODO(b/147699819): remove this
+ "telephony/java",
],
},
}
@@ -397,9 +418,7 @@
"app-compat-annotations",
"ext",
"unsupportedappusage",
- "framework-media-stubs-systemapi",
- "framework-mediaprovider-stubs-systemapi",
- "framework-telephony-stubs",
+ "framework-updatable-stubs-module_libs_api",
],
jarjar_rules: ":framework-jarjar-rules",
@@ -465,13 +484,6 @@
name: "framework-minus-apex",
defaults: ["framework-defaults"],
srcs: [":framework-non-updatable-sources"],
- libs: [
- "framework-sdkextensions-stubs-systemapi",
- "framework-statsd-stubs-module_libs_api",
- "framework-permission-stubs-systemapi",
- "framework-wifi-stubs-systemapi",
- "framework-tethering-stubs",
- ],
installable: true,
javac_shard_size: 150,
required: [
@@ -512,16 +524,9 @@
installable: false, // this lib is a build-only library
static_libs: [
"framework-minus-apex",
- "framework-media-stubs-systemapi",
- "framework-mediaprovider-stubs-systemapi",
- "framework-permission-stubs-systemapi",
- "framework-sdkextensions-stubs-systemapi",
- "framework-statsd-stubs-module_libs_api",
- "framework-wifi-stubs-systemapi",
- "framework-tethering-stubs",
- // TODO (b/147688669) should be framework-telephony-stubs
+ // TODO (b/147688669) should be removed
"framework-telephony",
- // TODO(jiyong): add stubs for APEXes here
+ "framework-updatable-stubs-module_libs_api",
],
sdk_version: "core_platform",
apex_available: ["//apex_available:platform"],
@@ -540,9 +545,7 @@
visibility: [
// DO NOT ADD ANY MORE ENTRIES TO THIS LIST
"//external/robolectric-shadows:__subpackages__",
- "//frameworks/base/packages/Tethering/common/TetheringLib:__subpackages__",
"//frameworks/layoutlib:__subpackages__",
- "//frameworks/opt/net/ike:__subpackages__",
],
}
@@ -690,6 +693,7 @@
"core/java/android/annotation/CallbackExecutor.java",
"core/java/android/annotation/CheckResult.java",
"core/java/android/annotation/CurrentTimeMillisLong.java",
+ "core/java/android/annotation/Hide.java",
"core/java/android/annotation/IntDef.java",
"core/java/android/annotation/IntRange.java",
"core/java/android/annotation/LongDef.java",
@@ -701,6 +705,7 @@
"core/java/android/annotation/SystemApi.java",
"core/java/android/annotation/SystemService.java",
"core/java/android/annotation/TestApi.java",
+ "core/java/android/annotation/WorkerThread.java",
"core/java/com/android/internal/annotations/GuardedBy.java",
"core/java/com/android/internal/annotations/VisibleForTesting.java",
"core/java/com/android/internal/annotations/Immutable.java",
@@ -748,6 +753,18 @@
],
}
+filegroup {
+ name: "framework-services-net-module-wifi-shared-srcs",
+ srcs: [
+ "core/java/android/net/DhcpResults.java",
+ "core/java/android/net/shared/Inet4AddressUtils.java",
+ "core/java/android/net/shared/InetAddressUtils.java",
+ "core/java/android/net/util/IpUtils.java",
+ "core/java/android/util/LocalLog.java",
+ "core/java/com/android/internal/util/Preconditions.java",
+ ],
+}
+
// keep these files in sync with the package/Tethering/jarjar-rules.txt for the tethering module.
filegroup {
name: "framework-tethering-shared-srcs",
@@ -774,10 +791,6 @@
"libphonenumber-platform",
"tagsoup",
"rappor",
- "libtextclassifier-java",
- ],
- required: [
- "libtextclassifier",
],
dxflags: ["--core-library"],
}
@@ -969,7 +982,6 @@
srcs: [
"core/java/android/os/incremental/IIncrementalService.aidl",
"core/java/android/os/incremental/IncrementalNewFileParams.aidl",
- "core/java/android/os/incremental/IncrementalSignature.aidl",
],
path: "core/java",
}
@@ -1236,7 +1248,6 @@
"core/java/android/net/InterfaceConfiguration.java",
"core/java/android/os/BasicShellCommandHandler.java",
"core/java/android/util/BackupUtils.java",
- "core/java/android/util/LocalLog.java",
"core/java/android/util/Rational.java",
"core/java/com/android/internal/util/FastXmlSerializer.java",
"core/java/com/android/internal/util/HexDump.java",
diff --git a/StubLibraries.bp b/StubLibraries.bp
index 7f23df7..da9f165 100644
--- a/StubLibraries.bp
+++ b/StubLibraries.bp
@@ -41,7 +41,7 @@
]
stubs_defaults {
- name: "metalava-non-updatable-api-stubs-default",
+ name: "metalava-base-api-stubs-default",
srcs: [
":framework-non-updatable-sources",
"core/java/**/*.logtags",
@@ -70,12 +70,18 @@
}
stubs_defaults {
- name: "metalava-api-stubs-default",
- defaults: ["metalava-non-updatable-api-stubs-default"],
+ name: "metalava-full-api-stubs-default",
+ defaults: ["metalava-base-api-stubs-default"],
srcs: [":framework-updatable-sources"],
sdk_version: "core_platform",
}
+stubs_defaults {
+ name: "metalava-non-updatable-api-stubs-default",
+ defaults: ["metalava-base-api-stubs-default"],
+ sdk_version: "system_current",
+}
+
/////////////////////////////////////////////////////////////////////
// *-api-stubs-docs modules providing source files for the stub libraries
/////////////////////////////////////////////////////////////////////
@@ -85,7 +91,7 @@
// modules
droidstubs {
name: "api-stubs-docs",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-full-api-stubs-default"],
api_filename: "public_api.txt",
private_api_filename: "private.txt",
removed_api_filename: "removed.txt",
@@ -124,7 +130,7 @@
droidstubs {
name: "system-api-stubs-docs",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-full-api-stubs-default"],
api_tag_name: "SYSTEM",
api_filename: "system-api.txt",
private_api_filename: "system-private.txt",
@@ -155,7 +161,7 @@
droidstubs {
name: "test-api-stubs-docs",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-full-api-stubs-default"],
api_tag_name: "TEST",
api_filename: "test-api.txt",
removed_api_filename: "test-removed.txt",
@@ -188,7 +194,7 @@
droidstubs {
name: "module-lib-api",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-full-api-stubs-default"],
arg_files: ["core/res/AndroidManifest.xml"],
args: metalava_framework_docs_args + module_libs,
check_api: {
@@ -216,7 +222,7 @@
droidstubs {
name: "module-lib-api-stubs-docs",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-non-updatable-api-stubs-default"],
arg_files: ["core/res/AndroidManifest.xml"],
args: metalava_framework_docs_args + priv_apps + module_libs,
}
@@ -266,6 +272,7 @@
name: "android_module_lib_stubs_current",
srcs: [ ":module-lib-api-stubs-docs" ],
defaults: ["framework-stubs-default"],
+ libs: ["android_system_stubs_current"],
}
/////////////////////////////////////////////////////////////////////
@@ -317,7 +324,7 @@
droidstubs {
name: "hiddenapi-lists-docs",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-full-api-stubs-default"],
arg_files: [
"core/res/AndroidManifest.xml",
],
@@ -332,7 +339,7 @@
droidstubs {
name: "hiddenapi-mappings",
- defaults: ["metalava-api-stubs-default"],
+ defaults: ["metalava-full-api-stubs-default"],
srcs: [
":opt-telephony-common-srcs",
],
diff --git a/apct-tests/perftests/blobstore/src/com/android/perftests/blob/BlobStorePerfTests.java b/apct-tests/perftests/blobstore/src/com/android/perftests/blob/BlobStorePerfTests.java
index 02df5e2..23f025b 100644
--- a/apct-tests/perftests/blobstore/src/com/android/perftests/blob/BlobStorePerfTests.java
+++ b/apct-tests/perftests/blobstore/src/com/android/perftests/blob/BlobStorePerfTests.java
@@ -121,8 +121,9 @@
}
private DummyBlobData prepareDataBlob(int fileSizeInMb) throws Exception {
- final DummyBlobData blobData = new DummyBlobData(mContext,
- fileSizeInMb * 1024 * 1024 /* bytes */);
+ final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+ .setFileSize(fileSizeInMb * 1024 * 1024 /* bytes */)
+ .build();
blobData.prepare();
return blobData;
}
diff --git a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
index c458d11..e042782 100644
--- a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
+++ b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
@@ -670,7 +670,7 @@
private void startApp(int userId, String packageName) throws RemoteException {
final Context context = InstrumentationRegistry.getContext();
final WaitResult result = ActivityTaskManager.getService().startActivityAndWait(null,
- context.getPackageName(), context.getFeatureId(),
+ context.getPackageName(), context.getAttributionTag(),
context.getPackageManager().getLaunchIntentForPackage(packageName), null, null,
null, 0, 0, null, null, userId);
attestTrue("User " + userId + " failed to start " + packageName,
diff --git a/apct-tests/perftests/textclassifier/src/android/view/textclassifier/TextClassificationManagerPerfTest.java b/apct-tests/perftests/textclassifier/src/android/view/textclassifier/TextClassificationManagerPerfTest.java
index f61ea85..46250d7 100644
--- a/apct-tests/perftests/textclassifier/src/android/view/textclassifier/TextClassificationManagerPerfTest.java
+++ b/apct-tests/perftests/textclassifier/src/android/view/textclassifier/TextClassificationManagerPerfTest.java
@@ -77,7 +77,6 @@
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
textClassificationManager.getTextClassifier();
- textClassificationManager.invalidateForTesting();
}
}
@@ -90,7 +89,6 @@
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
textClassificationManager.getTextClassifier();
- textClassificationManager.invalidateForTesting();
}
}
diff --git a/apex/Android.bp b/apex/Android.bp
index 051986e..39137fb 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -43,13 +43,15 @@
name: "framework-module-stubs-defaults-publicapi",
args: mainline_stubs_args,
installable: false,
+ sdk_version: "current",
}
stubs_defaults {
name: "framework-module-stubs-defaults-systemapi",
args: mainline_stubs_args + priv_apps,
- srcs: [":framework-annotations"],
+ libs: ["framework-annotations-lib"],
installable: false,
+ sdk_version: "system_current",
}
// The defaults for module_libs comes in two parts - defaults for API checks
@@ -60,13 +62,15 @@
stubs_defaults {
name: "framework-module-api-defaults-module_libs_api",
args: mainline_stubs_args + module_libs,
- srcs: [":framework-annotations"],
+ libs: ["framework-annotations-lib"],
installable: false,
+ sdk_version: "module_current",
}
stubs_defaults {
name: "framework-module-stubs-defaults-module_libs_api",
args: mainline_stubs_args + module_libs + priv_apps,
- srcs: [":framework-annotations"],
+ libs: ["framework-annotations-lib"],
installable: false,
+ sdk_version: "module_current",
}
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/apex/blobstore/framework/java/android/app/blob/BlobInfo.aidl
similarity index 65%
copy from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
copy to apex/blobstore/framework/java/android/app/blob/BlobInfo.aidl
index d691f41..2549773 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/apex/blobstore/framework/java/android/app/blob/BlobInfo.aidl
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright 2020 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.
@@ -13,17 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package android.app.blob;
-package android.net.wifi;
-
-/**
- * Interface for Wi-Fi score callback.
- *
- * @hide
- */
-oneway interface IScoreChangeCallback
-{
- void onScoreChange(int sessionId, int score);
-
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
-}
+/** {@hide} */
+parcelable BlobInfo;
\ No newline at end of file
diff --git a/apex/blobstore/framework/java/android/app/blob/BlobInfo.java b/apex/blobstore/framework/java/android/app/blob/BlobInfo.java
new file mode 100644
index 0000000..80062d5
--- /dev/null
+++ b/apex/blobstore/framework/java/android/app/blob/BlobInfo.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2020 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.app.blob;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Class to provide information about a shared blob.
+ *
+ * @hide
+ */
+public final class BlobInfo implements Parcelable {
+ private final long mId;
+ private final long mExpiryTimeMs;
+ private final CharSequence mLabel;
+ private final List<LeaseInfo> mLeaseInfos;
+
+ public BlobInfo(long id, long expiryTimeMs, CharSequence label,
+ List<LeaseInfo> leaseInfos) {
+ mId = id;
+ mExpiryTimeMs = expiryTimeMs;
+ mLabel = label;
+ mLeaseInfos = leaseInfos;
+ }
+
+ private BlobInfo(Parcel in) {
+ mId = in.readLong();
+ mExpiryTimeMs = in.readLong();
+ mLabel = in.readCharSequence();
+ mLeaseInfos = in.readArrayList(null /* classloader */);
+ }
+
+ public long getId() {
+ return mId;
+ }
+
+ public long getExpiryTimeMs() {
+ return mExpiryTimeMs;
+ }
+
+ public CharSequence getLabel() {
+ return mLabel;
+ }
+
+ public List<LeaseInfo> getLeases() {
+ return Collections.unmodifiableList(mLeaseInfos);
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeLong(mId);
+ dest.writeLong(mExpiryTimeMs);
+ dest.writeCharSequence(mLabel);
+ dest.writeList(mLeaseInfos);
+ }
+
+ @Override
+ public String toString() {
+ return toShortString();
+ }
+
+ private String toShortString() {
+ return "BlobInfo {"
+ + "id: " + mId + ","
+ + "expiryMs: " + mExpiryTimeMs + ","
+ + "label: " + mLabel + ","
+ + "leases: " + LeaseInfo.toShortString(mLeaseInfos) + ","
+ + "}";
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @NonNull
+ public static final Creator<BlobInfo> CREATOR = new Creator<BlobInfo>() {
+ @Override
+ @NonNull
+ public BlobInfo createFromParcel(Parcel source) {
+ return new BlobInfo(source);
+ }
+
+ @Override
+ @NonNull
+ public BlobInfo[] newArray(int size) {
+ return new BlobInfo[size];
+ }
+ };
+}
diff --git a/apex/blobstore/framework/java/android/app/blob/BlobStoreManager.java b/apex/blobstore/framework/java/android/app/blob/BlobStoreManager.java
index f53f1f1..c339351 100644
--- a/apex/blobstore/framework/java/android/app/blob/BlobStoreManager.java
+++ b/apex/blobstore/framework/java/android/app/blob/BlobStoreManager.java
@@ -21,17 +21,21 @@
import android.annotation.IdRes;
import android.annotation.IntRange;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.SystemService;
+import android.annotation.TestApi;
import android.content.Context;
import android.os.ParcelFileDescriptor;
import android.os.ParcelableException;
import android.os.RemoteCallback;
import android.os.RemoteException;
+import android.os.UserHandle;
import com.android.internal.util.function.pooled.PooledLambda;
import java.io.Closeable;
import java.io.IOException;
+import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
@@ -212,7 +216,7 @@
}
/**
- * Delete an existing session and any data that was written to that session so far.
+ * Abandons an existing session and deletes any data that was written to that session so far.
*
* @param sessionId a unique id obtained via {@link #createSession(BlobHandle)} that
* represents a particular session.
@@ -221,9 +225,9 @@
* @throws SecurityException when the caller does not own the session, or
* the session does not exist or is invalid.
*/
- public void deleteSession(@IntRange(from = 1) long sessionId) throws IOException {
+ public void abandonSession(@IntRange(from = 1) long sessionId) throws IOException {
try {
- mService.deleteSession(sessionId, mContext.getOpPackageName());
+ mService.abandonSession(sessionId, mContext.getOpPackageName());
} catch (ParcelableException e) {
e.maybeRethrow(IOException.class);
throw new RuntimeException(e);
@@ -269,6 +273,9 @@
* <p> When an app acquires a lease on a blob, the System will try to keep this
* blob around but note that it can still be deleted if it was requested by the user.
*
+ * <p> In case the resource name for the {@code descriptionResId} is modified as part of
+ * an app update, apps should re-acquire the lease with the new resource id.
+ *
* @param blobHandle the {@link BlobHandle} representing the blob that the caller wants to
* acquire a lease for.
* @param descriptionResId the resource id for a short description string that can be surfaced
@@ -380,6 +387,9 @@
* <p> When an app acquires a lease on a blob, the System will try to keep this
* blob around but note that it can still be deleted if it was requested by the user.
*
+ * <p> In case the resource name for the {@code descriptionResId} is modified as part of
+ * an app update, apps should re-acquire the lease with the new resource id.
+ *
* @param blobHandle the {@link BlobHandle} representing the blob that the caller wants to
* acquire a lease for.
* @param descriptionResId the resource id for a short description string that can be surfaced
@@ -445,13 +455,13 @@
}
/**
- * Release all active leases to the blob represented by {@code blobHandle} which are
+ * Release any active lease to the blob represented by {@code blobHandle} which is
* currently held by the caller.
*
* @param blobHandle the {@link BlobHandle} representing the blob that the caller wants to
- * release the leases for.
+ * release the lease for.
*
- * @throws IOException when there is an I/O error while releasing the releases to the blob.
+ * @throws IOException when there is an I/O error while releasing the release to the blob.
* @throws SecurityException when the blob represented by the {@code blobHandle} does not
* exist or the caller does not have access to it.
* @throws IllegalArgumentException when {@code blobHandle} is invalid.
@@ -472,6 +482,7 @@
*
* @hide
*/
+ @TestApi
public void waitForIdle(long timeoutMillis) throws InterruptedException, TimeoutException {
try {
final CountDownLatch countDownLatch = new CountDownLatch(1);
@@ -486,6 +497,75 @@
}
}
+ /** @hide */
+ @NonNull
+ public List<BlobInfo> queryBlobsForUser(@NonNull UserHandle user) throws IOException {
+ try {
+ return mService.queryBlobsForUser(user.getIdentifier());
+ } catch (ParcelableException e) {
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /** @hide */
+ public void deleteBlob(@NonNull BlobInfo blobInfo) throws IOException {
+ try {
+ mService.deleteBlob(blobInfo.getId());
+ } catch (ParcelableException e) {
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Return the {@link BlobHandle BlobHandles} corresponding to the data blobs that
+ * the calling app has acquired a lease on using {@link #acquireLease(BlobHandle, int)} or
+ * one of it's other variants.
+ *
+ * @hide
+ */
+ @TestApi
+ @NonNull
+ public List<BlobHandle> getLeasedBlobs() throws IOException {
+ try {
+ return mService.getLeasedBlobs(mContext.getOpPackageName());
+ } catch (ParcelableException e) {
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Return {@link LeaseInfo} representing a lease acquired using
+ * {@link #acquireLease(BlobHandle, int)} or one of it's other variants,
+ * or {@code null} if there is no lease acquired.
+ *
+ * @throws SecurityException when the blob represented by the {@code blobHandle} does not
+ * exist or the caller does not have access to it.
+ * @throws IllegalArgumentException when {@code blobHandle} is invalid.
+ *
+ * @hide
+ */
+ @TestApi
+ @Nullable
+ public LeaseInfo getLeaseInfo(@NonNull BlobHandle blobHandle) throws IOException {
+ try {
+ return mService.getLeaseInfo(blobHandle, mContext.getOpPackageName());
+ } catch (ParcelableException e) {
+ e.maybeRethrow(IOException.class);
+ throw new RuntimeException(e);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
/**
* Represents an ongoing session of a blob's contribution to the blob store managed by the
* system.
@@ -590,7 +670,7 @@
/**
* Close this session. It can be re-opened for writing/reading if it has not been
- * abandoned (using {@link #abandon}) or closed (using {@link #commit}).
+ * abandoned (using {@link #abandon}) or committed (using {@link #commit}).
*
* @throws IOException when there is an I/O error while closing the session.
* @throws SecurityException when the caller is not the owner of the session.
diff --git a/apex/blobstore/framework/java/android/app/blob/IBlobStoreManager.aidl b/apex/blobstore/framework/java/android/app/blob/IBlobStoreManager.aidl
index a85a25c..20c15ab 100644
--- a/apex/blobstore/framework/java/android/app/blob/IBlobStoreManager.aidl
+++ b/apex/blobstore/framework/java/android/app/blob/IBlobStoreManager.aidl
@@ -16,7 +16,9 @@
package android.app.blob;
import android.app.blob.BlobHandle;
+import android.app.blob.BlobInfo;
import android.app.blob.IBlobStoreSession;
+import android.app.blob.LeaseInfo;
import android.os.RemoteCallback;
/** {@hide} */
@@ -24,11 +26,17 @@
long createSession(in BlobHandle handle, in String packageName);
IBlobStoreSession openSession(long sessionId, in String packageName);
ParcelFileDescriptor openBlob(in BlobHandle handle, in String packageName);
- void deleteSession(long sessionId, in String packageName);
+ void abandonSession(long sessionId, in String packageName);
void acquireLease(in BlobHandle handle, int descriptionResId, in CharSequence description,
long leaseTimeoutMillis, in String packageName);
void releaseLease(in BlobHandle handle, in String packageName);
void waitForIdle(in RemoteCallback callback);
+
+ List<BlobInfo> queryBlobsForUser(int userId);
+ void deleteBlob(long blobId);
+
+ List<BlobHandle> getLeasedBlobs(in String packageName);
+ LeaseInfo getLeaseInfo(in BlobHandle blobHandle, in String packageName);
}
\ No newline at end of file
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/apex/blobstore/framework/java/android/app/blob/LeaseInfo.aidl
similarity index 65%
copy from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
copy to apex/blobstore/framework/java/android/app/blob/LeaseInfo.aidl
index d691f41..9088857 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/apex/blobstore/framework/java/android/app/blob/LeaseInfo.aidl
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright 2020 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.
@@ -13,17 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package android.app.blob;
-package android.net.wifi;
-
-/**
- * Interface for Wi-Fi score callback.
- *
- * @hide
- */
-oneway interface IScoreChangeCallback
-{
- void onScoreChange(int sessionId, int score);
-
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
-}
+/** {@hide} */
+parcelable LeaseInfo;
\ No newline at end of file
diff --git a/apex/blobstore/framework/java/android/app/blob/LeaseInfo.java b/apex/blobstore/framework/java/android/app/blob/LeaseInfo.java
new file mode 100644
index 0000000..fef50c9
--- /dev/null
+++ b/apex/blobstore/framework/java/android/app/blob/LeaseInfo.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2020 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.app.blob;
+
+import android.annotation.CurrentTimeMillisLong;
+import android.annotation.IdRes;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.TestApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.util.List;
+
+/**
+ * Class to provide information about a lease (acquired using
+ * {@link BlobStoreManager#acquireLease(BlobHandle, int)} or one of it's variants)
+ * for a shared blob.
+ *
+ * @hide
+ */
+@TestApi
+public final class LeaseInfo implements Parcelable {
+ private final String mPackageName;
+ private final long mExpiryTimeMillis;
+ private final int mDescriptionResId;
+ private final CharSequence mDescription;
+
+ public LeaseInfo(@NonNull String packageName, @CurrentTimeMillisLong long expiryTimeMs,
+ @IdRes int descriptionResId, @Nullable CharSequence description) {
+ mPackageName = packageName;
+ mExpiryTimeMillis = expiryTimeMs;
+ mDescriptionResId = descriptionResId;
+ mDescription = description;
+ }
+
+ private LeaseInfo(Parcel in) {
+ mPackageName = in.readString();
+ mExpiryTimeMillis = in.readLong();
+ mDescriptionResId = in.readInt();
+ mDescription = in.readCharSequence();
+ }
+
+ @NonNull
+ public String getPackageName() {
+ return mPackageName;
+ }
+
+ @CurrentTimeMillisLong
+ public long getExpiryTimeMillis() {
+ return mExpiryTimeMillis;
+ }
+
+ @IdRes
+ public int getDescriptionResId() {
+ return mDescriptionResId;
+ }
+
+ @Nullable
+ public CharSequence getDescription() {
+ return mDescription;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeString(mPackageName);
+ dest.writeLong(mExpiryTimeMillis);
+ dest.writeInt(mDescriptionResId);
+ dest.writeCharSequence(mDescription);
+ }
+
+ @Override
+ public String toString() {
+ return "LeaseInfo {"
+ + "package: " + mPackageName + ","
+ + "expiryMs: " + mExpiryTimeMillis + ","
+ + "descriptionResId: " + mDescriptionResId + ","
+ + "description: " + mDescription + ","
+ + "}";
+ }
+
+ private String toShortString() {
+ return mPackageName;
+ }
+
+ static String toShortString(List<LeaseInfo> leaseInfos) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("[");
+ for (int i = 0, size = leaseInfos.size(); i < size; ++i) {
+ sb.append(leaseInfos.get(i).toShortString());
+ sb.append(",");
+ }
+ sb.append("]");
+ return sb.toString();
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @NonNull
+ public static final Creator<LeaseInfo> CREATOR = new Creator<LeaseInfo>() {
+ @Override
+ @NonNull
+ public LeaseInfo createFromParcel(Parcel source) {
+ return new LeaseInfo(source);
+ }
+
+ @Override
+ @NonNull
+ public LeaseInfo[] newArray(int size) {
+ return new LeaseInfo[size];
+ }
+ };
+}
diff --git a/apex/blobstore/framework/java/android/app/blob/XmlTags.java b/apex/blobstore/framework/java/android/app/blob/XmlTags.java
index 9834d74..e64edc3 100644
--- a/apex/blobstore/framework/java/android/app/blob/XmlTags.java
+++ b/apex/blobstore/framework/java/android/app/blob/XmlTags.java
@@ -51,6 +51,6 @@
// For leasee
public static final String TAG_LEASEE = "l";
- public static final String ATTR_DESCRIPTION_RES_ID = "rid";
+ public static final String ATTR_DESCRIPTION_RES_NAME = "rn";
public static final String ATTR_DESCRIPTION = "d";
}
diff --git a/apex/blobstore/service/java/com/android/server/blob/BlobMetadata.java b/apex/blobstore/service/java/com/android/server/blob/BlobMetadata.java
index 4a85a69..8b640ca 100644
--- a/apex/blobstore/service/java/com/android/server/blob/BlobMetadata.java
+++ b/apex/blobstore/service/java/com/android/server/blob/BlobMetadata.java
@@ -16,7 +16,7 @@
package com.android.server.blob;
import static android.app.blob.XmlTags.ATTR_DESCRIPTION;
-import static android.app.blob.XmlTags.ATTR_DESCRIPTION_RES_ID;
+import static android.app.blob.XmlTags.ATTR_DESCRIPTION_RES_NAME;
import static android.app.blob.XmlTags.ATTR_EXPIRY_TIME;
import static android.app.blob.XmlTags.ATTR_ID;
import static android.app.blob.XmlTags.ATTR_PACKAGE;
@@ -30,13 +30,16 @@
import static android.system.OsConstants.O_RDONLY;
import static com.android.server.blob.BlobStoreConfig.TAG;
+import static com.android.server.blob.BlobStoreConfig.XML_VERSION_ADD_DESC_RES_NAME;
import static com.android.server.blob.BlobStoreConfig.XML_VERSION_ADD_STRING_DESC;
+import static com.android.server.blob.BlobStoreUtils.getDescriptionResourceId;
+import static com.android.server.blob.BlobStoreUtils.getPackageResources;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.blob.BlobHandle;
+import android.app.blob.LeaseInfo;
import android.content.Context;
-import android.content.pm.PackageManager;
import android.content.res.ResourceId;
import android.content.res.Resources;
import android.os.ParcelFileDescriptor;
@@ -62,6 +65,7 @@
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.Objects;
+import java.util.function.Consumer;
class BlobMetadata {
private final Object mMetadataLock = new Object();
@@ -154,7 +158,7 @@
synchronized (mMetadataLock) {
// We need to override the leasee data, so first remove any existing
// leasee before adding the new one.
- final Leasee leasee = new Leasee(callingPackage, callingUid,
+ final Leasee leasee = new Leasee(mContext, callingPackage, callingUid,
descriptionResId, description, leaseExpiryTimeMillis);
mLeasees.remove(leasee);
mLeasees.add(leasee);
@@ -239,7 +243,7 @@
return hasOtherLeasees(null, uid);
}
- private boolean isALeasee(@Nullable String packageName, int uid) {
+ boolean isALeasee(@Nullable String packageName, int uid) {
synchronized (mMetadataLock) {
// Check if the package is a leasee of the data blob.
for (int i = 0, size = mLeasees.size(); i < size; ++i) {
@@ -278,6 +282,29 @@
return false;
}
+ @Nullable
+ LeaseInfo getLeaseInfo(@NonNull String packageName, int uid) {
+ synchronized (mMetadataLock) {
+ for (int i = 0, size = mLeasees.size(); i < size; ++i) {
+ final Leasee leasee = mLeasees.valueAt(i);
+ if (leasee.uid == uid && leasee.packageName.equals(packageName)) {
+ final int descriptionResId = leasee.descriptionResEntryName == null
+ ? Resources.ID_NULL
+ : BlobStoreUtils.getDescriptionResourceId(
+ mContext, leasee.descriptionResEntryName, leasee.packageName,
+ UserHandle.getUserId(leasee.uid));
+ return new LeaseInfo(packageName, leasee.expiryTimeMillis,
+ descriptionResId, leasee.description);
+ }
+ }
+ }
+ return null;
+ }
+
+ void forEachLeasee(Consumer<Leasee> consumer) {
+ mLeasees.forEach(consumer);
+ }
+
File getBlobFile() {
if (mBlobFile == null) {
mBlobFile = BlobStoreConfig.getBlobFile(mBlobId);
@@ -459,59 +486,103 @@
}
static final class Leasee extends Accessor {
- public final int descriptionResId;
+ public final String descriptionResEntryName;
public final CharSequence description;
public final long expiryTimeMillis;
- Leasee(String packageName, int uid, int descriptionResId, CharSequence description,
- long expiryTimeMillis) {
+ Leasee(@NonNull Context context, @NonNull String packageName,
+ int uid, int descriptionResId,
+ @Nullable CharSequence description, long expiryTimeMillis) {
super(packageName, uid);
- this.descriptionResId = descriptionResId;
+ final Resources packageResources = getPackageResources(context, packageName,
+ UserHandle.getUserId(uid));
+ this.descriptionResEntryName = getResourceEntryName(packageResources, descriptionResId);
+ this.expiryTimeMillis = expiryTimeMillis;
+ this.description = description == null
+ ? getDescription(packageResources, descriptionResId)
+ : description;
+ }
+
+ Leasee(String packageName, int uid, @Nullable String descriptionResEntryName,
+ @Nullable CharSequence description, long expiryTimeMillis) {
+ super(packageName, uid);
+ this.descriptionResEntryName = descriptionResEntryName;
this.expiryTimeMillis = expiryTimeMillis;
this.description = description;
}
+ @Nullable
+ private static String getResourceEntryName(@Nullable Resources packageResources,
+ int resId) {
+ if (!ResourceId.isValid(resId) || packageResources == null) {
+ return null;
+ }
+ return packageResources.getResourceEntryName(resId);
+ }
+
+ @Nullable
+ private static String getDescription(@NonNull Context context,
+ @NonNull String descriptionResEntryName, @NonNull String packageName, int userId) {
+ if (descriptionResEntryName == null || descriptionResEntryName.isEmpty()) {
+ return null;
+ }
+ final Resources resources = getPackageResources(context, packageName, userId);
+ if (resources == null) {
+ return null;
+ }
+ final int resId = getDescriptionResourceId(resources, descriptionResEntryName,
+ packageName);
+ return resId == Resources.ID_NULL ? null : resources.getString(resId);
+ }
+
+ @Nullable
+ private static String getDescription(@Nullable Resources packageResources,
+ int descriptionResId) {
+ if (!ResourceId.isValid(descriptionResId) || packageResources == null) {
+ return null;
+ }
+ return packageResources.getString(descriptionResId);
+ }
+
boolean isStillValid() {
return expiryTimeMillis == 0 || expiryTimeMillis <= System.currentTimeMillis();
}
- void dump(Context context, IndentingPrintWriter fout) {
+ void dump(@NonNull Context context, @NonNull IndentingPrintWriter fout) {
fout.println("desc: " + getDescriptionToDump(context));
fout.println("expiryMs: " + expiryTimeMillis);
}
- private String getDescriptionToDump(Context context) {
- String desc = null;
- if (ResourceId.isValid(descriptionResId)) {
- try {
- final Resources leaseeRes = context.getPackageManager()
- .getResourcesForApplicationAsUser(
- packageName, UserHandle.getUserId(uid));
- desc = leaseeRes.getString(descriptionResId);
- } catch (PackageManager.NameNotFoundException e) {
- Slog.d(TAG, "Unknown package in user " + UserHandle.getUserId(uid) + ": "
- + packageName, e);
- desc = "<none>";
- }
- } else {
+ @NonNull
+ private String getDescriptionToDump(@NonNull Context context) {
+ String desc = getDescription(context, descriptionResEntryName, packageName,
+ UserHandle.getUserId(uid));
+ if (desc == null) {
desc = description.toString();
}
- return desc;
+ return desc == null ? "<none>" : desc;
}
void writeToXml(@NonNull XmlSerializer out) throws IOException {
XmlUtils.writeStringAttribute(out, ATTR_PACKAGE, packageName);
XmlUtils.writeIntAttribute(out, ATTR_UID, uid);
- XmlUtils.writeIntAttribute(out, ATTR_DESCRIPTION_RES_ID, descriptionResId);
+ XmlUtils.writeStringAttribute(out, ATTR_DESCRIPTION_RES_NAME, descriptionResEntryName);
XmlUtils.writeLongAttribute(out, ATTR_EXPIRY_TIME, expiryTimeMillis);
XmlUtils.writeStringAttribute(out, ATTR_DESCRIPTION, description);
}
@NonNull
- static Leasee createFromXml(@NonNull XmlPullParser in, int version) throws IOException {
+ static Leasee createFromXml(@NonNull XmlPullParser in, int version)
+ throws IOException {
final String packageName = XmlUtils.readStringAttribute(in, ATTR_PACKAGE);
final int uid = XmlUtils.readIntAttribute(in, ATTR_UID);
- final int descriptionResId = XmlUtils.readIntAttribute(in, ATTR_DESCRIPTION_RES_ID);
+ final String descriptionResEntryName;
+ if (version >= XML_VERSION_ADD_DESC_RES_NAME) {
+ descriptionResEntryName = XmlUtils.readStringAttribute(
+ in, ATTR_DESCRIPTION_RES_NAME);
+ } else {
+ descriptionResEntryName = null;
+ }
final long expiryTimeMillis = XmlUtils.readLongAttribute(in, ATTR_EXPIRY_TIME);
final CharSequence description;
if (version >= XML_VERSION_ADD_STRING_DESC) {
@@ -520,7 +591,8 @@
description = null;
}
- return new Leasee(packageName, uid, descriptionResId, description, expiryTimeMillis);
+ return new Leasee(packageName, uid, descriptionResEntryName,
+ description, expiryTimeMillis);
}
}
diff --git a/apex/blobstore/service/java/com/android/server/blob/BlobStoreConfig.java b/apex/blobstore/service/java/com/android/server/blob/BlobStoreConfig.java
index bcc1610..5e8ea7a 100644
--- a/apex/blobstore/service/java/com/android/server/blob/BlobStoreConfig.java
+++ b/apex/blobstore/service/java/com/android/server/blob/BlobStoreConfig.java
@@ -15,12 +15,23 @@
*/
package com.android.server.blob;
+import static android.provider.DeviceConfig.NAMESPACE_BLOBSTORE;
+import static android.text.format.Formatter.FLAG_IEC_UNITS;
+import static android.text.format.Formatter.formatFileSize;
+import static android.util.TimeUtils.formatDuration;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.content.Context;
import android.os.Environment;
+import android.provider.DeviceConfig;
+import android.provider.DeviceConfig.Properties;
+import android.util.DataUnit;
import android.util.Log;
import android.util.Slog;
+import com.android.internal.util.IndentingPrintWriter;
+
import java.io.File;
import java.util.concurrent.TimeUnit;
@@ -32,8 +43,9 @@
public static final int XML_VERSION_INIT = 1;
// Added a string variant of lease description.
public static final int XML_VERSION_ADD_STRING_DESC = 2;
+ public static final int XML_VERSION_ADD_DESC_RES_NAME = 3;
- public static final int XML_VERSION_CURRENT = XML_VERSION_ADD_STRING_DESC;
+ public static final int XML_VERSION_CURRENT = XML_VERSION_ADD_DESC_RES_NAME;
private static final String ROOT_DIR_NAME = "blobstore";
private static final String BLOBS_DIR_NAME = "blobs";
@@ -54,6 +66,76 @@
*/
public static final long SESSION_EXPIRY_TIMEOUT_MILLIS = TimeUnit.DAYS.toMillis(7);
+ public static class DeviceConfigProperties {
+ /**
+ * Denotes how low the limit for the amount of data, that an app will be allowed to acquire
+ * a lease on, can be.
+ */
+ public static final String KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR =
+ "total_bytes_per_app_limit_floor";
+ public static final long DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FLOOR =
+ DataUnit.MEBIBYTES.toBytes(300); // 300 MiB
+ public static long TOTAL_BYTES_PER_APP_LIMIT_FLOOR =
+ DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FLOOR;
+
+ /**
+ * Denotes the maximum amount of data an app can acquire a lease on, in terms of fraction
+ * of total disk space.
+ */
+ public static final String KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION =
+ "total_bytes_per_app_limit_fraction";
+ public static final float DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FRACTION = 0.01f;
+ public static float TOTAL_BYTES_PER_APP_LIMIT_FRACTION =
+ DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FRACTION;
+
+ static void refresh(Properties properties) {
+ if (!NAMESPACE_BLOBSTORE.equals(properties.getNamespace())) {
+ return;
+ }
+ properties.getKeyset().forEach(key -> {
+ switch (key) {
+ case KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR:
+ TOTAL_BYTES_PER_APP_LIMIT_FLOOR = properties.getLong(key,
+ DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FLOOR);
+ break;
+ case KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION:
+ TOTAL_BYTES_PER_APP_LIMIT_FRACTION = properties.getFloat(key,
+ DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FRACTION);
+ break;
+ default:
+ Slog.wtf(TAG, "Unknown key in device config properties: " + key);
+ }
+ });
+ }
+
+ static void dump(IndentingPrintWriter fout, Context context) {
+ final String dumpFormat = "%s: [cur: %s, def: %s]";
+ fout.println(String.format(dumpFormat, KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR,
+ formatFileSize(context, TOTAL_BYTES_PER_APP_LIMIT_FLOOR, FLAG_IEC_UNITS),
+ formatFileSize(context, DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FLOOR,
+ FLAG_IEC_UNITS)));
+ fout.println(String.format(dumpFormat, KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION,
+ TOTAL_BYTES_PER_APP_LIMIT_FRACTION,
+ DEFAULT_TOTAL_BYTES_PER_APP_LIMIT_FRACTION));
+ }
+ }
+
+ public static void initialize(Context context) {
+ DeviceConfig.addOnPropertiesChangedListener(NAMESPACE_BLOBSTORE,
+ context.getMainExecutor(),
+ properties -> DeviceConfigProperties.refresh(properties));
+ DeviceConfigProperties.refresh(DeviceConfig.getProperties(NAMESPACE_BLOBSTORE));
+ }
+
+ /**
+ * Returns the maximum amount of data that an app can acquire a lease on.
+ */
+ public static long getAppDataBytesLimit() {
+ final long totalBytesLimit = (long) (Environment.getDataSystemDirectory().getTotalSpace()
+ * DeviceConfigProperties.TOTAL_BYTES_PER_APP_LIMIT_FRACTION);
+ return Math.max(DeviceConfigProperties.TOTAL_BYTES_PER_APP_LIMIT_FLOOR, totalBytesLimit);
+ }
+
@Nullable
public static File prepareBlobFile(long sessionId) {
final File blobsDir = prepareBlobsDir();
@@ -122,4 +204,21 @@
public static File getBlobStoreRootDir() {
return new File(Environment.getDataSystemDirectory(), ROOT_DIR_NAME);
}
+
+ public static void dump(IndentingPrintWriter fout, Context context) {
+ fout.println("XML current version: " + XML_VERSION_CURRENT);
+
+ fout.println("Idle job ID: " + IDLE_JOB_ID);
+ fout.println("Idle job period: " + formatDuration(IDLE_JOB_PERIOD_MILLIS));
+
+ fout.println("Session expiry timeout: " + formatDuration(SESSION_EXPIRY_TIMEOUT_MILLIS));
+
+ fout.println("Total bytes per app limit: " + formatFileSize(context,
+ getAppDataBytesLimit(), FLAG_IEC_UNITS));
+
+ fout.println("Device config properties:");
+ fout.increaseIndent();
+ DeviceConfigProperties.dump(fout, context);
+ fout.decreaseIndent();
+ }
}
diff --git a/apex/blobstore/service/java/com/android/server/blob/BlobStoreManagerService.java b/apex/blobstore/service/java/com/android/server/blob/BlobStoreManagerService.java
index 49adaa8..f4b8f0f 100644
--- a/apex/blobstore/service/java/com/android/server/blob/BlobStoreManagerService.java
+++ b/apex/blobstore/service/java/com/android/server/blob/BlobStoreManagerService.java
@@ -36,6 +36,8 @@
import static com.android.server.blob.BlobStoreSession.STATE_VERIFIED_INVALID;
import static com.android.server.blob.BlobStoreSession.STATE_VERIFIED_VALID;
import static com.android.server.blob.BlobStoreSession.stateToString;
+import static com.android.server.blob.BlobStoreUtils.getDescriptionResourceId;
+import static com.android.server.blob.BlobStoreUtils.getPackageResources;
import android.annotation.CurrentTimeSecondsLong;
import android.annotation.IdRes;
@@ -44,8 +46,10 @@
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.app.blob.BlobHandle;
+import android.app.blob.BlobInfo;
import android.app.blob.IBlobStoreManager;
import android.app.blob.IBlobStoreSession;
+import android.app.blob.LeaseInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -54,6 +58,7 @@
import android.content.pm.PackageManagerInternal;
import android.content.pm.PackageStats;
import android.content.res.ResourceId;
+import android.content.res.Resources;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
@@ -99,6 +104,7 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
+import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
@@ -109,6 +115,7 @@
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
+import java.util.function.Function;
/**
* Service responsible for maintaining and facilitating access to data blobs published by apps.
@@ -187,7 +194,9 @@
@Override
public void onBootPhase(int phase) {
- if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
+ if (phase == PHASE_ACTIVITY_MANAGER_READY) {
+ BlobStoreConfig.initialize(mContext);
+ } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
synchronized (mBlobsLock) {
final SparseArray<SparseArray<String>> allPackages = getAllPackages();
readBlobSessionsLocked(allPackages);
@@ -213,12 +222,17 @@
}
private void registerReceivers() {
- final IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
- intentFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
- intentFilter.addAction(Intent.ACTION_USER_REMOVED);
+ final IntentFilter packageChangedFilter = new IntentFilter();
+ packageChangedFilter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
+ packageChangedFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
+ packageChangedFilter.addDataScheme("package");
mContext.registerReceiverAsUser(new PackageChangedReceiver(), UserHandle.ALL,
- intentFilter, null, mHandler);
+ packageChangedFilter, null, mHandler);
+
+ final IntentFilter userActionFilter = new IntentFilter();
+ userActionFilter.addAction(Intent.ACTION_USER_REMOVED);
+ mContext.registerReceiverAsUser(new UserActionReceiver(), UserHandle.ALL,
+ userActionFilter, null, mHandler);
}
@GuardedBy("mBlobsLock")
@@ -335,7 +349,7 @@
return session;
}
- private void deleteSessionInternal(long sessionId,
+ private void abandonSessionInternal(long sessionId,
int callingUid, String callingPackage) {
synchronized (mBlobsLock) {
final BlobStoreSession session = openSessionInternal(sessionId,
@@ -343,7 +357,7 @@
session.open();
session.abandon();
if (LOGV) {
- Slog.v(TAG, "Deleted session with id " + sessionId
+ Slog.v(TAG, "Abandoned session with id " + sessionId
+ "; callingUid=" + callingUid + ", callingPackage=" + callingPackage);
}
writeBlobSessionsAsync();
@@ -380,6 +394,11 @@
throw new IllegalArgumentException(
"Lease expiry cannot be later than blobs expiry time");
}
+ if (getTotalUsageBytesLocked(callingUid, callingPackage)
+ + blobMetadata.getSize() > BlobStoreConfig.getAppDataBytesLimit()) {
+ throw new IllegalStateException("Total amount of data with an active lease"
+ + " is exceeding the max limit");
+ }
blobMetadata.addLeasee(callingPackage, callingUid,
descriptionResId, description, leaseExpiryTimeMillis);
if (LOGV) {
@@ -390,6 +409,18 @@
}
}
+ @VisibleForTesting
+ @GuardedBy("mBlobsLock")
+ long getTotalUsageBytesLocked(int callingUid, String callingPackage) {
+ final AtomicLong totalBytes = new AtomicLong(0);
+ forEachBlobInUser((blobMetadata) -> {
+ if (blobMetadata.isALeasee(callingPackage, callingUid)) {
+ totalBytes.getAndAdd(blobMetadata.getSize());
+ }
+ }, UserHandle.getUserId(callingUid));
+ return totalBytes.get();
+ }
+
private void releaseLeaseInternal(BlobHandle blobHandle, int callingUid,
String callingPackage) {
synchronized (mBlobsLock) {
@@ -409,6 +440,73 @@
}
}
+ private List<BlobInfo> queryBlobsForUserInternal(int userId) {
+ final ArrayList<BlobInfo> blobInfos = new ArrayList<>();
+ synchronized (mBlobsLock) {
+ final ArrayMap<String, WeakReference<Resources>> resources = new ArrayMap<>();
+ final Function<String, Resources> resourcesGetter = (packageName) -> {
+ final WeakReference<Resources> resourcesRef = resources.get(packageName);
+ Resources packageResources = resourcesRef == null ? null : resourcesRef.get();
+ if (packageResources == null) {
+ packageResources = getPackageResources(mContext, packageName, userId);
+ resources.put(packageName, new WeakReference<>(packageResources));
+ }
+ return packageResources;
+ };
+ getUserBlobsLocked(userId).forEach((blobHandle, blobMetadata) -> {
+ final ArrayList<LeaseInfo> leaseInfos = new ArrayList<>();
+ blobMetadata.forEachLeasee(leasee -> {
+ final int descriptionResId = leasee.descriptionResEntryName == null
+ ? Resources.ID_NULL
+ : getDescriptionResourceId(resourcesGetter.apply(leasee.packageName),
+ leasee.descriptionResEntryName, leasee.packageName);
+ leaseInfos.add(new LeaseInfo(leasee.packageName, leasee.expiryTimeMillis,
+ descriptionResId, leasee.description));
+ });
+ blobInfos.add(new BlobInfo(blobMetadata.getBlobId(),
+ blobHandle.getExpiryTimeMillis(), blobHandle.getLabel(), leaseInfos));
+ });
+ }
+ return blobInfos;
+ }
+
+ private void deleteBlobInternal(long blobId, int callingUid) {
+ synchronized (mBlobsLock) {
+ final ArrayMap<BlobHandle, BlobMetadata> userBlobs = getUserBlobsLocked(
+ UserHandle.getUserId(callingUid));
+ userBlobs.entrySet().removeIf(entry -> {
+ final BlobMetadata blobMetadata = entry.getValue();
+ return blobMetadata.getBlobId() == blobId;
+ });
+ writeBlobsInfoAsync();
+ }
+ }
+
+ private List<BlobHandle> getLeasedBlobsInternal(int callingUid,
+ @NonNull String callingPackage) {
+ final ArrayList<BlobHandle> leasedBlobs = new ArrayList<>();
+ forEachBlobInUser(blobMetadata -> {
+ if (blobMetadata.isALeasee(callingPackage, callingUid)) {
+ leasedBlobs.add(blobMetadata.getBlobHandle());
+ }
+ }, UserHandle.getUserId(callingUid));
+ return leasedBlobs;
+ }
+
+ private LeaseInfo getLeaseInfoInternal(BlobHandle blobHandle,
+ int callingUid, @NonNull String callingPackage) {
+ synchronized (mBlobsLock) {
+ final BlobMetadata blobMetadata = getUserBlobsLocked(UserHandle.getUserId(callingUid))
+ .get(blobHandle);
+ if (blobMetadata == null || !blobMetadata.isAccessAllowedForCaller(
+ callingPackage, callingUid)) {
+ throw new SecurityException("Caller not allowed to access " + blobHandle
+ + "; callingUid=" + callingUid + ", callingPackage=" + callingPackage);
+ }
+ return blobMetadata.getLeaseInfo(callingPackage, callingUid);
+ }
+ }
+
private void verifyCallingPackage(int callingUid, String callingPackage) {
if (mPackageManagerInternal.getPackageUid(
callingPackage, 0, UserHandle.getUserId(callingUid)) != callingUid) {
@@ -749,40 +847,34 @@
// Clean up any pending sessions
final LongSparseArray<BlobStoreSession> userSessions =
getUserSessionsLocked(UserHandle.getUserId(uid));
- final ArrayList<Integer> indicesToRemove = new ArrayList<>();
- for (int i = 0, count = userSessions.size(); i < count; ++i) {
- final BlobStoreSession session = userSessions.valueAt(i);
- if (session.getOwnerUid() == uid
- && session.getOwnerPackageName().equals(packageName)) {
- session.getSessionFile().delete();
- mActiveBlobIds.remove(session.getSessionId());
- indicesToRemove.add(i);
+ userSessions.removeIf((sessionId, blobStoreSession) -> {
+ if (blobStoreSession.getOwnerUid() == uid
+ && blobStoreSession.getOwnerPackageName().equals(packageName)) {
+ blobStoreSession.getSessionFile().delete();
+ mActiveBlobIds.remove(blobStoreSession.getSessionId());
+ return true;
}
- }
- for (int i = 0, count = indicesToRemove.size(); i < count; ++i) {
- userSessions.removeAt(indicesToRemove.get(i));
- }
+ return false;
+ });
writeBlobSessionsAsync();
// Remove the package from the committer and leasee list
final ArrayMap<BlobHandle, BlobMetadata> userBlobs =
getUserBlobsLocked(UserHandle.getUserId(uid));
- indicesToRemove.clear();
- for (int i = 0, count = userBlobs.size(); i < count; ++i) {
- final BlobMetadata blobMetadata = userBlobs.valueAt(i);
+ userBlobs.entrySet().removeIf(entry -> {
+ final BlobMetadata blobMetadata = entry.getValue();
blobMetadata.removeCommitter(packageName, uid);
blobMetadata.removeLeasee(packageName, uid);
// Delete the blob if it doesn't have any active leases.
if (!blobMetadata.hasLeases()) {
blobMetadata.getBlobFile().delete();
mActiveBlobIds.remove(blobMetadata.getBlobId());
- indicesToRemove.add(i);
+ return true;
}
- }
- for (int i = 0, count = indicesToRemove.size(); i < count; ++i) {
- userBlobs.removeAt(indicesToRemove.get(i));
- }
+ return false;
+ });
writeBlobsInfoAsync();
+
if (LOGV) {
Slog.v(TAG, "Removed blobs data associated with pkg="
+ packageName + ", uid=" + uid);
@@ -1083,6 +1175,19 @@
}
handlePackageRemoved(packageName, uid);
break;
+ default:
+ Slog.wtf(TAG, "Received unknown intent: " + intent);
+ }
+ }
+ }
+
+ private class UserActionReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (LOGV) {
+ Slog.v(TAG, "Received: " + intent);
+ }
+ switch (intent.getAction()) {
case Intent.ACTION_USER_REMOVED:
final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
USER_NULL);
@@ -1135,7 +1240,7 @@
}
@Override
- public void deleteSession(@IntRange(from = 1) long sessionId,
+ public void abandonSession(@IntRange(from = 1) long sessionId,
@NonNull String packageName) {
Preconditions.checkArgumentPositive(sessionId,
"sessionId must be positive: " + sessionId);
@@ -1144,7 +1249,7 @@
final int callingUid = Binder.getCallingUid();
verifyCallingPackage(callingUid, packageName);
- deleteSessionInternal(sessionId, callingUid, packageName);
+ abandonSessionInternal(sessionId, callingUid, packageName);
}
@Override
@@ -1187,8 +1292,18 @@
final int callingUid = Binder.getCallingUid();
verifyCallingPackage(callingUid, packageName);
- acquireLeaseInternal(blobHandle, descriptionResId, description, leaseExpiryTimeMillis,
- callingUid, packageName);
+ if (Process.isIsolated(callingUid) || mPackageManagerInternal.isInstantApp(
+ packageName, UserHandle.getUserId(callingUid))) {
+ throw new SecurityException("Caller not allowed to open blob; "
+ + "callingUid=" + callingUid + ", callingPackage=" + packageName);
+ }
+
+ try {
+ acquireLeaseInternal(blobHandle, descriptionResId, description,
+ leaseExpiryTimeMillis, callingUid, packageName);
+ } catch (Resources.NotFoundException e) {
+ throw new IllegalArgumentException(e);
+ }
}
@Override
@@ -1200,6 +1315,12 @@
final int callingUid = Binder.getCallingUid();
verifyCallingPackage(callingUid, packageName);
+ if (Process.isIsolated(callingUid) || mPackageManagerInternal.isInstantApp(
+ packageName, UserHandle.getUserId(callingUid))) {
+ throw new SecurityException("Caller not allowed to open blob; "
+ + "callingUid=" + callingUid + ", callingPackage=" + packageName);
+ }
+
releaseLeaseInternal(blobHandle, callingUid, packageName);
}
@@ -1214,6 +1335,58 @@
}
@Override
+ @NonNull
+ public List<BlobInfo> queryBlobsForUser(@UserIdInt int userId) {
+ if (Binder.getCallingUid() != Process.SYSTEM_UID) {
+ throw new SecurityException("Only system uid is allowed to call "
+ + "queryBlobsForUser()");
+ }
+
+ return queryBlobsForUserInternal(userId);
+ }
+
+ @Override
+ public void deleteBlob(long blobId) {
+ final int callingUid = Binder.getCallingUid();
+ if (callingUid != Process.SYSTEM_UID) {
+ throw new SecurityException("Only system uid is allowed to call "
+ + "deleteBlob()");
+ }
+
+ deleteBlobInternal(blobId, callingUid);
+ }
+
+ @Override
+ @NonNull
+ public List<BlobHandle> getLeasedBlobs(@NonNull String packageName) {
+ Objects.requireNonNull(packageName, "packageName must not be null");
+
+ final int callingUid = Binder.getCallingUid();
+ verifyCallingPackage(callingUid, packageName);
+
+ return getLeasedBlobsInternal(callingUid, packageName);
+ }
+
+ @Override
+ @Nullable
+ public LeaseInfo getLeaseInfo(@NonNull BlobHandle blobHandle, @NonNull String packageName) {
+ Objects.requireNonNull(blobHandle, "blobHandle must not be null");
+ blobHandle.assertIsValid();
+ Objects.requireNonNull(packageName, "packageName must not be null");
+
+ final int callingUid = Binder.getCallingUid();
+ verifyCallingPackage(callingUid, packageName);
+
+ if (Process.isIsolated(callingUid) || mPackageManagerInternal.isInstantApp(
+ packageName, UserHandle.getUserId(callingUid))) {
+ throw new SecurityException("Caller not allowed to open blob; "
+ + "callingUid=" + callingUid + ", callingPackage=" + packageName);
+ }
+
+ return getLeaseInfoInternal(blobHandle, callingUid, packageName);
+ }
+
+ @Override
public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
@Nullable String[] args) {
// TODO: add proto-based version of this.
@@ -1231,8 +1404,10 @@
}
synchronized (mBlobsLock) {
- fout.println("mCurrentMaxSessionId: " + mCurrentMaxSessionId);
- fout.println();
+ if (dumpArgs.shouldDumpAllSections()) {
+ fout.println("mCurrentMaxSessionId: " + mCurrentMaxSessionId);
+ fout.println();
+ }
if (dumpArgs.shouldDumpSessions()) {
dumpSessionsLocked(fout, dumpArgs);
@@ -1243,6 +1418,14 @@
fout.println();
}
}
+
+ if (dumpArgs.shouldDumpConfig()) {
+ fout.println("BlobStore config:");
+ fout.increaseIndent();
+ BlobStoreConfig.dump(fout, mContext);
+ fout.decreaseIndent();
+ fout.println();
+ }
}
@Override
@@ -1255,14 +1438,16 @@
}
static final class DumpArgs {
+ private static final int FLAG_DUMP_SESSIONS = 1 << 0;
+ private static final int FLAG_DUMP_BLOBS = 1 << 1;
+ private static final int FLAG_DUMP_CONFIG = 1 << 2;
+
+ private int mSelectedSectionFlags;
private boolean mDumpFull;
private final ArrayList<String> mDumpPackages = new ArrayList<>();
private final ArrayList<Integer> mDumpUids = new ArrayList<>();
private final ArrayList<Integer> mDumpUserIds = new ArrayList<>();
private final ArrayList<Long> mDumpBlobIds = new ArrayList<>();
- private boolean mDumpOnlySelectedSections;
- private boolean mDumpSessions;
- private boolean mDumpBlobs;
private boolean mDumpHelp;
public boolean shouldDumpSession(String packageName, int uid, long blobId) {
@@ -1281,18 +1466,41 @@
return true;
}
+ public boolean shouldDumpAllSections() {
+ return mSelectedSectionFlags == 0;
+ }
+
+ public void allowDumpSessions() {
+ mSelectedSectionFlags |= FLAG_DUMP_SESSIONS;
+ }
+
public boolean shouldDumpSessions() {
- if (!mDumpOnlySelectedSections) {
+ if (shouldDumpAllSections()) {
return true;
}
- return mDumpSessions;
+ return (mSelectedSectionFlags & FLAG_DUMP_SESSIONS) != 0;
+ }
+
+ public void allowDumpBlobs() {
+ mSelectedSectionFlags |= FLAG_DUMP_BLOBS;
}
public boolean shouldDumpBlobs() {
- if (!mDumpOnlySelectedSections) {
+ if (shouldDumpAllSections()) {
return true;
}
- return mDumpBlobs;
+ return (mSelectedSectionFlags & FLAG_DUMP_BLOBS) != 0;
+ }
+
+ public void allowDumpConfig() {
+ mSelectedSectionFlags |= FLAG_DUMP_CONFIG;
+ }
+
+ public boolean shouldDumpConfig() {
+ if (shouldDumpAllSections()) {
+ return true;
+ }
+ return (mSelectedSectionFlags & FLAG_DUMP_CONFIG) != 0;
}
public boolean shouldDumpBlob(long blobId) {
@@ -1329,11 +1537,11 @@
dumpArgs.mDumpFull = true;
}
} else if ("--sessions".equals(opt)) {
- dumpArgs.mDumpOnlySelectedSections = true;
- dumpArgs.mDumpSessions = true;
+ dumpArgs.allowDumpSessions();
} else if ("--blobs".equals(opt)) {
- dumpArgs.mDumpOnlySelectedSections = true;
- dumpArgs.mDumpBlobs = true;
+ dumpArgs.allowDumpBlobs();
+ } else if ("--config".equals(opt)) {
+ dumpArgs.allowDumpConfig();
} else if ("--package".equals(opt) || "-p".equals(opt)) {
dumpArgs.mDumpPackages.add(getStringArgRequired(args, ++i, "packageName"));
} else if ("--uid".equals(opt) || "-u".equals(opt)) {
@@ -1392,6 +1600,8 @@
printWithIndent(pw, "Dump only the sessions info");
pw.println("--blobs");
printWithIndent(pw, "Dump only the committed blobs info");
+ pw.println("--config");
+ printWithIndent(pw, "Dump only the config values");
pw.println("--package | -p [package-name]");
printWithIndent(pw, "Dump blobs info associated with the given package");
pw.println("--uid | -u [uid]");
diff --git a/apex/blobstore/service/java/com/android/server/blob/BlobStoreUtils.java b/apex/blobstore/service/java/com/android/server/blob/BlobStoreUtils.java
new file mode 100644
index 0000000..fabce76
--- /dev/null
+++ b/apex/blobstore/service/java/com/android/server/blob/BlobStoreUtils.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2020 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.blob;
+
+import static com.android.server.blob.BlobStoreConfig.TAG;
+
+import android.annotation.IdRes;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.util.Slog;
+
+class BlobStoreUtils {
+ private static final String DESC_RES_TYPE_STRING = "string";
+
+ @Nullable
+ static Resources getPackageResources(@NonNull Context context,
+ @NonNull String packageName, int userId) {
+ try {
+ return context.getPackageManager()
+ .getResourcesForApplicationAsUser(packageName, userId);
+ } catch (PackageManager.NameNotFoundException e) {
+ Slog.d(TAG, "Unknown package in user " + userId + ": "
+ + packageName, e);
+ return null;
+ }
+ }
+
+ @IdRes
+ static int getDescriptionResourceId(@NonNull Resources resources,
+ @NonNull String resourceEntryName, @NonNull String packageName) {
+ return resources.getIdentifier(resourceEntryName, DESC_RES_TYPE_STRING, packageName);
+ }
+
+ @IdRes
+ static int getDescriptionResourceId(@NonNull Context context,
+ @NonNull String resourceEntryName, @NonNull String packageName, int userId) {
+ final Resources resources = getPackageResources(context, packageName, userId);
+ return resources == null
+ ? Resources.ID_NULL
+ : getDescriptionResourceId(resources, resourceEntryName, packageName);
+ }
+}
diff --git a/apex/jobscheduler/framework/java/android/app/job/JobInfo.java b/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
index b905273..ae8976a 100644
--- a/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
+++ b/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
@@ -53,9 +53,8 @@
* Container of data passed to the {@link android.app.job.JobScheduler} fully encapsulating the
* parameters required to schedule work against the calling application. These are constructed
* using the {@link JobInfo.Builder}.
- * You must specify at least one sort of constraint on the JobInfo object that you are creating.
* The goal here is to provide the scheduler with high-level semantics about the work you want to
- * accomplish. Doing otherwise with throw an exception in your app.
+ * accomplish.
*/
public class JobInfo implements Parcelable {
private static String TAG = "JobInfo";
@@ -147,7 +146,7 @@
/**
* Query the minimum interval allowed for periodic scheduled jobs. Attempting
- * to declare a smaller period that this when scheduling a job will result in a
+ * to declare a smaller period than this when scheduling a job will result in a
* job that is still periodic, but will run with this effective period.
*
* @return The minimum available interval for scheduling periodic jobs, in milliseconds.
diff --git a/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java b/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java
index f8b598a..6d9e3ed 100644
--- a/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java
+++ b/apex/jobscheduler/framework/java/com/android/server/usage/AppStandbyInternal.java
@@ -5,6 +5,7 @@
import android.app.usage.AppStandbyInfo;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager.StandbyBuckets;
+import android.app.usage.UsageStatsManager.SystemForcedReasons;
import android.content.Context;
import android.os.Looper;
@@ -123,9 +124,10 @@
* appropriate time.
*
* @param restrictReason The restrictReason for restricting the app. Should be one of the
- * UsageStatsManager.REASON_SUB_RESTRICT_* reasons.
+ * UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_* reasons.
*/
- void restrictApp(@NonNull String packageName, int userId, int restrictReason);
+ void restrictApp(@NonNull String packageName, int userId,
+ @SystemForcedReasons int restrictReason);
void addActiveDeviceAdmin(String adminPkg, int userId);
diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java
index fc29c9c..819f253 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java
@@ -974,7 +974,7 @@
if (!mQuotaTracker.isWithinQuota(userId, pkg, QUOTA_TRACKER_SCHEDULE_PERSISTED_TAG)) {
Slog.e(TAG, userId + "-" + pkg + " has called schedule() too many times");
mAppStandbyInternal.restrictApp(
- pkg, userId, UsageStatsManager.REASON_SUB_RESTRICT_BUGGY);
+ pkg, userId, UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY);
if (mConstants.API_QUOTA_SCHEDULE_THROW_EXCEPTION) {
final boolean isDebuggable;
synchronized (mLock) {
diff --git a/apex/jobscheduler/service/java/com/android/server/job/TEST_MAPPING b/apex/jobscheduler/service/java/com/android/server/job/TEST_MAPPING
index cdcd6598..e2e1180 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/TEST_MAPPING
+++ b/apex/jobscheduler/service/java/com/android/server/job/TEST_MAPPING
@@ -1,6 +1,13 @@
{
"presubmit": [
{
+ "name": "CtsJobSchedulerTestCases",
+ "options": [
+ {"exclude-annotation": "androidx.test.filters.FlakyTest"},
+ {"exclude-annotation": "androidx.test.filters.LargeTest"}
+ ]
+ },
+ {
"name": "FrameworksMockingServicesTests",
"options": [
{"include-filter": "com.android.server.job"},
diff --git a/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java b/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java
index 249bc52..e14ca99 100644
--- a/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java
+++ b/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java
@@ -58,6 +58,7 @@
import android.app.usage.AppStandbyInfo;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager.StandbyBuckets;
+import android.app.usage.UsageStatsManager.SystemForcedReasons;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
@@ -1153,6 +1154,13 @@
}
}
+ @VisibleForTesting
+ int getAppStandbyBucketReason(String packageName, int userId, long elapsedRealtime) {
+ synchronized (mAppIdleLock) {
+ return mAppIdleHistory.getAppStandbyReason(packageName, userId, elapsedRealtime);
+ }
+ }
+
@Override
public List<AppStandbyInfo> getAppStandbyBuckets(int userId) {
synchronized (mAppIdleLock) {
@@ -1161,7 +1169,8 @@
}
@Override
- public void restrictApp(@NonNull String packageName, int userId, int restrictReason) {
+ public void restrictApp(@NonNull String packageName, int userId,
+ @SystemForcedReasons int restrictReason) {
// If the package is not installed, don't allow the bucket to be set.
if (!mInjector.isPackageInstalled(packageName, 0, userId)) {
Slog.e(TAG, "Tried to restrict uninstalled app: " + packageName);
@@ -1248,30 +1257,52 @@
// Don't allow changing bucket if higher than ACTIVE
if (app.currentBucket < STANDBY_BUCKET_ACTIVE) return;
- // Don't allow prediction to change from/to NEVER or from RESTRICTED.
- if ((app.currentBucket == STANDBY_BUCKET_NEVER
- || app.currentBucket == STANDBY_BUCKET_RESTRICTED
- || newBucket == STANDBY_BUCKET_NEVER)
+ // Don't allow prediction to change from/to NEVER.
+ if ((app.currentBucket == STANDBY_BUCKET_NEVER || newBucket == STANDBY_BUCKET_NEVER)
&& predicted) {
return;
}
+ final boolean wasForcedBySystem =
+ (app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_SYSTEM;
+
// If the bucket was forced, don't allow prediction to override
if (predicted
&& ((app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_USER
- || (app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_SYSTEM)) {
+ || wasForcedBySystem)) {
+ return;
+ }
+
+ final boolean isForcedBySystem =
+ (reason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_SYSTEM;
+
+ if (app.currentBucket == newBucket && wasForcedBySystem && isForcedBySystem) {
+ mAppIdleHistory
+ .noteRestrictionAttempt(packageName, userId, elapsedRealtime, reason);
+ // Keep track of all restricting reasons
+ reason = REASON_MAIN_FORCED_BY_SYSTEM
+ | (app.bucketingReason & REASON_SUB_MASK)
+ | (reason & REASON_SUB_MASK);
+ mAppIdleHistory.setAppStandbyBucket(packageName, userId, elapsedRealtime,
+ newBucket, reason, resetTimeout);
return;
}
final boolean isForcedByUser =
(reason & REASON_MAIN_MASK) == REASON_MAIN_FORCED_BY_USER;
- // If the current bucket is RESTRICTED, only user force or usage should bring it out,
- // unless the app was put into the bucket due to timing out.
- if (app.currentBucket == STANDBY_BUCKET_RESTRICTED && !isUserUsage(reason)
- && !isForcedByUser
- && (app.bucketingReason & REASON_MAIN_MASK) != REASON_MAIN_TIMEOUT) {
- return;
+ if (app.currentBucket == STANDBY_BUCKET_RESTRICTED) {
+ if ((app.bucketingReason & REASON_MAIN_MASK) == REASON_MAIN_TIMEOUT) {
+ if (predicted && newBucket >= STANDBY_BUCKET_RARE) {
+ // Predicting into RARE or below means we don't expect the user to use the
+ // app anytime soon, so don't elevate it from RESTRICTED.
+ return;
+ }
+ } else if (!isUserUsage(reason) && !isForcedByUser) {
+ // If the current bucket is RESTRICTED, only user force or usage should bring
+ // it out, unless the app was put into the bucket due to timing out.
+ return;
+ }
}
if (newBucket == STANDBY_BUCKET_RESTRICTED) {
diff --git a/apex/media/framework/java/android/media/MediaParser.java b/apex/media/framework/java/android/media/MediaParser.java
index b219fd41..29c48ad 100644
--- a/apex/media/framework/java/android/media/MediaParser.java
+++ b/apex/media/framework/java/android/media/MediaParser.java
@@ -139,7 +139,7 @@
* @Override
* public void onSampleCompleted(
* int trackIndex,
- * long timeUs,
+ * long timeMicros,
* int flags,
* int size,
* int offset,
@@ -163,7 +163,7 @@
* /* destPos= */ 0,
* /* size= */ offset);
* bytesWrittenCount = bytesWrittenCount - offset;
- * publishSample(sampleData, timeUs, flags);
+ * publishSample(sampleData, timeMicros, flags);
* }
*
* private void ensureSpaceInBuffer(int numberOfBytesToRead) {
@@ -187,7 +187,7 @@
*/
public static final class SeekMap {
- /** Returned by {@link #getDurationUs()} when the duration is unknown. */
+ /** Returned by {@link #getDurationMicros()} when the duration is unknown. */
public static final int UNKNOWN_DURATION = Integer.MIN_VALUE;
private final com.google.android.exoplayer2.extractor.SeekMap mExoPlayerSeekMap;
@@ -205,26 +205,26 @@
* Returns the duration of the stream in microseconds or {@link #UNKNOWN_DURATION} if the
* duration is unknown.
*/
- public long getDurationUs() {
+ public long getDurationMicros() {
return mExoPlayerSeekMap.getDurationUs();
}
/**
* Obtains {@link SeekPoint SeekPoints} for the specified seek time in microseconds.
*
- * <p>{@code getSeekPoints(timeUs).first} contains the latest seek point for samples with
- * timestamp equal to or smaller than {@code timeUs}.
+ * <p>{@code getSeekPoints(timeMicros).first} contains the latest seek point for samples
+ * with timestamp equal to or smaller than {@code timeMicros}.
*
- * <p>{@code getSeekPoints(timeUs).second} contains the earliest seek point for samples with
- * timestamp equal to or greater than {@code timeUs}. If a seek point exists for {@code
- * timeUs}, the returned pair will contain the same {@link SeekPoint} twice.
+ * <p>{@code getSeekPoints(timeMicros).second} contains the earliest seek point for samples
+ * with timestamp equal to or greater than {@code timeMicros}. If a seek point exists for
+ * {@code timeMicros}, the returned pair will contain the same {@link SeekPoint} twice.
*
- * @param timeUs A seek time in microseconds.
+ * @param timeMicros A seek time in microseconds.
* @return The corresponding {@link SeekPoint SeekPoints}.
*/
@NonNull
- public Pair<SeekPoint, SeekPoint> getSeekPoints(long timeUs) {
- SeekPoints seekPoints = mExoPlayerSeekMap.getSeekPoints(timeUs);
+ public Pair<SeekPoint, SeekPoint> getSeekPoints(long timeMicros) {
+ SeekPoints seekPoints = mExoPlayerSeekMap.getSeekPoints(timeMicros);
return new Pair<>(toSeekPoint(seekPoints.first), toSeekPoint(seekPoints.second));
}
}
@@ -254,24 +254,24 @@
@NonNull public static final SeekPoint START = new SeekPoint(0, 0);
/** The time of the seek point, in microseconds. */
- public final long timeUs;
+ public final long timeMicros;
/** The byte offset of the seek point. */
public final long position;
/**
- * @param timeUs The time of the seek point, in microseconds.
+ * @param timeMicros The time of the seek point, in microseconds.
* @param position The byte offset of the seek point.
*/
- private SeekPoint(long timeUs, long position) {
- this.timeUs = timeUs;
+ private SeekPoint(long timeMicros, long position) {
+ this.timeMicros = timeMicros;
this.position = position;
}
@Override
@NonNull
public String toString() {
- return "[timeUs=" + timeUs + ", position=" + position + "]";
+ return "[timeMicros=" + timeMicros + ", position=" + position + "]";
}
@Override
@@ -283,12 +283,12 @@
return false;
}
SeekPoint other = (SeekPoint) obj;
- return timeUs == other.timeUs && position == other.position;
+ return timeMicros == other.timeMicros && position == other.position;
}
@Override
public int hashCode() {
- int result = (int) timeUs;
+ int result = (int) timeMicros;
result = 31 * result + (int) position;
return result;
}
@@ -345,25 +345,25 @@
*
* @param seekMap The extracted {@link SeekMap}.
*/
- void onSeekMap(@NonNull SeekMap seekMap);
+ void onSeekMapFound(@NonNull SeekMap seekMap);
/**
* Called when the number of tracks is found.
*
* @param numberOfTracks The number of tracks in the stream.
*/
- void onTracksFound(int numberOfTracks);
+ void onTrackCountFound(int numberOfTracks);
/**
- * Called when new {@link TrackData} is extracted from the stream.
+ * Called when new {@link TrackData} is found in the stream.
*
* @param trackIndex The index of the track for which the {@link TrackData} was extracted.
* @param trackData The extracted {@link TrackData}.
*/
- void onTrackData(int trackIndex, @NonNull TrackData trackData);
+ void onTrackDataFound(int trackIndex, @NonNull TrackData trackData);
/**
- * Called to write sample data to the output.
+ * Called when sample data is found in the stream.
*
* <p>If the invocation of this method returns before the entire {@code inputReader} {@link
* InputReader#getLength() length} is consumed, the method will be called again for the
@@ -374,15 +374,15 @@
* @param inputReader The {@link InputReader} from which to read the data.
* @throws IOException If an exception occurs while reading from {@code inputReader}.
*/
- void onSampleData(int trackIndex, @NonNull InputReader inputReader) throws IOException;
+ void onSampleDataFound(int trackIndex, @NonNull InputReader inputReader) throws IOException;
/**
- * Called once all the data of a sample has been passed to {@link #onSampleData}.
+ * Called once all the data of a sample has been passed to {@link #onSampleDataFound}.
*
* <p>Also includes sample metadata, like presentation timestamp and flags.
*
* @param trackIndex The index of the track to which the sample corresponds.
- * @param timeUs The media timestamp associated with the sample, in microseconds.
+ * @param timeMicros The media timestamp associated with the sample, in microseconds.
* @param flags Flags associated with the sample. See {@link MediaCodec
* MediaCodec.BUFFER_FLAG_*}.
* @param size The size of the sample data, in bytes.
@@ -394,7 +394,7 @@
*/
void onSampleCompleted(
int trackIndex,
- long timeUs,
+ long timeMicros,
int flags,
int size,
int offset,
@@ -632,7 +632,7 @@
private Extractor mExtractor;
private ExtractorInput mExtractorInput;
private long mPendingSeekPosition;
- private long mPendingSeekTimeUs;
+ private long mPendingSeekTimeMicros;
// Public methods.
@@ -760,7 +760,7 @@
}
if (isPendingSeek()) {
- mExtractor.seek(mPendingSeekPosition, mPendingSeekTimeUs);
+ mExtractor.seek(mPendingSeekPosition, mPendingSeekTimeMicros);
removePendingSeek();
}
@@ -786,7 +786,7 @@
* Seeks within the media container being extracted.
*
* <p>{@link SeekPoint SeekPoints} can be obtained from the {@link SeekMap} passed to {@link
- * OutputConsumer#onSeekMap(SeekMap)}.
+ * OutputConsumer#onSeekMapFound(SeekMap)}.
*
* <p>Following a call to this method, the {@link InputReader} passed to the next invocation of
* {@link #advance} must provide data starting from {@link SeekPoint#position} in the stream.
@@ -796,9 +796,9 @@
public void seek(@NonNull SeekPoint seekPoint) {
if (mExtractor == null) {
mPendingSeekPosition = seekPoint.position;
- mPendingSeekTimeUs = seekPoint.timeUs;
+ mPendingSeekTimeMicros = seekPoint.timeMicros;
} else {
- mExtractor.seek(seekPoint.position, seekPoint.timeUs);
+ mExtractor.seek(seekPoint.position, seekPoint.timeMicros);
}
}
@@ -836,7 +836,7 @@
private void removePendingSeek() {
mPendingSeekPosition = -1;
- mPendingSeekTimeUs = -1;
+ mPendingSeekTimeMicros = -1;
}
// Private classes.
@@ -897,12 +897,12 @@
@Override
public void endTracks() {
- mOutputConsumer.onTracksFound(mTrackOutputAdapters.size());
+ mOutputConsumer.onTrackCountFound(mTrackOutputAdapters.size());
}
@Override
public void seekMap(com.google.android.exoplayer2.extractor.SeekMap exoplayerSeekMap) {
- mOutputConsumer.onSeekMap(new SeekMap(exoplayerSeekMap));
+ mOutputConsumer.onSeekMapFound(new SeekMap(exoplayerSeekMap));
}
}
@@ -916,7 +916,7 @@
@Override
public void format(Format format) {
- mOutputConsumer.onTrackData(
+ mOutputConsumer.onTrackDataFound(
mTrackIndex,
new TrackData(
toMediaFormat(format), toFrameworkDrmInitData(format.drmInitData)));
@@ -927,7 +927,7 @@
throws IOException {
mScratchExtractorInputAdapter.setExtractorInput(input, length);
long positionBeforeReading = mScratchExtractorInputAdapter.getPosition();
- mOutputConsumer.onSampleData(mTrackIndex, mScratchExtractorInputAdapter);
+ mOutputConsumer.onSampleDataFound(mTrackIndex, mScratchExtractorInputAdapter);
return (int) (mScratchExtractorInputAdapter.getPosition() - positionBeforeReading);
}
@@ -935,7 +935,7 @@
public void sampleData(ParsableByteArray data, int length) {
mScratchParsableByteArrayAdapter.resetWithByteArray(data, length);
try {
- mOutputConsumer.onSampleData(mTrackIndex, mScratchParsableByteArrayAdapter);
+ mOutputConsumer.onSampleDataFound(mTrackIndex, mScratchParsableByteArrayAdapter);
} catch (IOException e) {
// Unexpected.
throw new RuntimeException(e);
diff --git a/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistence.java b/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistence.java
index 0d163cf..aedba29 100644
--- a/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistence.java
+++ b/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistence.java
@@ -40,7 +40,7 @@
* @return the runtime permissions read
*/
@Nullable
- RuntimePermissionsState readAsUser(@NonNull UserHandle user);
+ RuntimePermissionsState readForUser(@NonNull UserHandle user);
/**
* Write the runtime permissions to persistence.
@@ -50,7 +50,8 @@
* @param runtimePermissions the runtime permissions to write
* @param user the user to write for
*/
- void writeAsUser(@NonNull RuntimePermissionsState runtimePermissions, @NonNull UserHandle user);
+ void writeForUser(@NonNull RuntimePermissionsState runtimePermissions,
+ @NonNull UserHandle user);
/**
* Delete the runtime permissions from persistence.
@@ -59,7 +60,7 @@
*
* @param user the user to delete for
*/
- void deleteAsUser(@NonNull UserHandle user);
+ void deleteForUser(@NonNull UserHandle user);
/**
* Create a new instance of {@link RuntimePermissionsPersistence} implementation.
diff --git a/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistenceImpl.java b/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistenceImpl.java
index 30a8b45..e43f59a 100644
--- a/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistenceImpl.java
+++ b/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsPersistenceImpl.java
@@ -18,7 +18,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.content.ApexContext;
+import android.content.ApexEnvironment;
import android.content.pm.PackageManager;
import android.os.UserHandle;
import android.util.ArrayMap;
@@ -67,7 +67,7 @@
@Nullable
@Override
- public RuntimePermissionsState readAsUser(@NonNull UserHandle user) {
+ public RuntimePermissionsState readForUser(@NonNull UserHandle user) {
File file = getFile(user);
try (FileInputStream inputStream = new AtomicFile(file).openRead()) {
XmlPullParser parser = Xml.newPullParser();
@@ -172,7 +172,7 @@
}
@Override
- public void writeAsUser(@NonNull RuntimePermissionsState runtimePermissions,
+ public void writeForUser(@NonNull RuntimePermissionsState runtimePermissions,
@NonNull UserHandle user) {
File file = getFile(user);
AtomicFile atomicFile = new AtomicFile(file);
@@ -252,14 +252,14 @@
}
@Override
- public void deleteAsUser(@NonNull UserHandle user) {
+ public void deleteForUser(@NonNull UserHandle user) {
getFile(user).delete();
}
@NonNull
private static File getFile(@NonNull UserHandle user) {
- ApexContext apexContext = ApexContext.getApexContext(APEX_MODULE_NAME);
- File dataDirectory = apexContext.getDeviceProtectedDataDirForUser(user);
+ ApexEnvironment apexEnvironment = ApexEnvironment.getApexEnvironment(APEX_MODULE_NAME);
+ File dataDirectory = apexEnvironment.getDeviceProtectedDataDirForUser(user);
return new File(dataDirectory, RUNTIME_PERMISSIONS_FILE_NAME);
}
}
diff --git a/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsState.java b/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsState.java
index cd2750a..c6bfc6d 100644
--- a/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsState.java
+++ b/apex/permission/service/java/com/android/permission/persistence/RuntimePermissionsState.java
@@ -23,6 +23,7 @@
import java.util.List;
import java.util.Map;
+import java.util.Objects;
/**
* State of all runtime permissions.
@@ -61,6 +62,14 @@
@NonNull
private final Map<String, List<PermissionState>> mSharedUserPermissions;
+ /**
+ * Create a new instance of this class.
+ *
+ * @param version the version of the runtime permissions
+ * @param fingerprint the fingerprint of the runtime permissions
+ * @param packagePermissions the runtime permissions by packages
+ * @param sharedUserPermissions the runtime permissions by shared users
+ */
public RuntimePermissionsState(int version, @Nullable String fingerprint,
@NonNull Map<String, List<PermissionState>> packagePermissions,
@NonNull Map<String, List<PermissionState>> sharedUserPermissions) {
@@ -70,32 +79,72 @@
mSharedUserPermissions = sharedUserPermissions;
}
+ /**
+ * Get the version of the runtime permissions.
+ *
+ * @return the version of the runtime permissions
+ */
public int getVersion() {
return mVersion;
}
+ /**
+ * Get the fingerprint of the runtime permissions.
+ *
+ * @return the fingerprint of the runtime permissions
+ */
@Nullable
public String getFingerprint() {
return mFingerprint;
}
+ /**
+ * Get the runtime permissions by packages.
+ *
+ * @return the runtime permissions by packages
+ */
@NonNull
public Map<String, List<PermissionState>> getPackagePermissions() {
return mPackagePermissions;
}
+ /**
+ * Get the runtime permissions by shared users.
+ *
+ * @return the runtime permissions by shared users
+ */
@NonNull
public Map<String, List<PermissionState>> getSharedUserPermissions() {
return mSharedUserPermissions;
}
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (object == null || getClass() != object.getClass()) {
+ return false;
+ }
+ RuntimePermissionsState that = (RuntimePermissionsState) object;
+ return mVersion == that.mVersion
+ && Objects.equals(mFingerprint, that.mFingerprint)
+ && Objects.equals(mPackagePermissions, that.mPackagePermissions)
+ && Objects.equals(mSharedUserPermissions, that.mSharedUserPermissions);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mVersion, mFingerprint, mPackagePermissions, mSharedUserPermissions);
+ }
+
/**
* State of a single permission.
*/
- public static class PermissionState {
+ public static final class PermissionState {
/**
- * Name of the permission.
+ * The name of the permission.
*/
@NonNull
private final String mName;
@@ -106,27 +155,68 @@
private final boolean mGranted;
/**
- * Flags of the permission.
+ * The flags of the permission.
*/
private final int mFlags;
+ /**
+ * Create a new instance of this class.
+ *
+ * @param name the name of the permission
+ * @param granted whether the permission is granted
+ * @param flags the flags of the permission
+ */
public PermissionState(@NonNull String name, boolean granted, int flags) {
mName = name;
mGranted = granted;
mFlags = flags;
}
+ /**
+ * Get the name of the permission.
+ *
+ * @return the name of the permission
+ */
@NonNull
public String getName() {
return mName;
}
+ /**
+ * Get whether the permission is granted.
+ *
+ * @return whether the permission is granted
+ */
public boolean isGranted() {
return mGranted;
}
+ /**
+ * Get the flags of the permission.
+ *
+ * @return the flags of the permission
+ */
public int getFlags() {
return mFlags;
}
+
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (object == null || getClass() != object.getClass()) {
+ return false;
+ }
+ PermissionState that = (PermissionState) object;
+ return mGranted == that.mGranted
+ && mFlags == that.mFlags
+ && Objects.equals(mName, that.mName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mName, mGranted, mFlags);
+ }
}
}
diff --git a/apex/permission/service/java/com/android/role/persistence/RolesPersistence.java b/apex/permission/service/java/com/android/role/persistence/RolesPersistence.java
index 64d6545..2e5a28a 100644
--- a/apex/permission/service/java/com/android/role/persistence/RolesPersistence.java
+++ b/apex/permission/service/java/com/android/role/persistence/RolesPersistence.java
@@ -40,7 +40,7 @@
* @return the roles read
*/
@Nullable
- RolesState readAsUser(@NonNull UserHandle user);
+ RolesState readForUser(@NonNull UserHandle user);
/**
* Write the roles to persistence.
@@ -50,7 +50,7 @@
* @param roles the roles to write
* @param user the user to write for
*/
- void writeAsUser(@NonNull RolesState roles, @NonNull UserHandle user);
+ void writeForUser(@NonNull RolesState roles, @NonNull UserHandle user);
/**
* Delete the roles from persistence.
@@ -59,7 +59,7 @@
*
* @param user the user to delete for
*/
- void deleteAsUser(@NonNull UserHandle user);
+ void deleteForUser(@NonNull UserHandle user);
/**
* Create a new instance of {@link RolesPersistence} implementation.
diff --git a/apex/permission/service/java/com/android/role/persistence/RolesPersistenceImpl.java b/apex/permission/service/java/com/android/role/persistence/RolesPersistenceImpl.java
index 3031c82..f66257f 100644
--- a/apex/permission/service/java/com/android/role/persistence/RolesPersistenceImpl.java
+++ b/apex/permission/service/java/com/android/role/persistence/RolesPersistenceImpl.java
@@ -18,7 +18,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.content.ApexContext;
+import android.content.ApexEnvironment;
import android.os.UserHandle;
import android.util.ArrayMap;
import android.util.ArraySet;
@@ -65,7 +65,7 @@
@Nullable
@Override
- public RolesState readAsUser(@NonNull UserHandle user) {
+ public RolesState readForUser(@NonNull UserHandle user) {
File file = getFile(user);
try (FileInputStream inputStream = new AtomicFile(file).openRead()) {
XmlPullParser parser = Xml.newPullParser();
@@ -146,7 +146,7 @@
}
@Override
- public void writeAsUser(@NonNull RolesState roles, @NonNull UserHandle user) {
+ public void writeForUser(@NonNull RolesState roles, @NonNull UserHandle user) {
File file = getFile(user);
AtomicFile atomicFile = new AtomicFile(file);
FileOutputStream outputStream = null;
@@ -205,14 +205,14 @@
}
@Override
- public void deleteAsUser(@NonNull UserHandle user) {
+ public void deleteForUser(@NonNull UserHandle user) {
getFile(user).delete();
}
@NonNull
private static File getFile(@NonNull UserHandle user) {
- ApexContext apexContext = ApexContext.getApexContext(APEX_MODULE_NAME);
- File dataDirectory = apexContext.getDeviceProtectedDataDirForUser(user);
+ ApexEnvironment apexEnvironment = ApexEnvironment.getApexEnvironment(APEX_MODULE_NAME);
+ File dataDirectory = apexEnvironment.getDeviceProtectedDataDirForUser(user);
return new File(dataDirectory, ROLES_FILE_NAME);
}
}
diff --git a/apex/permission/service/java/com/android/role/persistence/RolesState.java b/apex/permission/service/java/com/android/role/persistence/RolesState.java
index 7da9d11..f61efa0 100644
--- a/apex/permission/service/java/com/android/role/persistence/RolesState.java
+++ b/apex/permission/service/java/com/android/role/persistence/RolesState.java
@@ -22,6 +22,7 @@
import android.annotation.SystemApi.Client;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
/**
@@ -50,6 +51,13 @@
@NonNull
private final Map<String, Set<String>> mRoles;
+ /**
+ * Create a new instance of this class.
+ *
+ * @param version the version of the roles
+ * @param packagesHash the hash of all packages in the system
+ * @param roles the roles
+ */
public RolesState(int version, @Nullable String packagesHash,
@NonNull Map<String, Set<String>> roles) {
mVersion = version;
@@ -57,17 +65,51 @@
mRoles = roles;
}
+ /**
+ * Get the version of the roles.
+ *
+ * @return the version of the roles
+ */
public int getVersion() {
return mVersion;
}
+ /**
+ * Get the hash of all packages in the system.
+ *
+ * @return the hash of all packages in the system
+ */
@Nullable
public String getPackagesHash() {
return mPackagesHash;
}
+ /**
+ * Get the roles.
+ *
+ * @return the roles
+ */
@NonNull
public Map<String, Set<String>> getRoles() {
return mRoles;
}
+
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (object == null || getClass() != object.getClass()) {
+ return false;
+ }
+ RolesState that = (RolesState) object;
+ return mVersion == that.mVersion
+ && Objects.equals(mPackagesHash, that.mPackagesHash)
+ && Objects.equals(mRoles, that.mRoles);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mVersion, mPackagesHash, mRoles);
+ }
}
diff --git a/apex/statsd/aidl/android/os/IStatsManagerService.aidl b/apex/statsd/aidl/android/os/IStatsManagerService.aidl
index 4a259f5..b59a97e 100644
--- a/apex/statsd/aidl/android/os/IStatsManagerService.aidl
+++ b/apex/statsd/aidl/android/os/IStatsManagerService.aidl
@@ -128,7 +128,7 @@
void removeConfiguration(in long configId, in String packageName);
/** Tell StatsManagerService to register a puller for the given atom tag with statsd. */
- oneway void registerPullAtomCallback(int atomTag, long coolDownNs, long timeoutNs,
+ oneway void registerPullAtomCallback(int atomTag, long coolDownMillis, long timeoutMillis,
in int[] additiveFields, IPullAtomCallback pullerCallback);
/** Tell StatsManagerService to unregister the pulller for the given atom tag from statsd. */
diff --git a/apex/statsd/aidl/android/os/IStatsd.aidl b/apex/statsd/aidl/android/os/IStatsd.aidl
index 10b1e5b..c8aec53 100644
--- a/apex/statsd/aidl/android/os/IStatsd.aidl
+++ b/apex/statsd/aidl/android/os/IStatsd.aidl
@@ -186,8 +186,9 @@
* Registers a puller callback function that, when invoked, pulls the data
* for the specified atom tag.
*/
- oneway void registerPullAtomCallback(int uid, int atomTag, long coolDownNs, long timeoutNs,
- in int[] additiveFields, IPullAtomCallback pullerCallback);
+ oneway void registerPullAtomCallback(int uid, int atomTag, long coolDownMillis,
+ long timeoutMillis,in int[] additiveFields,
+ IPullAtomCallback pullerCallback);
/**
* Registers a puller callback function that, when invoked, pulls the data
diff --git a/apex/statsd/framework/java/android/app/StatsManager.java b/apex/statsd/framework/java/android/app/StatsManager.java
index e637187..f021dcf 100644
--- a/apex/statsd/framework/java/android/app/StatsManager.java
+++ b/apex/statsd/framework/java/android/app/StatsManager.java
@@ -119,14 +119,12 @@
/**
* @hide
**/
- @VisibleForTesting
- public static final long DEFAULT_COOL_DOWN_NS = 1_000_000_000L; // 1 second.
+ @VisibleForTesting public static final long DEFAULT_COOL_DOWN_MILLIS = 1_000L; // 1 second.
/**
* @hide
**/
- @VisibleForTesting
- public static final long DEFAULT_TIMEOUT_NS = 10_000_000_000L; // 10 seconds.
+ @VisibleForTesting public static final long DEFAULT_TIMEOUT_MILLIS = 10_000L; // 10 seconds.
/**
* Constructor for StatsManagerClient.
@@ -489,23 +487,24 @@
}
/**
- * Registers a callback for an atom when that atom is to be pulled. The stats service will
+ * Sets a callback for an atom when that atom is to be pulled. The stats service will
* invoke pullData in the callback when the stats service determines that this atom needs to be
* pulled. This method should not be called by third-party apps.
*
* @param atomTag The tag of the atom for this puller callback.
* @param metadata Optional metadata specifying the timeout, cool down time, and
* additive fields for mapping isolated to host uids.
- * @param callback The callback to be invoked when the stats service pulls the atom.
* @param executor The executor in which to run the callback.
+ * @param callback The callback to be invoked when the stats service pulls the atom.
*
*/
@RequiresPermission(android.Manifest.permission.REGISTER_STATS_PULL_ATOM)
- public void registerPullAtomCallback(int atomTag, @Nullable PullAtomMetadata metadata,
+ public void setPullAtomCallback(int atomTag, @Nullable PullAtomMetadata metadata,
@NonNull @CallbackExecutor Executor executor,
@NonNull StatsPullAtomCallback callback) {
- long coolDownNs = metadata == null ? DEFAULT_COOL_DOWN_NS : metadata.mCoolDownNs;
- long timeoutNs = metadata == null ? DEFAULT_TIMEOUT_NS : metadata.mTimeoutNs;
+ long coolDownMillis =
+ metadata == null ? DEFAULT_COOL_DOWN_MILLIS : metadata.mCoolDownMillis;
+ long timeoutMillis = metadata == null ? DEFAULT_TIMEOUT_MILLIS : metadata.mTimeoutMillis;
int[] additiveFields = metadata == null ? new int[0] : metadata.mAdditiveFields;
if (additiveFields == null) {
additiveFields = new int[0];
@@ -516,8 +515,8 @@
IStatsManagerService service = getIStatsManagerServiceLocked();
PullAtomCallbackInternal rec =
new PullAtomCallbackInternal(atomTag, callback, executor);
- service.registerPullAtomCallback(atomTag, coolDownNs, timeoutNs, additiveFields,
- rec);
+ service.registerPullAtomCallback(
+ atomTag, coolDownMillis, timeoutMillis, additiveFields, rec);
} catch (RemoteException e) {
throw new RuntimeException("Unable to register pull callback", e);
}
@@ -525,14 +524,14 @@
}
/**
- * Unregisters a callback for an atom when that atom is to be pulled. Note that any ongoing
+ * Clears a callback for an atom when that atom is to be pulled. Note that any ongoing
* pulls will still occur. This method should not be called by third-party apps.
*
* @param atomTag The tag of the atom of which to unregister
*
*/
@RequiresPermission(android.Manifest.permission.REGISTER_STATS_PULL_ATOM)
- public void unregisterPullAtomCallback(int atomTag) {
+ public void clearPullAtomCallback(int atomTag) {
synchronized (sLock) {
try {
IStatsManagerService service = getIStatsManagerServiceLocked();
@@ -585,14 +584,14 @@
*
*/
public static class PullAtomMetadata {
- private final long mCoolDownNs;
- private final long mTimeoutNs;
+ private final long mCoolDownMillis;
+ private final long mTimeoutMillis;
private final int[] mAdditiveFields;
// Private Constructor for builder
- private PullAtomMetadata(long coolDownNs, long timeoutNs, int[] additiveFields) {
- mCoolDownNs = coolDownNs;
- mTimeoutNs = timeoutNs;
+ private PullAtomMetadata(long coolDownMillis, long timeoutMillis, int[] additiveFields) {
+ mCoolDownMillis = coolDownMillis;
+ mTimeoutMillis = timeoutMillis;
mAdditiveFields = additiveFields;
}
@@ -600,8 +599,8 @@
* Builder for PullAtomMetadata.
*/
public static class Builder {
- private long mCoolDownNs;
- private long mTimeoutNs;
+ private long mCoolDownMillis;
+ private long mTimeoutMillis;
private int[] mAdditiveFields;
/**
@@ -609,27 +608,28 @@
* StatsManager#registerPullAtomCallback
*/
public Builder() {
- mCoolDownNs = DEFAULT_COOL_DOWN_NS;
- mTimeoutNs = DEFAULT_TIMEOUT_NS;
+ mCoolDownMillis = DEFAULT_COOL_DOWN_MILLIS;
+ mTimeoutMillis = DEFAULT_TIMEOUT_MILLIS;
mAdditiveFields = null;
}
/**
- * Set the cool down time of the pull in nanoseconds. If two successive pulls are issued
- * within the cool down, a cached version of the first will be used for the second.
+ * Set the cool down time of the pull in milliseconds. If two successive pulls are
+ * issued within the cool down, a cached version of the first pull will be used for the
+ * second pull.
*/
@NonNull
- public Builder setCoolDownNs(long coolDownNs) {
- mCoolDownNs = coolDownNs;
+ public Builder setCoolDownMillis(long coolDownMillis) {
+ mCoolDownMillis = coolDownMillis;
return this;
}
/**
- * Set the maximum time the pull can take in nanoseconds.
+ * Set the maximum time the pull can take in milliseconds.
*/
@NonNull
- public Builder setTimeoutNs(long timeoutNs) {
- mTimeoutNs = timeoutNs;
+ public Builder setTimeoutMillis(long timeoutMillis) {
+ mTimeoutMillis = timeoutMillis;
return this;
}
@@ -652,30 +652,32 @@
*/
@NonNull
public PullAtomMetadata build() {
- return new PullAtomMetadata(mCoolDownNs, mTimeoutNs, mAdditiveFields);
+ return new PullAtomMetadata(mCoolDownMillis, mTimeoutMillis, mAdditiveFields);
}
}
/**
- * @hide
+ * Return the cool down time of this pull in milliseconds.
*/
- @VisibleForTesting
- public long getCoolDownNs() {
- return mCoolDownNs;
+ public long getCoolDownMillis() {
+ return mCoolDownMillis;
}
/**
- * @hide
+ * Return the maximum amount of time this pull can take in milliseconds.
*/
- @VisibleForTesting
- public long getTimeoutNs() {
- return mTimeoutNs;
+ public long getTimeoutMillis() {
+ return mTimeoutMillis;
}
/**
- * @hide
+ * Return the additive fields of this pulled atom.
+ *
+ * This is only applicable for atoms that have a uid field. When tasks are run in
+ * isolated processes, the data will be attributed to the host uid. Additive fields
+ * will be combined when the non-additive fields are the same.
*/
- @VisibleForTesting
+ @Nullable
public int[] getAdditiveFields() {
return mAdditiveFields;
}
diff --git a/apex/statsd/framework/test/src/android/app/PullAtomMetadataTest.java b/apex/statsd/framework/test/src/android/app/PullAtomMetadataTest.java
index 0ae6134..fd386bd 100644
--- a/apex/statsd/framework/test/src/android/app/PullAtomMetadataTest.java
+++ b/apex/statsd/framework/test/src/android/app/PullAtomMetadataTest.java
@@ -33,28 +33,28 @@
@Test
public void testEmpty() {
PullAtomMetadata metadata = new PullAtomMetadata.Builder().build();
- assertThat(metadata.getTimeoutNs()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_NS);
- assertThat(metadata.getCoolDownNs()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_NS);
+ assertThat(metadata.getTimeoutMillis()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_MILLIS);
+ assertThat(metadata.getCoolDownMillis()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_MILLIS);
assertThat(metadata.getAdditiveFields()).isNull();
}
@Test
- public void testSetTimeoutNs() {
- long timeoutNs = 500_000_000L;
+ public void testSetTimeoutMillis() {
+ long timeoutMillis = 500L;
PullAtomMetadata metadata =
- new PullAtomMetadata.Builder().setTimeoutNs(timeoutNs).build();
- assertThat(metadata.getTimeoutNs()).isEqualTo(timeoutNs);
- assertThat(metadata.getCoolDownNs()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_NS);
+ new PullAtomMetadata.Builder().setTimeoutMillis(timeoutMillis).build();
+ assertThat(metadata.getTimeoutMillis()).isEqualTo(timeoutMillis);
+ assertThat(metadata.getCoolDownMillis()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_MILLIS);
assertThat(metadata.getAdditiveFields()).isNull();
}
@Test
- public void testSetCoolDownNs() {
- long coolDownNs = 10_000_000_000L;
+ public void testSetCoolDownMillis() {
+ long coolDownMillis = 10_000L;
PullAtomMetadata metadata =
- new PullAtomMetadata.Builder().setCoolDownNs(coolDownNs).build();
- assertThat(metadata.getTimeoutNs()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_NS);
- assertThat(metadata.getCoolDownNs()).isEqualTo(coolDownNs);
+ new PullAtomMetadata.Builder().setCoolDownMillis(coolDownMillis).build();
+ assertThat(metadata.getTimeoutMillis()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_MILLIS);
+ assertThat(metadata.getCoolDownMillis()).isEqualTo(coolDownMillis);
assertThat(metadata.getAdditiveFields()).isNull();
}
@@ -63,23 +63,23 @@
int[] fields = {2, 4, 6};
PullAtomMetadata metadata =
new PullAtomMetadata.Builder().setAdditiveFields(fields).build();
- assertThat(metadata.getTimeoutNs()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_NS);
- assertThat(metadata.getCoolDownNs()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_NS);
+ assertThat(metadata.getTimeoutMillis()).isEqualTo(StatsManager.DEFAULT_TIMEOUT_MILLIS);
+ assertThat(metadata.getCoolDownMillis()).isEqualTo(StatsManager.DEFAULT_COOL_DOWN_MILLIS);
assertThat(metadata.getAdditiveFields()).isEqualTo(fields);
}
@Test
public void testSetAllElements() {
- long timeoutNs = 300L;
- long coolDownNs = 9572L;
+ long timeoutMillis = 300L;
+ long coolDownMillis = 9572L;
int[] fields = {3, 2};
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
- .setTimeoutNs(timeoutNs)
- .setCoolDownNs(coolDownNs)
+ .setTimeoutMillis(timeoutMillis)
+ .setCoolDownMillis(coolDownMillis)
.setAdditiveFields(fields)
.build();
- assertThat(metadata.getTimeoutNs()).isEqualTo(timeoutNs);
- assertThat(metadata.getCoolDownNs()).isEqualTo(coolDownNs);
+ assertThat(metadata.getTimeoutMillis()).isEqualTo(timeoutMillis);
+ assertThat(metadata.getCoolDownMillis()).isEqualTo(coolDownMillis);
assertThat(metadata.getAdditiveFields()).isEqualTo(fields);
}
}
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
index dc61f2ae..c84627d 100644
--- a/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
+++ b/apex/statsd/service/java/com/android/server/stats/StatsCompanionService.java
@@ -54,6 +54,7 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -102,9 +103,6 @@
private final OnAlarmListener mAnomalyAlarmListener = new AnomalyAlarmListener();
private final OnAlarmListener mPullingAlarmListener = new PullingAlarmListener();
private final OnAlarmListener mPeriodicAlarmListener = new PeriodicAlarmListener();
- private final BroadcastReceiver mAppUpdateReceiver;
- private final BroadcastReceiver mUserUpdateReceiver;
- private final ShutdownEventReceiver mShutdownEventReceiver;
private StatsManagerService mStatsManagerService;
@@ -118,27 +116,6 @@
super();
mContext = context;
mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
- mAppUpdateReceiver = new AppUpdateReceiver();
- mUserUpdateReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- synchronized (sStatsdLock) {
- if (sStatsd == null) {
- Log.w(TAG, "Could not access statsd for UserUpdateReceiver");
- return;
- }
- try {
- // Pull the latest state of UID->app name, version mapping.
- // Needed since the new user basically has a version of every app.
- informAllUidsLocked(context);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to inform statsd latest update of all apps", e);
- forgetEverythingLocked();
- }
- }
- }
- };
- mShutdownEventReceiver = new ShutdownEventReceiver();
if (DEBUG) Log.d(TAG, "Registered receiver for ACTION_PACKAGE_REPLACED and ADDED.");
HandlerThread handlerThread = new HandlerThread(TAG);
handlerThread.start();
@@ -162,9 +139,18 @@
return ret;
}
- // Assumes that sStatsdLock is held.
- @GuardedBy("sStatsdLock")
- private void informAllUidsLocked(Context context) throws RemoteException {
+ /**
+ * Non-blocking call to retrieve a reference to statsd
+ *
+ * @return IStatsd object if statsd is ready, null otherwise.
+ */
+ private static IStatsd getStatsdNonblocking() {
+ synchronized (sStatsdLock) {
+ return sStatsd;
+ }
+ }
+
+ private static void informAllUidsLocked(Context context) throws RemoteException {
UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
PackageManager pm = context.getPackageManager();
final List<UserHandle> users = um.getUserHandles(true);
@@ -273,7 +259,6 @@
if (!replacing) {
// Don't bother sending an update if we're right about to get another
// intent for the new version that's added.
- PackageManager pm = context.getPackageManager();
String app = intent.getData().getSchemeSpecificPart();
sStatsd.informOnePackageRemoved(app, uid);
}
@@ -303,23 +288,43 @@
}
}
- public final static class AnomalyAlarmListener implements OnAlarmListener {
+ private static final class UserUpdateReceiver extends BroadcastReceiver {
@Override
- public void onAlarm() {
- Log.i(TAG, "StatsCompanionService believes an anomaly has occurred at time "
- + System.currentTimeMillis() + "ms.");
+ public void onReceive(Context context, Intent intent) {
synchronized (sStatsdLock) {
if (sStatsd == null) {
- Log.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
+ Log.w(TAG, "Could not access statsd for UserUpdateReceiver");
return;
}
try {
- // Two-way call to statsd to retain AlarmManager wakelock
- sStatsd.informAnomalyAlarmFired();
+ // Pull the latest state of UID->app name, version mapping.
+ // Needed since the new user basically has a version of every app.
+ informAllUidsLocked(context);
} catch (RemoteException e) {
- Log.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
+ Log.e(TAG, "Failed to inform statsd latest update of all apps", e);
}
}
+ }
+ }
+
+ public static final class AnomalyAlarmListener implements OnAlarmListener {
+ @Override
+ public void onAlarm() {
+ if (DEBUG) {
+ Log.i(TAG, "StatsCompanionService believes an anomaly has occurred at time "
+ + System.currentTimeMillis() + "ms.");
+ }
+ IStatsd statsd = getStatsdNonblocking();
+ if (statsd == null) {
+ Log.w(TAG, "Could not access statsd to inform it of anomaly alarm firing");
+ return;
+ }
+ try {
+ // Two-way call to statsd to retain AlarmManager wakelock
+ statsd.informAnomalyAlarmFired();
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed to inform statsd of anomaly alarm firing", e);
+ }
// AlarmManager releases its own wakelock here.
}
}
@@ -330,17 +335,16 @@
if (DEBUG) {
Log.d(TAG, "Time to poll something.");
}
- synchronized (sStatsdLock) {
- if (sStatsd == null) {
- Log.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
- return;
- }
- try {
- // Two-way call to statsd to retain AlarmManager wakelock
- sStatsd.informPollAlarmFired();
- } catch (RemoteException e) {
- Log.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
- }
+ IStatsd statsd = getStatsdNonblocking();
+ if (statsd == null) {
+ Log.w(TAG, "Could not access statsd to inform it of pulling alarm firing.");
+ return;
+ }
+ try {
+ // Two-way call to statsd to retain AlarmManager wakelock
+ statsd.informPollAlarmFired();
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed to inform statsd of pulling alarm firing.", e);
}
}
}
@@ -351,17 +355,16 @@
if (DEBUG) {
Log.d(TAG, "Time to trigger periodic alarm.");
}
- synchronized (sStatsdLock) {
- if (sStatsd == null) {
- Log.w(TAG, "Could not access statsd to inform it of periodic alarm firing.");
- return;
- }
- try {
- // Two-way call to statsd to retain AlarmManager wakelock
- sStatsd.informAlarmForSubscriberTriggeringFired();
- } catch (RemoteException e) {
- Log.w(TAG, "Failed to inform statsd of periodic alarm firing.", e);
- }
+ IStatsd statsd = getStatsdNonblocking();
+ if (statsd == null) {
+ Log.w(TAG, "Could not access statsd to inform it of periodic alarm firing.");
+ return;
+ }
+ try {
+ // Two-way call to statsd to retain AlarmManager wakelock
+ statsd.informAlarmForSubscriberTriggeringFired();
+ } catch (RemoteException e) {
+ Log.w(TAG, "Failed to inform statsd of periodic alarm firing.", e);
}
// AlarmManager releases its own wakelock here.
}
@@ -379,17 +382,19 @@
return;
}
- Log.i(TAG, "StatsCompanionService noticed a shutdown.");
- synchronized (sStatsdLock) {
- if (sStatsd == null) {
- Log.w(TAG, "Could not access statsd to inform it of a shutdown event.");
- return;
- }
- try {
- sStatsd.informDeviceShutdown();
- } catch (Exception e) {
- Log.w(TAG, "Failed to inform statsd of a shutdown event.", e);
- }
+ if (DEBUG) {
+ Log.i(TAG, "StatsCompanionService noticed a shutdown.");
+ }
+ IStatsd statsd = getStatsdNonblocking();
+ if (statsd == null) {
+ Log.w(TAG, "Could not access statsd to inform it of a shutdown event.");
+ return;
+ }
+ try {
+ // two way binder call
+ statsd.informDeviceShutdown();
+ } catch (Exception e) {
+ Log.w(TAG, "Failed to inform statsd of a shutdown event.", e);
}
}
}
@@ -515,7 +520,7 @@
}
}
- @Override
+ @Override // Binder call
public void triggerUidSnapshot() {
StatsCompanion.enforceStatsdCallingUid();
synchronized (sStatsdLock) {
@@ -525,7 +530,7 @@
} catch (RemoteException e) {
Log.e(TAG, "Failed to trigger uid snapshot.", e);
} finally {
- restoreCallingIdentity(token);
+ Binder.restoreCallingIdentity(token);
}
}
}
@@ -539,15 +544,28 @@
// Statsd related code
/**
- * Fetches the statsd IBinder service.
- * Note: This should only be called from sayHiToStatsd. All other clients should use the cached
- * sStatsd with a null check.
+ * Fetches the statsd IBinder service. This is a blocking call.
+ * Note: This should only be called from {@link #sayHiToStatsd()}. All other clients should use
+ * the cached sStatsd via {@link #getStatsdNonblocking()}.
*/
- private static IStatsd fetchStatsdService() {
- return IStatsd.Stub.asInterface(StatsFrameworkInitializer
- .getStatsServiceManager()
- .getStatsdServiceRegisterer()
- .get());
+ private IStatsd fetchStatsdService(StatsdDeathRecipient deathRecipient) {
+ synchronized (sStatsdLock) {
+ if (sStatsd == null) {
+ sStatsd = IStatsd.Stub.asInterface(StatsFrameworkInitializer
+ .getStatsServiceManager()
+ .getStatsdServiceRegisterer()
+ .get());
+ if (sStatsd != null) {
+ try {
+ sStatsd.asBinder().linkToDeath(deathRecipient, /* flags */ 0);
+ } catch (RemoteException e) {
+ Log.e(TAG, "linkToDeath(StatsdDeathRecipient) failed");
+ statsdNotReadyLocked();
+ }
+ }
+ }
+ return sStatsd;
+ }
}
/**
@@ -567,67 +585,84 @@
* statsd.
*/
private void sayHiToStatsd() {
- synchronized (sStatsdLock) {
- if (sStatsd != null) {
- Log.e(TAG, "Trying to fetch statsd, but it was already fetched",
- new IllegalStateException(
- "sStatsd is not null when being fetched"));
- return;
- }
- sStatsd = fetchStatsdService();
- if (sStatsd == null) {
- Log.i(TAG,
- "Could not yet find statsd to tell it that StatsCompanion is "
- + "alive.");
- return;
- }
- mStatsManagerService.statsdReady(sStatsd);
- if (DEBUG) Log.d(TAG, "Saying hi to statsd");
+ if (getStatsdNonblocking() != null) {
+ Log.e(TAG, "Trying to fetch statsd, but it was already fetched",
+ new IllegalStateException(
+ "sStatsd is not null when being fetched"));
+ return;
+ }
+ StatsdDeathRecipient deathRecipient = new StatsdDeathRecipient();
+ IStatsd statsd = fetchStatsdService(deathRecipient);
+ if (statsd == null) {
+ Log.i(TAG,
+ "Could not yet find statsd to tell it that StatsCompanion is "
+ + "alive.");
+ return;
+ }
+ mStatsManagerService.statsdReady(statsd);
+ if (DEBUG) Log.d(TAG, "Saying hi to statsd");
+ try {
+ statsd.statsCompanionReady();
+
+ cancelAnomalyAlarm();
+ cancelPullingAlarm();
+
+ BroadcastReceiver appUpdateReceiver = new AppUpdateReceiver();
+ BroadcastReceiver userUpdateReceiver = new UserUpdateReceiver();
+ BroadcastReceiver shutdownEventReceiver = new ShutdownEventReceiver();
+
+ // Setup broadcast receiver for updates.
+ IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
+ filter.addAction(Intent.ACTION_PACKAGE_ADDED);
+ filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+ filter.addDataScheme("package");
+ mContext.registerReceiverForAllUsers(appUpdateReceiver, filter, null, null);
+
+ // Setup receiver for user initialize (which happens once for a new user)
+ // and
+ // if a user is removed.
+ filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
+ filter.addAction(Intent.ACTION_USER_REMOVED);
+ mContext.registerReceiverForAllUsers(userUpdateReceiver, filter, null, null);
+
+ // Setup receiver for device reboots or shutdowns.
+ filter = new IntentFilter(Intent.ACTION_REBOOT);
+ filter.addAction(Intent.ACTION_SHUTDOWN);
+ mContext.registerReceiverForAllUsers(
+ shutdownEventReceiver, filter, null, null);
+
+ // Only add the receivers if the registration is successful.
+ deathRecipient.addRegisteredBroadcastReceivers(
+ List.of(appUpdateReceiver, userUpdateReceiver, shutdownEventReceiver));
+
+ final long token = Binder.clearCallingIdentity();
try {
- sStatsd.statsCompanionReady();
- // If the statsCompanionReady two-way binder call returns, link to statsd.
- try {
- sStatsd.asBinder().linkToDeath(new StatsdDeathRecipient(), 0);
- } catch (RemoteException e) {
- Log.e(TAG, "linkToDeath(StatsdDeathRecipient) failed", e);
- forgetEverythingLocked();
- }
- // Setup broadcast receiver for updates.
- IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REPLACED);
- filter.addAction(Intent.ACTION_PACKAGE_ADDED);
- filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
- filter.addDataScheme("package");
- mContext.registerReceiverForAllUsers(mAppUpdateReceiver, filter, null, null);
-
- // Setup receiver for user initialize (which happens once for a new user)
- // and
- // if a user is removed.
- filter = new IntentFilter(Intent.ACTION_USER_INITIALIZE);
- filter.addAction(Intent.ACTION_USER_REMOVED);
- mContext.registerReceiverForAllUsers(mUserUpdateReceiver, filter, null, null);
-
- // Setup receiver for device reboots or shutdowns.
- filter = new IntentFilter(Intent.ACTION_REBOOT);
- filter.addAction(Intent.ACTION_SHUTDOWN);
- mContext.registerReceiverForAllUsers(
- mShutdownEventReceiver, filter, null, null);
- final long token = Binder.clearCallingIdentity();
- try {
- // Pull the latest state of UID->app name, version mapping when
- // statsd starts.
- informAllUidsLocked(mContext);
- } finally {
- restoreCallingIdentity(token);
- }
- Log.i(TAG, "Told statsd that StatsCompanionService is alive.");
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
- forgetEverythingLocked();
+ // Pull the latest state of UID->app name, version mapping when
+ // statsd starts.
+ informAllUidsLocked(mContext);
+ } finally {
+ Binder.restoreCallingIdentity(token);
}
+ Log.i(TAG, "Told statsd that StatsCompanionService is alive.");
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to inform statsd that statscompanion is ready", e);
}
}
private class StatsdDeathRecipient implements IBinder.DeathRecipient {
+
+ private List<BroadcastReceiver> mReceiversToUnregister;
+
+ StatsdDeathRecipient() {
+ mReceiversToUnregister = new ArrayList<>();
+ }
+
+ public void addRegisteredBroadcastReceivers(List<BroadcastReceiver> receivers) {
+ synchronized (sStatsdLock) {
+ mReceiversToUnregister.addAll(receivers);
+ }
+ }
+
@Override
public void binderDied() {
Log.i(TAG, "Statsd is dead - erase all my knowledge, except pullers");
@@ -656,20 +691,18 @@
}
}
}
- forgetEverythingLocked();
+ // We only unregister in binder death becaseu receivers can only be unregistered
+ // once, or an IllegalArgumentException is thrown.
+ for (BroadcastReceiver receiver: mReceiversToUnregister) {
+ mContext.unregisterReceiver(receiver);
+ }
+ statsdNotReadyLocked();
}
}
}
- @GuardedBy("StatsCompanionService.sStatsdLock")
- private void forgetEverythingLocked() {
+ private void statsdNotReadyLocked() {
sStatsd = null;
- mContext.unregisterReceiver(mAppUpdateReceiver);
- mContext.unregisterReceiver(mUserUpdateReceiver);
- mContext.unregisterReceiver(mShutdownEventReceiver);
- cancelAnomalyAlarm();
- cancelPullingAlarm();
-
mStatsManagerService.statsdNotReady();
}
diff --git a/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java b/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java
index 4e4bc40..58c78da 100644
--- a/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java
+++ b/apex/statsd/service/java/com/android/server/stats/StatsManagerService.java
@@ -136,25 +136,25 @@
}
private static class PullerValue {
- private final long mCoolDownNs;
- private final long mTimeoutNs;
+ private final long mCoolDownMillis;
+ private final long mTimeoutMillis;
private final int[] mAdditiveFields;
private final IPullAtomCallback mCallback;
- PullerValue(long coolDownNs, long timeoutNs, int[] additiveFields,
+ PullerValue(long coolDownMillis, long timeoutMillis, int[] additiveFields,
IPullAtomCallback callback) {
- mCoolDownNs = coolDownNs;
- mTimeoutNs = timeoutNs;
+ mCoolDownMillis = coolDownMillis;
+ mTimeoutMillis = timeoutMillis;
mAdditiveFields = additiveFields;
mCallback = callback;
}
- public long getCoolDownNs() {
- return mCoolDownNs;
+ public long getCoolDownMillis() {
+ return mCoolDownMillis;
}
- public long getTimeoutNs() {
- return mTimeoutNs;
+ public long getTimeoutMillis() {
+ return mTimeoutMillis;
}
public int[] getAdditiveFields() {
@@ -169,12 +169,13 @@
private final ArrayMap<PullerKey, PullerValue> mPullers = new ArrayMap<>();
@Override
- public void registerPullAtomCallback(int atomTag, long coolDownNs, long timeoutNs,
+ public void registerPullAtomCallback(int atomTag, long coolDownMillis, long timeoutMillis,
int[] additiveFields, IPullAtomCallback pullerCallback) {
enforceRegisterStatsPullAtomPermission();
int callingUid = Binder.getCallingUid();
PullerKey key = new PullerKey(callingUid, atomTag);
- PullerValue val = new PullerValue(coolDownNs, timeoutNs, additiveFields, pullerCallback);
+ PullerValue val =
+ new PullerValue(coolDownMillis, timeoutMillis, additiveFields, pullerCallback);
// Always cache the puller in StatsManagerService. If statsd is down, we will register the
// puller when statsd comes back up.
@@ -189,8 +190,8 @@
final long token = Binder.clearCallingIdentity();
try {
- statsd.registerPullAtomCallback(
- callingUid, atomTag, coolDownNs, timeoutNs, additiveFields, pullerCallback);
+ statsd.registerPullAtomCallback(callingUid, atomTag, coolDownMillis, timeoutMillis,
+ additiveFields, pullerCallback);
} catch (RemoteException e) {
Log.e(TAG, "Failed to access statsd to register puller for atom " + atomTag);
} finally {
@@ -596,8 +597,8 @@
for (Map.Entry<PullerKey, PullerValue> entry : pullersCopy.entrySet()) {
PullerKey key = entry.getKey();
PullerValue value = entry.getValue();
- statsd.registerPullAtomCallback(key.getUid(), key.getAtom(), value.getCoolDownNs(),
- value.getTimeoutNs(), value.getAdditiveFields(), value.getCallback());
+ statsd.registerPullAtomCallback(key.getUid(), key.getAtom(), value.getCoolDownMillis(),
+ value.getTimeoutMillis(), value.getAdditiveFields(), value.getCallback());
}
}
diff --git a/apex/statsd/tests/libstatspull/jni/stats_pull_helper.cpp b/apex/statsd/tests/libstatspull/jni/stats_pull_helper.cpp
index eb97f65..9e5aa95 100644
--- a/apex/statsd/tests/libstatspull/jni/stats_pull_helper.cpp
+++ b/apex/statsd/tests/libstatspull/jni/stats_pull_helper.cpp
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-#include <android/binder_process.h>
#include <jni.h>
#include <log/log.h>
#include <stats_event.h>
@@ -32,17 +31,6 @@
static int32_t sAtomsPerPull;
static int32_t sNumPulls = 0;
-static bool initialized = false;
-
-static void init() {
- if (!initialized) {
- initialized = true;
- // Set up the binder
- ABinderProcess_setThreadPoolMaxThreadCount(9);
- ABinderProcess_startThreadPool();
- }
-}
-
static AStatsManager_PullAtomCallbackReturn pullAtomCallback(int32_t atomTag, AStatsEventList* data,
void* /*cookie*/) {
sNumPulls++;
@@ -62,7 +50,6 @@
JNIEnv* /*env*/, jobject /* this */, jint atomTag, jlong timeoutNs, jlong coolDownNs,
jint pullRetVal, jlong latencyMillis, int atomsPerPull)
{
- init();
sAtomTag = atomTag;
sPullReturnVal = pullRetVal;
sLatencyMillis = latencyMillis;
diff --git a/apex/statsd/tests/libstatspull/src/com/android/internal/os/statsd/libstats/LibStatsPullTests.java b/apex/statsd/tests/libstatspull/src/com/android/internal/os/statsd/libstats/LibStatsPullTests.java
index e119b4c..d4e51e0 100644
--- a/apex/statsd/tests/libstatspull/src/com/android/internal/os/statsd/libstats/LibStatsPullTests.java
+++ b/apex/statsd/tests/libstatspull/src/com/android/internal/os/statsd/libstats/LibStatsPullTests.java
@@ -229,7 +229,7 @@
// Let the current bucket finish.
Thread.sleep(LONG_SLEEP_MILLIS);
List<Atom> data = StatsConfigUtils.getGaugeMetricDataList(statsManager, sConfigId);
- statsManager.unregisterPullAtomCallback(PULL_ATOM_TAG);
+ unregisterStatsPuller(PULL_ATOM_TAG);
assertThat(data.size()).isEqualTo(sAtomsPerPull);
for (int i = 0; i < data.size(); i++) {
diff --git a/api/current.txt b/api/current.txt
index 5e64ba9..5e8158b 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -290,6 +290,7 @@
field public static final int allowAudioPlaybackCapture = 16844289; // 0x1010601
field public static final int allowBackup = 16843392; // 0x1010280
field public static final int allowClearUserData = 16842757; // 0x1010005
+ field public static final int allowDontAutoRevokePermissions = 16844309; // 0x1010615
field public static final int allowEmbedded = 16843765; // 0x10103f5
field public static final int allowNativeHeapPointerTagging = 16844307; // 0x1010613
field public static final int allowParallelSyncs = 16843570; // 0x1010332
@@ -315,7 +316,7 @@
field public static final int animationOrder = 16843214; // 0x10101ce
field @Deprecated public static final int animationResolution = 16843546; // 0x101031a
field public static final int antialias = 16843034; // 0x101011a
- field public static final int anyDensity = 16843372; // 0x101026c
+ field @Deprecated public static final int anyDensity = 16843372; // 0x101026c
field public static final int apduServiceBanner = 16843757; // 0x10103ed
field public static final int apiKey = 16843281; // 0x1010211
field public static final int appCategory = 16844101; // 0x1010545
@@ -572,6 +573,7 @@
field public static final int elevation = 16843840; // 0x1010440
field public static final int ellipsize = 16842923; // 0x10100ab
field public static final int ems = 16843096; // 0x1010158
+ field public static final int enableGwpAsan = 16844312; // 0x1010618
field public static final int enableVrMode = 16844069; // 0x1010525
field public static final int enabled = 16842766; // 0x101000e
field public static final int end = 16843996; // 0x10104dc
@@ -620,7 +622,6 @@
field public static final int fastScrollTextColor = 16843609; // 0x1010359
field public static final int fastScrollThumbDrawable = 16843574; // 0x1010336
field public static final int fastScrollTrackDrawable = 16843577; // 0x1010339
- field public static final int featureId = 16844301; // 0x101060d
field public static final int fillAfter = 16843197; // 0x10101bd
field public static final int fillAlpha = 16843980; // 0x10104cc
field public static final int fillBefore = 16843196; // 0x10101bc
@@ -953,7 +954,7 @@
field public static final int mediaRouteButtonStyle = 16843693; // 0x10103ad
field public static final int mediaRouteTypes = 16843694; // 0x10103ae
field public static final int menuCategory = 16843230; // 0x10101de
- field public static final int mimeGroup = 16844309; // 0x1010615
+ field public static final int mimeGroup = 16844311; // 0x1010617
field public static final int mimeType = 16842790; // 0x1010026
field public static final int min = 16844089; // 0x1010539
field public static final int minAspectRatio = 16844187; // 0x101059b
@@ -1082,7 +1083,7 @@
field public static final int preferenceScreenStyle = 16842891; // 0x101008b
field public static final int preferenceStyle = 16842894; // 0x101008e
field public static final int presentationTheme = 16843712; // 0x10103c0
- field public static final int preserveLegacyExternalStorage = 16844308; // 0x1010614
+ field public static final int preserveLegacyExternalStorage = 16844310; // 0x1010616
field public static final int previewImage = 16843482; // 0x10102da
field public static final int primaryContentAlpha = 16844114; // 0x1010552
field public static final int priority = 16842780; // 0x101001c
@@ -1139,6 +1140,7 @@
field public static final int reqKeyboardType = 16843304; // 0x1010228
field public static final int reqNavigation = 16843306; // 0x101022a
field public static final int reqTouchScreen = 16843303; // 0x1010227
+ field public static final int requestDontAutoRevokePermissions = 16844308; // 0x1010614
field public static final int requestLegacyExternalStorage = 16844291; // 0x1010603
field public static final int requireDeviceUnlock = 16843756; // 0x10103ec
field public static final int required = 16843406; // 0x101028e
@@ -4368,7 +4370,7 @@
method @Deprecated public int noteProxyOpNoThrow(@NonNull String, @Nullable String, int);
method public int noteProxyOpNoThrow(@NonNull String, @Nullable String, int, @Nullable String, @Nullable String);
method @Nullable public static String permissionToOp(@NonNull String);
- method public void setNotedAppOpsCollector(@Nullable android.app.AppOpsManager.AppOpsCollector);
+ method public void setOnOpNotedCallback(@Nullable java.util.concurrent.Executor, @Nullable android.app.AppOpsManager.OnOpNotedCallback);
method @Deprecated public int startOp(@NonNull String, int, @NonNull String);
method public int startOp(@NonNull String, int, @Nullable String, @Nullable String, @Nullable String);
method @Deprecated public int startOpNoThrow(@NonNull String, int, @NonNull String);
@@ -4424,14 +4426,6 @@
field public static final int WATCH_FOREGROUND_CHANGES = 1; // 0x1
}
- public abstract static class AppOpsManager.AppOpsCollector {
- ctor public AppOpsManager.AppOpsCollector();
- method @NonNull public java.util.concurrent.Executor getAsyncNotedExecutor();
- method public abstract void onAsyncNoted(@NonNull android.app.AsyncNotedAppOp);
- method public abstract void onNoted(@NonNull android.app.SyncNotedAppOp);
- method public abstract void onSelfNoted(@NonNull android.app.SyncNotedAppOp);
- }
-
public static interface AppOpsManager.OnOpActiveChangedListener {
method public void onOpActiveChanged(@NonNull String, int, @NonNull String, boolean);
}
@@ -4440,6 +4434,13 @@
method public void onOpChanged(String, String);
}
+ public abstract static class AppOpsManager.OnOpNotedCallback {
+ ctor public AppOpsManager.OnOpNotedCallback();
+ method public abstract void onAsyncNoted(@NonNull android.app.AsyncNotedAppOp);
+ method public abstract void onNoted(@NonNull android.app.SyncNotedAppOp);
+ method public abstract void onSelfNoted(@NonNull android.app.SyncNotedAppOp);
+ }
+
public class Application extends android.content.ContextWrapper implements android.content.ComponentCallbacks2 {
ctor public Application();
method public static String getProcessName();
@@ -4587,11 +4588,11 @@
public final class AsyncNotedAppOp implements android.os.Parcelable {
method public int describeContents();
- method @Nullable public String getFeatureId();
+ method @Nullable public String getAttributionTag();
method @NonNull public String getMessage();
method @IntRange(from=0) public int getNotingUid();
method @NonNull public String getOp();
- method @IntRange(from=0) public long getTime();
+ method public long getTime();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.AsyncNotedAppOp> CREATOR;
}
@@ -6431,7 +6432,7 @@
public final class SyncNotedAppOp implements android.os.Parcelable {
ctor public SyncNotedAppOp(@IntRange(from=0L) int, @Nullable String);
method public int describeContents();
- method @Nullable public String getFeatureId();
+ method @Nullable public String getAttributionTag();
method @NonNull public String getOp();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.SyncNotedAppOp> CREATOR;
@@ -6857,9 +6858,9 @@
method @Nullable public String getAlwaysOnVpnPackage(@NonNull android.content.ComponentName);
method @NonNull @WorkerThread public android.os.Bundle getApplicationRestrictions(@Nullable android.content.ComponentName, String);
method @Deprecated @Nullable public String getApplicationRestrictionsManagingPackage(@NonNull android.content.ComponentName);
- method public boolean getAutoTime(@NonNull android.content.ComponentName);
+ method public boolean getAutoTimeEnabled(@NonNull android.content.ComponentName);
method @Deprecated public boolean getAutoTimeRequired();
- method public boolean getAutoTimeZone(@NonNull android.content.ComponentName);
+ method public boolean getAutoTimeZoneEnabled(@NonNull android.content.ComponentName);
method @NonNull public java.util.List<android.os.UserHandle> getBindDeviceAdminTargetUsers(@NonNull android.content.ComponentName);
method public boolean getBluetoothContactSharingDisabled(@NonNull android.content.ComponentName);
method public boolean getCameraDisabled(@Nullable android.content.ComponentName);
@@ -6911,7 +6912,6 @@
method @Nullable public java.util.List<java.lang.String> getPermittedCrossProfileNotificationListeners(@NonNull android.content.ComponentName);
method @Nullable public java.util.List<java.lang.String> getPermittedInputMethods(@NonNull android.content.ComponentName);
method public int getPersonalAppsSuspendedReasons(@NonNull android.content.ComponentName);
- method @NonNull public java.util.List<java.lang.String> getProtectedPackages(@NonNull android.content.ComponentName);
method public long getRequiredStrongAuthTimeout(@Nullable android.content.ComponentName);
method public boolean getScreenCaptureDisabled(@Nullable android.content.ComponentName);
method public java.util.List<android.os.UserHandle> getSecondaryUsers(@NonNull android.content.ComponentName);
@@ -6922,6 +6922,7 @@
method @Nullable public android.app.admin.SystemUpdatePolicy getSystemUpdatePolicy();
method @Nullable public android.os.PersistableBundle getTransferOwnershipBundle();
method @Nullable public java.util.List<android.os.PersistableBundle> getTrustAgentConfiguration(@Nullable android.content.ComponentName, @NonNull android.content.ComponentName);
+ method @NonNull public java.util.List<java.lang.String> getUserControlDisabledPackages(@NonNull android.content.ComponentName);
method @NonNull public android.os.Bundle getUserRestrictions(@NonNull android.content.ComponentName);
method @Nullable public String getWifiMacAddress(@NonNull android.content.ComponentName);
method public boolean grantKeyPairToApp(@Nullable android.content.ComponentName, @NonNull String, @NonNull String);
@@ -6983,9 +6984,9 @@
method public boolean setApplicationHidden(@NonNull android.content.ComponentName, String, boolean);
method @WorkerThread public void setApplicationRestrictions(@Nullable android.content.ComponentName, String, android.os.Bundle);
method @Deprecated public void setApplicationRestrictionsManagingPackage(@NonNull android.content.ComponentName, @Nullable String) throws android.content.pm.PackageManager.NameNotFoundException;
- method public void setAutoTime(@NonNull android.content.ComponentName, boolean);
+ method public void setAutoTimeEnabled(@NonNull android.content.ComponentName, boolean);
method @Deprecated public void setAutoTimeRequired(@NonNull android.content.ComponentName, boolean);
- method public void setAutoTimeZone(@NonNull android.content.ComponentName, boolean);
+ method public void setAutoTimeZoneEnabled(@NonNull android.content.ComponentName, boolean);
method public void setBackupServiceEnabled(@NonNull android.content.ComponentName, boolean);
method public void setBluetoothContactSharingDisabled(@NonNull android.content.ComponentName, boolean);
method public void setCameraDisabled(@NonNull android.content.ComponentName, boolean);
@@ -7041,7 +7042,6 @@
method public void setPersonalAppsSuspended(@NonNull android.content.ComponentName, boolean);
method public void setProfileEnabled(@NonNull android.content.ComponentName);
method public void setProfileName(@NonNull android.content.ComponentName, String);
- method public void setProtectedPackages(@NonNull android.content.ComponentName, @NonNull java.util.List<java.lang.String>);
method public void setRecommendedGlobalProxy(@NonNull android.content.ComponentName, @Nullable android.net.ProxyInfo);
method public void setRequiredStrongAuthTimeout(@NonNull android.content.ComponentName, long);
method public boolean setResetPasswordToken(android.content.ComponentName, byte[]);
@@ -7060,6 +7060,7 @@
method public boolean setTimeZone(@NonNull android.content.ComponentName, String);
method public void setTrustAgentConfiguration(@NonNull android.content.ComponentName, @NonNull android.content.ComponentName, android.os.PersistableBundle);
method public void setUninstallBlocked(@Nullable android.content.ComponentName, String, boolean);
+ method public void setUserControlDisabledPackages(@NonNull android.content.ComponentName, @NonNull java.util.List<java.lang.String>);
method public void setUserIcon(@NonNull android.content.ComponentName, android.graphics.Bitmap);
method public int startUserInBackground(@NonNull android.content.ComponentName, @NonNull android.os.UserHandle);
method public int stopUser(@NonNull android.content.ComponentName, @NonNull android.os.UserHandle);
@@ -7583,12 +7584,12 @@
}
public class BlobStoreManager {
+ method public void abandonSession(@IntRange(from=1) long) throws java.io.IOException;
method public void acquireLease(@NonNull android.app.blob.BlobHandle, @IdRes int, long) throws java.io.IOException;
method public void acquireLease(@NonNull android.app.blob.BlobHandle, @NonNull CharSequence, long) throws java.io.IOException;
method public void acquireLease(@NonNull android.app.blob.BlobHandle, @IdRes int) throws java.io.IOException;
method public void acquireLease(@NonNull android.app.blob.BlobHandle, @NonNull CharSequence) throws java.io.IOException;
method @IntRange(from=1) public long createSession(@NonNull android.app.blob.BlobHandle) throws java.io.IOException;
- method public void deleteSession(@IntRange(from=1) long) throws java.io.IOException;
method @NonNull public android.os.ParcelFileDescriptor openBlob(@NonNull android.app.blob.BlobHandle) throws java.io.IOException;
method @NonNull public android.app.blob.BlobStoreManager.Session openSession(@IntRange(from=1) long) throws java.io.IOException;
method public void releaseLease(@NonNull android.app.blob.BlobHandle) throws java.io.IOException;
@@ -9467,7 +9468,7 @@
public static final class WifiDeviceFilter.Builder {
ctor public WifiDeviceFilter.Builder();
method @NonNull public android.companion.WifiDeviceFilter build();
- method @NonNull public android.companion.WifiDeviceFilter.Builder setBssid(@Nullable android.net.MacAddress);
+ method @NonNull public android.companion.WifiDeviceFilter.Builder setBssid(@NonNull android.net.MacAddress);
method @NonNull public android.companion.WifiDeviceFilter.Builder setBssidMask(@NonNull android.net.MacAddress);
method @NonNull public android.companion.WifiDeviceFilter.Builder setNamePattern(@Nullable java.util.regex.Pattern);
}
@@ -9697,7 +9698,7 @@
method public abstract int delete(@NonNull android.net.Uri, @Nullable String, @Nullable String[]);
method public int delete(@NonNull android.net.Uri, @Nullable android.os.Bundle);
method public void dump(java.io.FileDescriptor, java.io.PrintWriter, String[]);
- method @Nullable public final String getCallingFeatureId();
+ method @Nullable public final String getCallingAttributionTag();
method @Nullable public final String getCallingPackage();
method @Nullable public final String getCallingPackageUnchecked();
method @Nullable public final android.content.Context getContext();
@@ -9882,7 +9883,7 @@
method public void notifyChange(@NonNull android.net.Uri, @Nullable android.database.ContentObserver);
method @Deprecated public void notifyChange(@NonNull android.net.Uri, @Nullable android.database.ContentObserver, boolean);
method public void notifyChange(@NonNull android.net.Uri, @Nullable android.database.ContentObserver, int);
- method public void notifyChange(@NonNull Iterable<android.net.Uri>, @Nullable android.database.ContentObserver, int);
+ method public void notifyChange(@NonNull java.util.Collection<android.net.Uri>, @Nullable android.database.ContentObserver, int);
method @Nullable public final android.content.res.AssetFileDescriptor openAssetFile(@NonNull android.net.Uri, @NonNull String, @Nullable android.os.CancellationSignal) throws java.io.FileNotFoundException;
method @Nullable public final android.content.res.AssetFileDescriptor openAssetFileDescriptor(@NonNull android.net.Uri, @NonNull String) throws java.io.FileNotFoundException;
method @Nullable public final android.content.res.AssetFileDescriptor openAssetFileDescriptor(@NonNull android.net.Uri, @NonNull String, @Nullable android.os.CancellationSignal) throws java.io.FileNotFoundException;
@@ -10031,11 +10032,11 @@
method @CheckResult(suggest="#enforceUriPermission(Uri,int,int,String)") public abstract int checkUriPermission(android.net.Uri, int, int, int);
method @CheckResult(suggest="#enforceUriPermission(Uri,String,String,int,int,int,String)") public abstract int checkUriPermission(@Nullable android.net.Uri, @Nullable String, @Nullable String, int, int, int);
method @Deprecated public abstract void clearWallpaper() throws java.io.IOException;
+ method @NonNull public android.content.Context createAttributionContext(@Nullable String);
method public abstract android.content.Context createConfigurationContext(@NonNull android.content.res.Configuration);
method public abstract android.content.Context createContextForSplit(String) throws android.content.pm.PackageManager.NameNotFoundException;
method public abstract android.content.Context createDeviceProtectedStorageContext();
method public abstract android.content.Context createDisplayContext(@NonNull android.view.Display);
- method @NonNull public android.content.Context createFeatureContext(@Nullable String);
method public abstract android.content.Context createPackageContext(String, int) throws android.content.pm.PackageManager.NameNotFoundException;
method @NonNull public android.content.Context createWindowContext(int, @Nullable android.os.Bundle);
method public abstract String[] databaseList();
@@ -10053,6 +10054,7 @@
method public abstract android.content.Context getApplicationContext();
method public abstract android.content.pm.ApplicationInfo getApplicationInfo();
method public abstract android.content.res.AssetManager getAssets();
+ method @Nullable public String getAttributionTag();
method public abstract java.io.File getCacheDir();
method public abstract ClassLoader getClassLoader();
method public abstract java.io.File getCodeCacheDir();
@@ -10069,7 +10071,6 @@
method @Nullable public abstract java.io.File getExternalFilesDir(@Nullable String);
method public abstract java.io.File[] getExternalFilesDirs(String);
method @Deprecated public abstract java.io.File[] getExternalMediaDirs();
- method @Nullable public String getFeatureId();
method public abstract java.io.File getFileStreamPath(String);
method public abstract java.io.File getFilesDir();
method public java.util.concurrent.Executor getMainExecutor();
@@ -10566,6 +10567,7 @@
field public static final String ACTION_APP_ERROR = "android.intent.action.APP_ERROR";
field public static final String ACTION_ASSIST = "android.intent.action.ASSIST";
field public static final String ACTION_ATTACH_DATA = "android.intent.action.ATTACH_DATA";
+ field public static final String ACTION_AUTO_REVOKE_PERMISSIONS = "android.intent.action.AUTO_REVOKE_PERMISSIONS";
field public static final String ACTION_BATTERY_CHANGED = "android.intent.action.BATTERY_CHANGED";
field public static final String ACTION_BATTERY_LOW = "android.intent.action.BATTERY_LOW";
field public static final String ACTION_BATTERY_OKAY = "android.intent.action.BATTERY_OKAY";
@@ -10806,6 +10808,7 @@
field public static final String EXTRA_TEMPLATE = "android.intent.extra.TEMPLATE";
field public static final String EXTRA_TEXT = "android.intent.extra.TEXT";
field public static final String EXTRA_TIME = "android.intent.extra.TIME";
+ field public static final String EXTRA_TIMEZONE = "time-zone";
field public static final String EXTRA_TITLE = "android.intent.extra.TITLE";
field public static final String EXTRA_UID = "android.intent.extra.UID";
field public static final String EXTRA_USER = "android.intent.extra.USER";
@@ -11438,6 +11441,7 @@
method public int describeContents();
method public void dump(android.util.Printer, String);
method public static CharSequence getCategoryTitle(android.content.Context, int);
+ method @Nullable public Boolean isGwpAsanEnabled();
method public boolean isProfileableByShell();
method public boolean isResourceOverlay();
method public boolean isVirtualPreload();
@@ -11475,7 +11479,7 @@
field public static final int FLAG_SUPPORTS_LARGE_SCREENS = 2048; // 0x800
field public static final int FLAG_SUPPORTS_NORMAL_SCREENS = 1024; // 0x400
field public static final int FLAG_SUPPORTS_RTL = 4194304; // 0x400000
- field public static final int FLAG_SUPPORTS_SCREEN_DENSITIES = 8192; // 0x2000
+ field @Deprecated public static final int FLAG_SUPPORTS_SCREEN_DENSITIES = 8192; // 0x2000
field public static final int FLAG_SUPPORTS_SMALL_SCREENS = 512; // 0x200
field public static final int FLAG_SUPPORTS_XLARGE_SCREENS = 524288; // 0x80000
field public static final int FLAG_SUSPENDED = 1073741824; // 0x40000000
@@ -11571,6 +11575,7 @@
method @NonNull public CharSequence getProfileSwitchingLabel(@NonNull android.os.UserHandle);
method @NonNull public java.util.List<android.os.UserHandle> getTargetUserProfiles();
method @RequiresPermission(anyOf={android.Manifest.permission.INTERACT_ACROSS_PROFILES, "android.permission.INTERACT_ACROSS_USERS"}) public void startActivity(@NonNull android.content.Intent, @NonNull android.os.UserHandle, @Nullable android.app.Activity);
+ method @RequiresPermission(anyOf={android.Manifest.permission.INTERACT_ACROSS_PROFILES, "android.permission.INTERACT_ACROSS_USERS"}) public void startActivity(@NonNull android.content.Intent, @NonNull android.os.UserHandle, @Nullable android.app.Activity, @Nullable android.os.Bundle);
method public void startMainActivity(@NonNull android.content.ComponentName, @NonNull android.os.UserHandle);
field public static final String ACTION_CAN_INTERACT_ACROSS_PROFILES_CHANGED = "android.content.pm.action.CAN_INTERACT_ACROSS_PROFILES_CHANGED";
}
@@ -11891,6 +11896,7 @@
method public void setAppIcon(@Nullable android.graphics.Bitmap);
method public void setAppLabel(@Nullable CharSequence);
method public void setAppPackageName(@Nullable String);
+ method public void setAutoRevokePermissionsMode(boolean);
method public void setInstallLocation(int);
method public void setInstallReason(int);
method public void setMultiPackage();
@@ -12020,6 +12026,8 @@
method public boolean hasSigningCertificate(int, @NonNull byte[], int);
method public abstract boolean hasSystemFeature(@NonNull String);
method public abstract boolean hasSystemFeature(@NonNull String, int);
+ method @RequiresPermission(value="android.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS", conditional=true) public boolean isAutoRevokeWhitelisted(@NonNull String);
+ method public boolean isAutoRevokeWhitelisted();
method public boolean isDefaultApplicationIcon(@NonNull android.graphics.drawable.Drawable);
method public boolean isDeviceUpgrading();
method public abstract boolean isInstantApp();
@@ -12044,6 +12052,7 @@
method @Nullable public abstract android.content.pm.ResolveInfo resolveService(@NonNull android.content.Intent, int);
method public abstract void setApplicationCategoryHint(@NonNull String, int);
method @RequiresPermission(value=android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE, conditional=true) public abstract void setApplicationEnabledSetting(@NonNull String, int, int);
+ method @RequiresPermission(value="android.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS", conditional=true) public boolean setAutoRevokeWhitelisted(@NonNull String, boolean);
method @RequiresPermission(value=android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE, conditional=true) public abstract void setComponentEnabledSetting(@NonNull android.content.ComponentName, int, int);
method public abstract void setInstallerPackageName(@NonNull String, @Nullable String);
method public void setMimeGroup(@NonNull String, @NonNull java.util.Set<java.lang.String>);
@@ -12972,11 +12981,11 @@
method @Deprecated public final void dispatchChange(boolean);
method public final void dispatchChange(boolean, @Nullable android.net.Uri);
method public final void dispatchChange(boolean, @Nullable android.net.Uri, int);
- method public final void dispatchChange(boolean, @NonNull Iterable<android.net.Uri>, int);
+ method public final void dispatchChange(boolean, @NonNull java.util.Collection<android.net.Uri>, int);
method public void onChange(boolean);
method public void onChange(boolean, @Nullable android.net.Uri);
method public void onChange(boolean, @Nullable android.net.Uri, int);
- method public void onChange(boolean, @NonNull Iterable<android.net.Uri>, int);
+ method public void onChange(boolean, @NonNull java.util.Collection<android.net.Uri>, int);
}
public interface CrossProcessCursor extends android.database.Cursor {
@@ -17350,7 +17359,7 @@
public final class CameraManager {
method @NonNull public android.hardware.camera2.CameraCharacteristics getCameraCharacteristics(@NonNull String) throws android.hardware.camera2.CameraAccessException;
method @NonNull public String[] getCameraIdList() throws android.hardware.camera2.CameraAccessException;
- method @NonNull public java.util.Set<java.util.Set<java.lang.String>> getConcurrentStreamingCameraIds() throws android.hardware.camera2.CameraAccessException;
+ method @NonNull public java.util.Set<java.util.Set<java.lang.String>> getConcurrentCameraIds() throws android.hardware.camera2.CameraAccessException;
method @RequiresPermission(android.Manifest.permission.CAMERA) public boolean isConcurrentSessionConfigurationSupported(@NonNull java.util.Map<java.lang.String,android.hardware.camera2.params.SessionConfiguration>) throws android.hardware.camera2.CameraAccessException;
method @RequiresPermission(android.Manifest.permission.CAMERA) public void openCamera(@NonNull String, @NonNull android.hardware.camera2.CameraDevice.StateCallback, @Nullable android.os.Handler) throws android.hardware.camera2.CameraAccessException;
method @RequiresPermission(android.Manifest.permission.CAMERA) public void openCamera(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.hardware.camera2.CameraDevice.StateCallback) throws android.hardware.camera2.CameraAccessException;
@@ -18118,9 +18127,7 @@
ctor @Deprecated public FingerprintManager.CryptoObject(@NonNull java.security.Signature);
ctor @Deprecated public FingerprintManager.CryptoObject(@NonNull javax.crypto.Cipher);
ctor @Deprecated public FingerprintManager.CryptoObject(@NonNull javax.crypto.Mac);
- ctor @Deprecated public FingerprintManager.CryptoObject(@NonNull android.security.identity.IdentityCredential);
method @Deprecated public javax.crypto.Cipher getCipher();
- method @Deprecated @Nullable public android.security.identity.IdentityCredential getIdentityCredential();
method @Deprecated public javax.crypto.Mac getMac();
method @Deprecated public java.security.Signature getSignature();
}
@@ -20094,8 +20101,7 @@
method public T numberFormatterSecond(android.icu.number.UnlocalizedNumberFormatter);
}
- public abstract class Precision implements java.lang.Cloneable {
- method public Object clone();
+ public abstract class Precision {
method public static android.icu.number.CurrencyPrecision currency(android.icu.util.Currency.CurrencyUsage);
method public static android.icu.number.FractionPrecision fixedFraction(int);
method public static android.icu.number.Precision fixedSignificantDigits(int);
@@ -20118,8 +20124,7 @@
method public static android.icu.number.Scale powerOfTen(int);
}
- public class ScientificNotation extends android.icu.number.Notation implements java.lang.Cloneable {
- method public Object clone();
+ public class ScientificNotation extends android.icu.number.Notation {
method public android.icu.number.ScientificNotation withExponentSignDisplay(android.icu.number.NumberFormatter.SignDisplay);
method public android.icu.number.ScientificNotation withMinExponentDigits(int);
}
@@ -26450,14 +26455,14 @@
public static interface MediaParser.OutputConsumer {
method public void onSampleCompleted(int, long, int, int, int, @Nullable android.media.MediaCodec.CryptoInfo);
- method public void onSampleData(int, @NonNull android.media.MediaParser.InputReader) throws java.io.IOException;
- method public void onSeekMap(@NonNull android.media.MediaParser.SeekMap);
- method public void onTrackData(int, @NonNull android.media.MediaParser.TrackData);
- method public void onTracksFound(int);
+ method public void onSampleDataFound(int, @NonNull android.media.MediaParser.InputReader) throws java.io.IOException;
+ method public void onSeekMapFound(@NonNull android.media.MediaParser.SeekMap);
+ method public void onTrackCountFound(int);
+ method public void onTrackDataFound(int, @NonNull android.media.MediaParser.TrackData);
}
public static final class MediaParser.SeekMap {
- method public long getDurationUs();
+ method public long getDurationMicros();
method @NonNull public android.util.Pair<android.media.MediaParser.SeekPoint,android.media.MediaParser.SeekPoint> getSeekPoints(long);
method public boolean isSeekable();
field public static final int UNKNOWN_DURATION = -2147483648; // 0x80000000
@@ -26466,7 +26471,7 @@
public static final class MediaParser.SeekPoint {
field @NonNull public static final android.media.MediaParser.SeekPoint START;
field public final long position;
- field public final long timeUs;
+ field public final long timeMicros;
}
public static interface MediaParser.SeekableInputReader extends android.media.MediaParser.InputReader {
@@ -26858,7 +26863,6 @@
method @Nullable public String getClientPackageName();
method public int getConnectionState();
method @Nullable public CharSequence getDescription();
- method public int getDeviceType();
method @Nullable public android.os.Bundle getExtras();
method @NonNull public java.util.List<java.lang.String> getFeatures();
method @Nullable public android.net.Uri getIconUri();
@@ -26873,10 +26877,6 @@
field public static final int CONNECTION_STATE_CONNECTING = 1; // 0x1
field public static final int CONNECTION_STATE_DISCONNECTED = 0; // 0x0
field @NonNull public static final android.os.Parcelable.Creator<android.media.MediaRoute2Info> CREATOR;
- field public static final int DEVICE_TYPE_BLUETOOTH = 3; // 0x3
- field public static final int DEVICE_TYPE_REMOTE_SPEAKER = 2; // 0x2
- field public static final int DEVICE_TYPE_REMOTE_TV = 1; // 0x1
- field public static final int DEVICE_TYPE_UNKNOWN = 0; // 0x0
field public static final String FEATURE_LIVE_AUDIO = "android.media.intent.category.LIVE_AUDIO";
field public static final String FEATURE_LIVE_VIDEO = "android.media.intent.category.LIVE_VIDEO";
field public static final String FEATURE_REMOTE_PLAYBACK = "android.media.intent.category.REMOTE_PLAYBACK";
@@ -26894,7 +26894,6 @@
method @NonNull public android.media.MediaRoute2Info.Builder setClientPackageName(@Nullable String);
method @NonNull public android.media.MediaRoute2Info.Builder setConnectionState(int);
method @NonNull public android.media.MediaRoute2Info.Builder setDescription(@Nullable CharSequence);
- method @NonNull public android.media.MediaRoute2Info.Builder setDeviceType(int);
method @NonNull public android.media.MediaRoute2Info.Builder setExtras(@Nullable android.os.Bundle);
method @NonNull public android.media.MediaRoute2Info.Builder setIconUri(@Nullable android.net.Uri);
method @NonNull public android.media.MediaRoute2Info.Builder setVolume(int);
@@ -26908,7 +26907,7 @@
method @Nullable public final android.media.RoutingSessionInfo getSessionInfo(@NonNull String);
method public final void notifyRequestFailed(long, int);
method public final void notifyRoutes(@NonNull java.util.Collection<android.media.MediaRoute2Info>);
- method public final void notifySessionCreated(@NonNull android.media.RoutingSessionInfo, long);
+ method public final void notifySessionCreated(long, @NonNull android.media.RoutingSessionInfo);
method public final void notifySessionReleased(@NonNull String);
method public final void notifySessionUpdated(@NonNull android.media.RoutingSessionInfo);
method @CallSuper @Nullable public android.os.IBinder onBind(@NonNull android.content.Intent);
@@ -27052,7 +27051,7 @@
method public abstract void onVolumeUpdateRequest(android.media.MediaRouter.RouteInfo, int);
}
- public class MediaRouter2 {
+ public final class MediaRouter2 {
method @NonNull public java.util.List<android.media.MediaRouter2.RoutingController> getControllers();
method @NonNull public static android.media.MediaRouter2 getInstance(@NonNull android.content.Context);
method @NonNull public java.util.List<android.media.MediaRoute2Info> getRoutes();
@@ -27061,7 +27060,8 @@
method public void registerRouteCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.MediaRouter2.RouteCallback, @NonNull android.media.RouteDiscoveryPreference);
method public void registerTransferCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.MediaRouter2.TransferCallback);
method public void setOnGetControllerHintsListener(@Nullable android.media.MediaRouter2.OnGetControllerHintsListener);
- method public void transferTo(@Nullable android.media.MediaRoute2Info);
+ method public void stop();
+ method public void transferTo(@NonNull android.media.MediaRoute2Info);
method public void unregisterControllerCallback(@NonNull android.media.MediaRouter2.ControllerCallback);
method public void unregisterRouteCallback(@NonNull android.media.MediaRouter2.RouteCallback);
method public void unregisterTransferCallback(@NonNull android.media.MediaRouter2.TransferCallback);
@@ -27101,8 +27101,9 @@
public abstract static class MediaRouter2.TransferCallback {
ctor public MediaRouter2.TransferCallback();
+ method public void onStopped(@NonNull android.media.MediaRouter2.RoutingController);
method public void onTransferFailed(@NonNull android.media.MediaRoute2Info);
- method public void onTransferred(@NonNull android.media.MediaRouter2.RoutingController, @Nullable android.media.MediaRouter2.RoutingController);
+ method public void onTransferred(@NonNull android.media.MediaRouter2.RoutingController, @NonNull android.media.MediaRouter2.RoutingController);
}
public class MediaScannerConnection implements android.content.ServiceConnection {
@@ -36160,6 +36161,8 @@
method public static boolean isExternalStorageEmulated(@NonNull java.io.File);
method public static boolean isExternalStorageLegacy();
method public static boolean isExternalStorageLegacy(@NonNull java.io.File);
+ method public static boolean isExternalStorageManager();
+ method public static boolean isExternalStorageManager(@NonNull java.io.File);
method public static boolean isExternalStorageRemovable();
method public static boolean isExternalStorageRemovable(@NonNull java.io.File);
field public static String DIRECTORY_ALARMS;
@@ -36594,6 +36597,7 @@
method public static android.os.ParcelFileDescriptor open(java.io.File, int) throws java.io.FileNotFoundException;
method public static android.os.ParcelFileDescriptor open(java.io.File, int, android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener) throws java.io.IOException;
method public static int parseMode(String);
+ method @NonNull public static android.os.ParcelFileDescriptor wrap(@NonNull android.os.ParcelFileDescriptor, @NonNull android.os.Handler, @NonNull android.os.ParcelFileDescriptor.OnCloseListener) throws java.io.IOException;
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.os.ParcelFileDescriptor> CREATOR;
field public static final int MODE_APPEND = 33554432; // 0x2000000
@@ -37156,12 +37160,10 @@
method @Nullable public android.os.VibrationEffect.Composition addPrimitive(int, @FloatRange(from=0.0f, to=1.0f) float, @IntRange(from=0) int);
method @NonNull public android.os.VibrationEffect compose();
field public static final int PRIMITIVE_CLICK = 1; // 0x1
- field public static final int PRIMITIVE_LIGHT_TICK = 7; // 0x7
field public static final int PRIMITIVE_QUICK_FALL = 6; // 0x6
field public static final int PRIMITIVE_QUICK_RISE = 4; // 0x4
field public static final int PRIMITIVE_SLOW_RISE = 5; // 0x5
- field public static final int PRIMITIVE_SPIN = 3; // 0x3
- field public static final int PRIMITIVE_THUD = 2; // 0x2
+ field public static final int PRIMITIVE_TICK = 7; // 0x7
}
public abstract class Vibrator {
@@ -40574,7 +40576,7 @@
field public static final String EXTRA_APP_PACKAGE = "android.provider.extra.APP_PACKAGE";
field public static final String EXTRA_AUTHORITIES = "authorities";
field public static final String EXTRA_BATTERY_SAVER_MODE_ENABLED = "android.settings.extra.battery_saver_mode_enabled";
- field public static final String EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED = "android.provider.extra.BIOMETRIC_MINIMUM_STRENGTH_REQUIRED";
+ field public static final String EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED = "android.provider.extra.BIOMETRIC_AUTHENTICATORS_ALLOWED";
field public static final String EXTRA_CHANNEL_ID = "android.provider.extra.CHANNEL_ID";
field public static final String EXTRA_CONVERSATION_ID = "android.provider.extra.CONVERSATION_ID";
field public static final String EXTRA_DO_NOT_DISTURB_MODE_ENABLED = "android.settings.extra.do_not_disturb_mode_enabled";
@@ -40717,6 +40719,7 @@
field public static final String PARENTAL_CONTROL_LAST_UPDATE = "parental_control_last_update";
field public static final String PARENTAL_CONTROL_REDIRECT_URL = "parental_control_redirect_url";
field public static final String RTT_CALLING_MODE = "rtt_calling_mode";
+ field public static final String SECURE_FRP_MODE = "secure_frp_mode";
field public static final String SELECTED_INPUT_METHOD_SUBTYPE = "selected_input_method_subtype";
field public static final String SETTINGS_CLASSNAME = "settings_classname";
field public static final String SKIP_FIRST_USE_HINTS = "skip_first_use_hints";
@@ -42695,7 +42698,7 @@
ctor public PersonalizationData.Builder();
method @NonNull public android.security.identity.PersonalizationData.Builder addAccessControlProfile(@NonNull android.security.identity.AccessControlProfile);
method @NonNull public android.security.identity.PersonalizationData build();
- method @NonNull public android.security.identity.PersonalizationData.Builder setEntry(@NonNull String, @NonNull String, @NonNull java.util.Collection<android.security.identity.AccessControlProfileId>, @NonNull byte[]);
+ method @NonNull public android.security.identity.PersonalizationData.Builder putEntry(@NonNull String, @NonNull String, @NonNull java.util.Collection<android.security.identity.AccessControlProfileId>, @NonNull byte[]);
}
public abstract class ResultData {
@@ -42703,7 +42706,7 @@
method @Nullable public abstract byte[] getEntry(@NonNull String, @NonNull String);
method @Nullable public abstract java.util.Collection<java.lang.String> getEntryNames(@NonNull String);
method @Nullable public abstract byte[] getMessageAuthenticationCode();
- method @NonNull public abstract java.util.Collection<java.lang.String> getNamespaceNames();
+ method @NonNull public abstract java.util.Collection<java.lang.String> getNamespaces();
method @Nullable public abstract java.util.Collection<java.lang.String> getRetrievedEntryNames(@NonNull String);
method @NonNull public abstract byte[] getStaticAuthenticationData();
method public abstract int getStatus(@NonNull String, @NonNull String);
@@ -43015,12 +43018,12 @@
}
public static final class Dataset.Builder {
- ctor public Dataset.Builder(@NonNull android.widget.RemoteViews, @NonNull android.service.autofill.InlinePresentation);
ctor public Dataset.Builder(@NonNull android.widget.RemoteViews);
ctor public Dataset.Builder();
method @NonNull public android.service.autofill.Dataset build();
method @NonNull public android.service.autofill.Dataset.Builder setAuthentication(@Nullable android.content.IntentSender);
method @NonNull public android.service.autofill.Dataset.Builder setId(@Nullable String);
+ method @NonNull public android.service.autofill.Dataset.Builder setInlinePresentation(@NonNull android.service.autofill.InlinePresentation);
method @NonNull public android.service.autofill.Dataset.Builder setValue(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue);
method @NonNull public android.service.autofill.Dataset.Builder setValue(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @NonNull android.widget.RemoteViews);
method @NonNull public android.service.autofill.Dataset.Builder setValue(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern);
@@ -43115,7 +43118,7 @@
public static final class FillResponse.Builder {
ctor public FillResponse.Builder();
method @NonNull public android.service.autofill.FillResponse.Builder addDataset(@Nullable android.service.autofill.Dataset);
- method @NonNull public android.service.autofill.FillResponse.Builder addInlineAction(@NonNull android.service.autofill.InlinePresentation);
+ method @NonNull public android.service.autofill.FillResponse.Builder addInlineAction(@NonNull android.service.autofill.InlineAction);
method @NonNull public android.service.autofill.FillResponse build();
method @NonNull public android.service.autofill.FillResponse.Builder disableAutofill(long);
method @NonNull public android.service.autofill.FillResponse.Builder setAuthentication(@NonNull android.view.autofill.AutofillId[], @Nullable android.content.IntentSender, @Nullable android.widget.RemoteViews);
@@ -43145,6 +43148,15 @@
method public android.service.autofill.ImageTransformation build();
}
+ public final class InlineAction implements android.os.Parcelable {
+ ctor public InlineAction(@NonNull android.service.autofill.InlinePresentation, @NonNull android.content.IntentSender);
+ method public int describeContents();
+ method @NonNull public android.content.IntentSender getAction();
+ method @NonNull public android.service.autofill.InlinePresentation getInlinePresentation();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.service.autofill.InlineAction> CREATOR;
+ }
+
public final class InlinePresentation implements android.os.Parcelable {
ctor public InlinePresentation(@NonNull android.app.slice.Slice, @NonNull android.view.inline.InlinePresentationSpec, boolean);
method public int describeContents();
@@ -43513,6 +43525,7 @@
field public static final int TYPE_RADIATOR = 16; // 0x10
field public static final int TYPE_REFRIGERATOR = 48; // 0x30
field public static final int TYPE_REMOTE_CONTROL = 17; // 0x11
+ field public static final int TYPE_ROUTINE = 52; // 0x34
field public static final int TYPE_SECURITY_SYSTEM = 46; // 0x2e
field public static final int TYPE_SET_TOP = 18; // 0x12
field public static final int TYPE_SHOWER = 29; // 0x1d
@@ -43551,9 +43564,9 @@
public abstract class ControlAction {
method public abstract int getActionType();
method @Nullable public String getChallengeValue();
+ method @NonNull public static android.service.controls.actions.ControlAction getErrorAction();
method @NonNull public String getTemplateId();
method public static final boolean isValidResponse(int);
- field @NonNull public static final android.service.controls.actions.ControlAction ERROR_ACTION;
field public static final int RESPONSE_CHALLENGE_ACK = 3; // 0x3
field public static final int RESPONSE_CHALLENGE_PASSPHRASE = 5; // 0x5
field public static final int RESPONSE_CHALLENGE_PIN = 4; // 0x4
@@ -43565,7 +43578,6 @@
field public static final int TYPE_ERROR = -1; // 0xffffffff
field public static final int TYPE_FLOAT = 2; // 0x2
field public static final int TYPE_MODE = 4; // 0x4
- field public static final int TYPE_MULTI_FLOAT = 3; // 0x3
}
public final class FloatAction extends android.service.controls.actions.ControlAction {
@@ -43582,13 +43594,6 @@
method public int getNewMode();
}
- public final class MultiFloatAction extends android.service.controls.actions.ControlAction {
- ctor public MultiFloatAction(@NonNull String, @NonNull float[], @Nullable String);
- ctor public MultiFloatAction(@NonNull String, @NonNull float[]);
- method public int getActionType();
- method @NonNull public float[] getNewValues();
- }
-
}
package android.service.controls.templates {
@@ -43603,16 +43608,15 @@
}
public abstract class ControlTemplate {
+ method @NonNull public static android.service.controls.templates.ControlTemplate getErrorTemplate();
+ method @NonNull public static android.service.controls.templates.ControlTemplate getNoTemplateObject();
method @NonNull public String getTemplateId();
method public abstract int getTemplateType();
- field @NonNull public static final android.service.controls.templates.ControlTemplate ERROR_TEMPLATE;
- field @NonNull public static final android.service.controls.templates.ControlTemplate NO_TEMPLATE;
field public static final int TYPE_ERROR = -1; // 0xffffffff
- field public static final int TYPE_NONE = 0; // 0x0
+ field public static final int TYPE_NO_TEMPLATE = 0; // 0x0
field public static final int TYPE_RANGE = 2; // 0x2
field public static final int TYPE_STATELESS = 8; // 0x8
field public static final int TYPE_TEMPERATURE = 7; // 0x7
- field public static final int TYPE_THUMBNAIL = 3; // 0x3
field public static final int TYPE_TOGGLE = 1; // 0x1
field public static final int TYPE_TOGGLE_RANGE = 6; // 0x6
}
@@ -43652,13 +43656,6 @@
field public static final int MODE_UNKNOWN = 0; // 0x0
}
- public final class ThumbnailTemplate extends android.service.controls.templates.ControlTemplate {
- ctor public ThumbnailTemplate(@NonNull String, @NonNull android.graphics.drawable.Icon, @NonNull CharSequence);
- method @NonNull public CharSequence getContentDescription();
- method public int getTemplateType();
- method @NonNull public android.graphics.drawable.Icon getThumbnail();
- }
-
public final class ToggleRangeTemplate extends android.service.controls.templates.ControlTemplate {
ctor public ToggleRangeTemplate(@NonNull String, @NonNull android.service.controls.templates.ControlButton, @NonNull android.service.controls.templates.RangeTemplate);
ctor public ToggleRangeTemplate(@NonNull String, boolean, @NonNull CharSequence, @NonNull android.service.controls.templates.RangeTemplate);
@@ -45982,9 +45979,6 @@
field public static final int MISSED = 5; // 0x5
field public static final int OTHER = 9; // 0x9
field public static final String REASON_EMERGENCY_CALL_PLACED = "REASON_EMERGENCY_CALL_PLACED";
- field public static final String REASON_EMULATING_SINGLE_CALL = "EMULATING_SINGLE_CALL";
- field public static final String REASON_IMS_ACCESS_BLOCKED = "REASON_IMS_ACCESS_BLOCKED";
- field public static final String REASON_WIFI_ON_BUT_WFC_OFF = "REASON_WIFI_ON_BUT_WFC_OFF";
field public static final int REJECTED = 6; // 0x6
field public static final int REMOTE = 3; // 0x3
field public static final int RESTRICTED = 8; // 0x8
@@ -46311,7 +46305,6 @@
field public static final int DURATION_SHORT = 1; // 0x1
field public static final int DURATION_VERY_SHORT = 0; // 0x0
field public static final String EXTRA_CALL_BACK_NUMBER = "android.telecom.extra.CALL_BACK_NUMBER";
- field public static final String EXTRA_CALL_CREATED_TIME_MILLIS = "android.telecom.extra.CALL_CREATED_TIME_MILLIS";
field public static final String EXTRA_CALL_DISCONNECT_CAUSE = "android.telecom.extra.CALL_DISCONNECT_CAUSE";
field public static final String EXTRA_CALL_DISCONNECT_MESSAGE = "android.telecom.extra.CALL_DISCONNECT_MESSAGE";
field public static final String EXTRA_CALL_DURATION = "android.telecom.extra.CALL_DURATION";
@@ -46605,12 +46598,9 @@
field public static final String EXTRA_SLOT_INDEX = "android.telephony.extra.SLOT_INDEX";
field public static final String EXTRA_SUBSCRIPTION_INDEX = "android.telephony.extra.SUBSCRIPTION_INDEX";
field public static final String IMSI_KEY_AVAILABILITY_INT = "imsi_key_availability_int";
- field public static final String KEY_5G_ICON_CONFIGURATION_STRING = "5g_icon_configuration_string";
- field public static final String KEY_5G_ICON_DISPLAY_GRACE_PERIOD_SEC_INT = "5g_icon_display_grace_period_sec_int";
field public static final String KEY_5G_NR_SSRSRP_THRESHOLDS_INT_ARRAY = "5g_nr_ssrsrp_thresholds_int_array";
field public static final String KEY_5G_NR_SSRSRQ_THRESHOLDS_INT_ARRAY = "5g_nr_ssrsrq_thresholds_int_array";
field public static final String KEY_5G_NR_SSSINR_THRESHOLDS_INT_ARRAY = "5g_nr_sssinr_thresholds_int_array";
- field public static final String KEY_5G_WATCHDOG_TIME_MS_LONG = "5g_watchdog_time_long";
field public static final String KEY_ADDITIONAL_CALL_SETTING_BOOL = "additional_call_setting_bool";
field public static final String KEY_ALLOW_ADDING_APNS_BOOL = "allow_adding_apns_bool";
field public static final String KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL = "allow_add_call_during_video_call";
@@ -46803,7 +46793,6 @@
field public static final String KEY_SHOW_APN_SETTING_CDMA_BOOL = "show_apn_setting_cdma_bool";
field public static final String KEY_SHOW_BLOCKING_PAY_PHONE_OPTION_BOOL = "show_blocking_pay_phone_option_bool";
field public static final String KEY_SHOW_CALL_BLOCKING_DISABLED_NOTIFICATION_ALWAYS_BOOL = "show_call_blocking_disabled_notification_always_bool";
- field public static final String KEY_SHOW_CARRIER_DATA_ICON_PATTERN_STRING = "show_carrier_data_icon_pattern_string";
field public static final String KEY_SHOW_CDMA_CHOICES_BOOL = "show_cdma_choices_bool";
field public static final String KEY_SHOW_FORWARDED_NUMBER_BOOL = "show_forwarded_number_bool";
field public static final String KEY_SHOW_ICCID_IN_SIM_STATUS_BOOL = "show_iccid_in_sim_status_bool";
@@ -47583,7 +47572,6 @@
method @NonNull public java.util.List<java.lang.Integer> getAvailableServices();
method @Nullable public android.telephony.CellIdentity getCellIdentity();
method public int getDomain();
- method public int getNrState();
method @Nullable public String getRegisteredPlmn();
method public int getTransportType();
method public boolean isRegistered();
@@ -47786,9 +47774,7 @@
method public boolean getIsManualSelection();
method @NonNull public java.util.List<android.telephony.NetworkRegistrationInfo> getNetworkRegistrationInfoList();
method public String getOperatorAlphaLong();
- method @Nullable public String getOperatorAlphaLongRaw();
method public String getOperatorAlphaShort();
- method @Nullable public String getOperatorAlphaShortRaw();
method public String getOperatorNumeric();
method public boolean getRoaming();
method public int getState();
@@ -47847,6 +47833,7 @@
method @Deprecated public void sendMultimediaMessage(android.content.Context, android.net.Uri, String, android.os.Bundle, android.app.PendingIntent);
method public void sendMultipartTextMessage(String, String, java.util.ArrayList<java.lang.String>, java.util.ArrayList<android.app.PendingIntent>, java.util.ArrayList<android.app.PendingIntent>);
method public void sendMultipartTextMessage(@NonNull String, @Nullable String, @NonNull java.util.List<java.lang.String>, @Nullable java.util.List<android.app.PendingIntent>, @Nullable java.util.List<android.app.PendingIntent>, long);
+ method public void sendMultipartTextMessage(@NonNull String, @Nullable String, @NonNull java.util.List<java.lang.String>, @Nullable java.util.List<android.app.PendingIntent>, @Nullable java.util.List<android.app.PendingIntent>, @NonNull String);
method public void sendTextMessage(String, String, String, android.app.PendingIntent, android.app.PendingIntent);
method public void sendTextMessage(@NonNull String, @Nullable String, @NonNull String, @Nullable android.app.PendingIntent, @Nullable android.app.PendingIntent, long);
method @RequiresPermission(allOf={android.Manifest.permission.MODIFY_PHONE_STATE, android.Manifest.permission.SEND_SMS}) public void sendTextMessageWithoutPersisting(String, String, String, android.app.PendingIntent, android.app.PendingIntent);
@@ -48060,13 +48047,13 @@
method @NonNull @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.os.ParcelUuid createSubscriptionGroup(@NonNull java.util.List<java.lang.Integer>);
method @Deprecated public static android.telephony.SubscriptionManager from(android.content.Context);
method public java.util.List<android.telephony.SubscriptionInfo> getAccessibleSubscriptionInfoList();
- method @Nullable public java.util.List<android.telephony.SubscriptionInfo> getActiveAndHiddenSubscriptionInfoList();
method public static int getActiveDataSubscriptionId();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public android.telephony.SubscriptionInfo getActiveSubscriptionInfo(int);
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public int getActiveSubscriptionInfoCount();
method public int getActiveSubscriptionInfoCountMax();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public android.telephony.SubscriptionInfo getActiveSubscriptionInfoForSimSlotIndex(int);
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public java.util.List<android.telephony.SubscriptionInfo> getActiveSubscriptionInfoList();
+ method @NonNull public java.util.List<android.telephony.SubscriptionInfo> getCompleteActiveSubscriptionInfoList();
method public static int getDefaultDataSubscriptionId();
method public static int getDefaultSmsSubscriptionId();
method public static int getDefaultSubscriptionId();
@@ -48229,6 +48216,7 @@
method public boolean isEmergencyNumber(@NonNull String);
method public boolean isHearingAidCompatibilitySupported();
method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRECISE_PHONE_STATE, "android.permission.READ_PRIVILEGED_PHONE_STATE"}) public boolean isManualNetworkSelectionAllowed();
+ method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean isModemEnabledForSlot(int);
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public int isMultiSimSupported();
method public boolean isNetworkRoaming();
method public boolean isRttSupported();
@@ -48342,7 +48330,6 @@
field public static final int NETWORK_TYPE_UNKNOWN = 0; // 0x0
field public static final int PHONE_TYPE_CDMA = 2; // 0x2
field public static final int PHONE_TYPE_GSM = 1; // 0x1
- field public static final int PHONE_TYPE_IMS = 5; // 0x5
field public static final int PHONE_TYPE_NONE = 0; // 0x0
field public static final int PHONE_TYPE_SIP = 3; // 0x3
field public static final int SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION = 2; // 0x2
@@ -49012,8 +48999,8 @@
ctor public RegistrationManager.RegistrationCallback();
method public void onRegistered(int);
method public void onRegistering(int);
- method public void onTechnologyChangeFailed(int, @Nullable android.telephony.ims.ImsReasonInfo);
- method public void onUnregistered(@Nullable android.telephony.ims.ImsReasonInfo);
+ method public void onTechnologyChangeFailed(int, @NonNull android.telephony.ims.ImsReasonInfo);
+ method public void onUnregistered(@NonNull android.telephony.ims.ImsReasonInfo);
}
}
@@ -53621,10 +53608,11 @@
public class SurfaceControlViewHost {
ctor public SurfaceControlViewHost(@NonNull android.content.Context, @NonNull android.view.Display, @Nullable android.os.IBinder);
- method public void addView(@NonNull android.view.View, int, int);
method @Nullable public android.view.SurfaceControlViewHost.SurfacePackage getSurfacePackage();
+ method @Nullable public android.view.View getView();
method public void relayout(int, int);
method public void release();
+ method public void setView(@NonNull android.view.View, int, int);
}
public static final class SurfaceControlViewHost.SurfacePackage implements android.os.Parcelable {
@@ -55598,10 +55586,12 @@
}
public interface WindowInsetsController {
- method @NonNull public android.os.CancellationSignal controlWindowInsetsAnimation(int, long, @Nullable android.view.animation.Interpolator, @NonNull android.view.WindowInsetsAnimationControlListener);
+ method public void addOnControllableInsetsChangedListener(@NonNull android.view.WindowInsetsController.OnControllableInsetsChangedListener);
+ method public void controlWindowInsetsAnimation(int, long, @Nullable android.view.animation.Interpolator, @Nullable android.os.CancellationSignal, @NonNull android.view.WindowInsetsAnimationControlListener);
method public int getSystemBarsAppearance();
method public int getSystemBarsBehavior();
method public void hide(int);
+ method public void removeOnControllableInsetsChangedListener(@NonNull android.view.WindowInsetsController.OnControllableInsetsChangedListener);
method public void setSystemBarsAppearance(int, int);
method public void setSystemBarsBehavior(int);
method public void show(int);
@@ -55612,6 +55602,10 @@
field public static final int BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE = 2; // 0x2
}
+ public static interface WindowInsetsController.OnControllableInsetsChangedListener {
+ method public void onControllableInsetsChanged(@NonNull android.view.WindowInsetsController, int);
+ }
+
public interface WindowManager extends android.view.ViewManager {
method @NonNull public default android.view.WindowMetrics getCurrentWindowMetrics();
method @Deprecated public android.view.Display getDefaultDisplay();
@@ -56177,7 +56171,7 @@
}
public static final class AccessibilityNodeInfo.ExtraRenderingInfo {
- method @Nullable public android.util.Size getLayoutParams();
+ method @Nullable public android.util.Size getLayoutSize();
method public float getTextSizeInPx();
method public int getTextSizeUnit();
}
@@ -56751,6 +56745,7 @@
method public final void notifySessionResumed();
method public final void notifyViewAppeared(@NonNull android.view.ViewStructure);
method public final void notifyViewDisappeared(@NonNull android.view.autofill.AutofillId);
+ method public final void notifyViewInsetsChanged(@NonNull android.graphics.Insets);
method public final void notifyViewTextChanged(@NonNull android.view.autofill.AutofillId, @Nullable CharSequence);
method public final void notifyViewsDisappeared(@NonNull android.view.autofill.AutofillId, @NonNull long[]);
method public final void setContentCaptureContext(@Nullable android.view.contentcapture.ContentCaptureContext);
@@ -56816,7 +56811,7 @@
public static final class InlinePresentationSpec.Builder {
ctor public InlinePresentationSpec.Builder(@NonNull android.util.Size, @NonNull android.util.Size);
method @NonNull public android.view.inline.InlinePresentationSpec build();
- method @NonNull public android.view.inline.InlinePresentationSpec.Builder setStyle(@Nullable android.os.Bundle);
+ method @NonNull public android.view.inline.InlinePresentationSpec.Builder setStyle(@NonNull android.os.Bundle);
}
}
@@ -57028,7 +57023,7 @@
ctor public InlineSuggestionsRequest.Builder(@NonNull java.util.List<android.view.inline.InlinePresentationSpec>);
method @NonNull public android.view.inputmethod.InlineSuggestionsRequest.Builder addPresentationSpecs(@NonNull android.view.inline.InlinePresentationSpec);
method @NonNull public android.view.inputmethod.InlineSuggestionsRequest build();
- method @NonNull public android.view.inputmethod.InlineSuggestionsRequest.Builder setExtras(@Nullable android.os.Bundle);
+ method @NonNull public android.view.inputmethod.InlineSuggestionsRequest.Builder setExtras(@NonNull android.os.Bundle);
method @NonNull public android.view.inputmethod.InlineSuggestionsRequest.Builder setMaxSuggestionCount(int);
method @NonNull public android.view.inputmethod.InlineSuggestionsRequest.Builder setSupportedLocales(@NonNull android.os.LocaleList);
}
@@ -58011,7 +58006,7 @@
method @Deprecated public abstract void removeSessionCookie();
method public abstract void removeSessionCookies(@Nullable android.webkit.ValueCallback<java.lang.Boolean>);
method public abstract void setAcceptCookie(boolean);
- method public static void setAcceptFileSchemeCookies(boolean);
+ method @Deprecated public static void setAcceptFileSchemeCookies(boolean);
method public abstract void setAcceptThirdPartyCookies(android.webkit.WebView, boolean);
method public abstract void setCookie(String, String);
method public abstract void setCookie(String, String, @Nullable android.webkit.ValueCallback<java.lang.Boolean>);
@@ -58376,8 +58371,8 @@
method public abstract String getUserAgentString();
method public abstract void setAllowContentAccess(boolean);
method public abstract void setAllowFileAccess(boolean);
- method public abstract void setAllowFileAccessFromFileURLs(boolean);
- method public abstract void setAllowUniversalAccessFromFileURLs(boolean);
+ method @Deprecated public abstract void setAllowFileAccessFromFileURLs(boolean);
+ method @Deprecated public abstract void setAllowUniversalAccessFromFileURLs(boolean);
method public abstract void setAppCacheEnabled(boolean);
method @Deprecated public abstract void setAppCacheMaxSize(long);
method public abstract void setAppCachePath(String);
diff --git a/api/lint-baseline.txt b/api/lint-baseline.txt
index 569e838..83c78fe 100644
--- a/api/lint-baseline.txt
+++ b/api/lint-baseline.txt
@@ -15,6 +15,16 @@
ArrayReturn: android.content.ContentProviderOperation#resolveExtrasBackReferences(android.content.ContentProviderResult[], int) parameter #0:
+ArrayReturn: android.location.GnssAntennaInfo.SphericalCorrections#SphericalCorrections(double[][], double[][]) parameter #0:
+ Method parameter should be Collection<> (or subclass) instead of raw array; was `double[][]`
+ArrayReturn: android.location.GnssAntennaInfo.SphericalCorrections#SphericalCorrections(double[][], double[][]) parameter #1:
+ Method parameter should be Collection<> (or subclass) instead of raw array; was `double[][]`
+ArrayReturn: android.location.GnssAntennaInfo.SphericalCorrections#getCorrectionUncertaintiesArray():
+ Method should return Collection<> (or subclass) instead of raw array; was `double[][]`
+ArrayReturn: android.location.GnssAntennaInfo.SphericalCorrections#getCorrectionsArray():
+ Method should return Collection<> (or subclass) instead of raw array; was `double[][]`
+ArrayReturn: android.service.autofill.FillResponse.Builder#setAuthentication(android.view.autofill.AutofillId[], android.content.IntentSender, android.widget.RemoteViews, android.service.autofill.InlinePresentation) parameter #0:
+ Method parameter should be Collection<AutofillId> (or subclass) instead of raw array; was `android.view.autofill.AutofillId[]`
BroadcastBehavior: android.app.AlarmManager#ACTION_NEXT_ALARM_CLOCK_CHANGED:
@@ -453,8 +463,12 @@
+ExecutorRegistration: android.media.MediaRouter2#setOnGetControllerHintsListener(android.media.MediaRouter2.OnGetControllerHintsListener):
+ Registration methods should have overload that accepts delivery Executor: `setOnGetControllerHintsListener`
+
+
GenericException: android.content.res.loader.ResourcesProvider#finalize():
- Methods must not throw generic exceptions (`java.lang.Throwable`)
+
HiddenSuperclass: android.content.res.ColorStateList:
@@ -499,6 +513,30 @@
+IntentBuilderName: android.net.VpnManager#provisionVpnProfile(android.net.PlatformVpnProfile):
+ Methods creating an Intent should be named `create<Foo>Intent()`, was `provisionVpnProfile`
+
+
+KotlinOperator: android.media.AudioMetadata.Map#set(android.media.AudioMetadata.Key<T>, T):
+ Method can be invoked with an indexing operator from Kotlin: `set` (this is usually desirable; just make sure it makes sense for this type of object)
+KotlinOperator: android.media.AudioMetadata.ReadMap#get(android.media.AudioMetadata.Key<T>):
+ Method can be invoked with an indexing operator from Kotlin: `get` (this is usually desirable; just make sure it makes sense for this type of object)
+
+
+MethodNameUnits: android.media.MediaParser.SeekMap#getDurationMicros():
+ Returned time values are strongly encouraged to be in milliseconds unless you need the extra precision, was `getDurationMicros`
+
+
+MinMaxConstant: android.telephony.DataFailCause#MAX_ACCESS_PROBE:
+ If min/max could change in future, make them dynamic methods: android.telephony.DataFailCause#MAX_ACCESS_PROBE
+MinMaxConstant: android.telephony.DataFailCause#MAX_IPV4_CONNECTIONS:
+ If min/max could change in future, make them dynamic methods: android.telephony.DataFailCause#MAX_IPV4_CONNECTIONS
+MinMaxConstant: android.telephony.DataFailCause#MAX_IPV6_CONNECTIONS:
+ If min/max could change in future, make them dynamic methods: android.telephony.DataFailCause#MAX_IPV6_CONNECTIONS
+MinMaxConstant: android.telephony.DataFailCause#MAX_PPP_INACTIVITY_TIMER_EXPIRED:
+ If min/max could change in future, make them dynamic methods: android.telephony.DataFailCause#MAX_PPP_INACTIVITY_TIMER_EXPIRED
+
+
MissingNullability: android.app.AsyncNotedAppOp#equals(Object) parameter #0:
MissingNullability: android.app.AsyncNotedAppOp#writeToParcel(android.os.Parcel, int) parameter #0:
@@ -506,11 +544,11 @@
MissingNullability: android.app.SyncNotedAppOp#equals(Object) parameter #0:
MissingNullability: android.icu.lang.UCharacter.UnicodeBlock#CHORASMIAN:
- Missing nullability on field `CHORASMIAN` in class `class android.icu.lang.UCharacter.UnicodeBlock`
+
MissingNullability: android.icu.lang.UCharacter.UnicodeBlock#CJK_UNIFIED_IDEOGRAPHS_EXTENSION_G:
- Missing nullability on field `CJK_UNIFIED_IDEOGRAPHS_EXTENSION_G` in class `class android.icu.lang.UCharacter.UnicodeBlock`
+
MissingNullability: android.icu.lang.UCharacter.UnicodeBlock#DIVES_AKURU:
- Missing nullability on field `DIVES_AKURU` in class `class android.icu.lang.UCharacter.UnicodeBlock`
+
MissingNullability: android.icu.lang.UCharacter.UnicodeBlock#EGYPTIAN_HIEROGLYPH_FORMAT_CONTROLS:
MissingNullability: android.icu.lang.UCharacter.UnicodeBlock#ELYMAIC:
@@ -556,14 +594,39 @@
MissingNullability: android.icu.util.VersionInfo#UNICODE_12_1:
MissingNullability: android.icu.util.VersionInfo#UNICODE_13_0:
- Missing nullability on field `UNICODE_13_0` in class `class android.icu.util.VersionInfo`
+
MissingNullability: android.media.MediaMetadataRetriever#getFrameAtTime(long, int, android.media.MediaMetadataRetriever.BitmapParams):
MissingNullability: android.media.MediaMetadataRetriever#getScaledFrameAtTime(long, int, int, int, android.media.MediaMetadataRetriever.BitmapParams):
-
MissingNullability: java.time.chrono.JapaneseEra#REIWA:
- Missing nullability on field `REIWA` in class `class java.time.chrono.JapaneseEra`
+
+
+
+NotCloseable: android.media.MediaCodec.GraphicBlock:
+ Classes that release resources (finalize()) should implement AutoClosable and CloseGuard: class android.media.MediaCodec.GraphicBlock
+NotCloseable: android.media.MediaCodec.LinearBlock:
+ Classes that release resources (finalize()) should implement AutoClosable and CloseGuard: class android.media.MediaCodec.LinearBlock
+NotCloseable: android.media.MediaParser:
+ Classes that release resources (release()) should implement AutoClosable and CloseGuard: class android.media.MediaParser
+NotCloseable: android.media.MediaRouter2.RoutingController:
+ Classes that release resources (release()) should implement AutoClosable and CloseGuard: class android.media.MediaRouter2.RoutingController
+NotCloseable: android.util.CloseGuard:
+ Classes that release resources (close()) should implement AutoClosable and CloseGuard: class android.util.CloseGuard
+NotCloseable: android.view.SurfaceControlViewHost:
+ Classes that release resources (release()) should implement AutoClosable and CloseGuard: class android.view.SurfaceControlViewHost
+
+
+OnNameExpected: android.app.admin.DevicePolicyKeyguardService#dismiss():
+ If implemented by developer, should follow the on<Something> style; otherwise consider marking final
+OnNameExpected: android.service.controls.ControlsProviderService#createPublisherFor(java.util.List<java.lang.String>):
+ Methods implemented by developers should follow the on<Something> style, was `createPublisherFor`
+OnNameExpected: android.service.controls.ControlsProviderService#createPublisherForAllAvailable():
+ Methods implemented by developers should follow the on<Something> style, was `createPublisherForAllAvailable`
+OnNameExpected: android.service.controls.ControlsProviderService#createPublisherForSuggested():
+ If implemented by developer, should follow the on<Something> style; otherwise consider marking final
+OnNameExpected: android.service.controls.ControlsProviderService#performControlAction(String, android.service.controls.actions.ControlAction, java.util.function.Consumer<java.lang.Integer>):
+ Methods implemented by developers should follow the on<Something> style, was `performControlAction`
RequiresPermission: android.accounts.AccountManager#getAccountsByTypeAndFeatures(String, String[], android.accounts.AccountManagerCallback<android.accounts.Account[]>, android.os.Handler):
@@ -1189,11 +1252,13 @@
SamShouldBeLast: android.location.LocationManager#requestLocationUpdates(String, long, float, java.util.concurrent.Executor, android.location.LocationListener):
SamShouldBeLast: android.location.LocationManager#requestLocationUpdates(long, float, android.location.Criteria, java.util.concurrent.Executor, android.location.LocationListener):
+
-
+StreamFiles: android.content.res.loader.DirectoryAssetsProvider#DirectoryAssetsProvider(java.io.File):
+ Methods accepting `File` should also accept `FileDescriptor` or streams: constructor android.content.res.loader.DirectoryAssetsProvider(java.io.File)
StreamFiles: android.content.res.loader.DirectoryResourceLoader#DirectoryResourceLoader(java.io.File):
- Methods accepting `File` should also accept `FileDescriptor` or streams: constructor android.content.res.loader.DirectoryResourceLoader(java.io.File)
+
Todo: android.hardware.camera2.params.StreamConfigurationMap:
diff --git a/api/module-lib-current.txt b/api/module-lib-current.txt
index 6863221..ee997f1 100644
--- a/api/module-lib-current.txt
+++ b/api/module-lib-current.txt
@@ -29,7 +29,7 @@
field @NonNull public static final android.os.Parcelable.Creator<android.net.TetheredClient.AddressInfo> CREATOR;
}
- public class TetheringConstants {
+ public final class TetheringConstants {
field public static final String EXTRA_ADD_TETHER_TYPE = "extraAddTetherType";
field public static final String EXTRA_PROVISION_CALLBACK = "extraProvisionCallback";
field public static final String EXTRA_REM_TETHER_TYPE = "extraRemTetherType";
@@ -47,6 +47,7 @@
method @NonNull public String[] getTetheredIfaces();
method @NonNull public String[] getTetheringErroredIfaces();
method public boolean isTetheringSupported();
+ method public boolean isTetheringSupported(@NonNull String);
method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void registerTetheringEventCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.TetheringManager.TetheringEventCallback);
method @RequiresPermission(anyOf={"android.permission.TETHER_PRIVILEGED", android.Manifest.permission.WRITE_SETTINGS}) public void requestLatestTetheringEntitlementResult(int, boolean, @NonNull java.util.concurrent.Executor, @NonNull android.net.TetheringManager.OnTetheringEntitlementResultListener);
method public void requestLatestTetheringEntitlementResult(int, @NonNull android.os.ResultReceiver, boolean);
@@ -86,6 +87,9 @@
field public static final int TETHER_ERROR_UNKNOWN_IFACE = 1; // 0x1
field public static final int TETHER_ERROR_UNSUPPORTED = 3; // 0x3
field public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7; // 0x7
+ field public static final int TETHER_HARDWARE_OFFLOAD_FAILED = 2; // 0x2
+ field public static final int TETHER_HARDWARE_OFFLOAD_STARTED = 1; // 0x1
+ field public static final int TETHER_HARDWARE_OFFLOAD_STOPPED = 0; // 0x0
}
public static interface TetheringManager.OnTetheringEntitlementResultListener {
@@ -102,6 +106,7 @@
ctor public TetheringManager.TetheringEventCallback();
method public void onClientsChanged(@NonNull java.util.Collection<android.net.TetheredClient>);
method public void onError(@NonNull String, int);
+ method public void onOffloadStatusChanged(int);
method @Deprecated public void onTetherableInterfaceRegexpsChanged(@NonNull android.net.TetheringManager.TetheringInterfaceRegexps);
method public void onTetherableInterfacesChanged(@NonNull java.util.List<java.lang.String>);
method public void onTetheredInterfacesChanged(@NonNull java.util.List<java.lang.String>);
diff --git a/api/removed.txt b/api/removed.txt
index fb6d576..077c915 100644
--- a/api/removed.txt
+++ b/api/removed.txt
@@ -1,4 +1,12 @@
// Signature format: 2.0
+package android {
+
+ public static final class R.attr {
+ field public static final int featureId = 16844301; // 0x101060d
+ }
+
+}
+
package android.app {
public class ActivityManager {
@@ -69,7 +77,17 @@
package android.content {
+ public abstract class ContentProvider implements android.content.ComponentCallbacks2 {
+ method @Deprecated @Nullable public final String getCallingFeatureId();
+ }
+
+ public abstract class ContentResolver {
+ method @Deprecated public void notifyChange(@NonNull Iterable<android.net.Uri>, @Nullable android.database.ContentObserver, int);
+ }
+
public abstract class Context {
+ method @Deprecated @NonNull public android.content.Context createFeatureContext(@Nullable String);
+ method @Deprecated @Nullable public String getFeatureId();
method public abstract android.content.SharedPreferences getSharedPreferences(java.io.File, int);
method public abstract java.io.File getSharedPreferencesPath(String);
}
diff --git a/api/system-current.txt b/api/system-current.txt
index e81af5a..ab3bcc1 100755
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -79,6 +79,7 @@
field public static final String DEVICE_POWER = "android.permission.DEVICE_POWER";
field public static final String DISPATCH_PROVISIONING_MESSAGE = "android.permission.DISPATCH_PROVISIONING_MESSAGE";
field public static final String ENTER_CAR_MODE_PRIORITIZED = "android.permission.ENTER_CAR_MODE_PRIORITIZED";
+ field public static final String EXEMPT_FROM_AUDIO_RECORD_RESTRICTIONS = "android.permission.EXEMPT_FROM_AUDIO_RECORD_RESTRICTIONS";
field public static final String FORCE_BACK = "android.permission.FORCE_BACK";
field public static final String FORCE_STOP_PACKAGES = "android.permission.FORCE_STOP_PACKAGES";
field public static final String GET_APP_OPS_STATS = "android.permission.GET_APP_OPS_STATS";
@@ -231,8 +232,10 @@
field public static final String UPDATE_APP_OPS_STATS = "android.permission.UPDATE_APP_OPS_STATS";
field public static final String UPDATE_LOCK = "android.permission.UPDATE_LOCK";
field public static final String UPDATE_TIME_ZONE_RULES = "android.permission.UPDATE_TIME_ZONE_RULES";
+ field public static final String UPGRADE_RUNTIME_PERMISSIONS = "android.permission.UPGRADE_RUNTIME_PERMISSIONS";
field public static final String USER_ACTIVITY = "android.permission.USER_ACTIVITY";
field public static final String USE_RESERVED_DISK = "android.permission.USE_RESERVED_DISK";
+ field public static final String WHITELIST_AUTO_REVOKE_PERMISSIONS = "android.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS";
field public static final String WHITELIST_RESTRICTED_PERMISSIONS = "android.permission.WHITELIST_RESTRICTED_PERMISSIONS";
field public static final String WIFI_SET_DEVICE_MOBILITY_STATE = "android.permission.WIFI_SET_DEVICE_MOBILITY_STATE";
field public static final String WIFI_UPDATE_USABILITY_STATS_SCORE = "android.permission.WIFI_UPDATE_USABILITY_STATS_SCORE";
@@ -249,9 +252,6 @@
public static final class R.array {
field public static final int config_keySystemUuidMapping = 17235973; // 0x1070005
- field public static final int config_restrictedPreinstalledCarrierApps = 17235975; // 0x1070007
- field public static final int config_sms_enabled_locking_shift_tables = 17235977; // 0x1070009
- field public static final int config_sms_enabled_single_shift_tables = 17235976; // 0x1070008
field public static final int simColors = 17235974; // 0x1070006
}
@@ -304,7 +304,6 @@
field public static final int config_helpPackageNameKey = 17039387; // 0x104001b
field public static final int config_helpPackageNameValue = 17039388; // 0x104001c
field public static final int config_systemGallery = 17039402; // 0x104002a
- field public static final int low_memory = 17039403; // 0x104002b
}
public static final class R.style {
@@ -388,6 +387,7 @@
field public static final String OPSTR_AUDIO_NOTIFICATION_VOLUME = "android:audio_notification_volume";
field public static final String OPSTR_AUDIO_RING_VOLUME = "android:audio_ring_volume";
field public static final String OPSTR_AUDIO_VOICE_VOLUME = "android:audio_voice_volume";
+ field public static final String OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED = "android:auto_revoke_permissions_if_unused";
field public static final String OPSTR_BIND_ACCESSIBILITY_SERVICE = "android:bind_accessibility_service";
field public static final String OPSTR_CHANGE_WIFI_STATE = "android:change_wifi_state";
field public static final String OPSTR_GET_ACCOUNTS = "android:get_accounts";
@@ -404,7 +404,6 @@
field public static final String OPSTR_POST_NOTIFICATION = "android:post_notification";
field public static final String OPSTR_PROJECT_MEDIA = "android:project_media";
field public static final String OPSTR_READ_CLIPBOARD = "android:read_clipboard";
- field public static final String OPSTR_READ_DEVICE_IDENTIFIERS = "android:read_device_identifiers";
field public static final String OPSTR_READ_ICC_SMS = "android:read_icc_sms";
field public static final String OPSTR_READ_MEDIA_AUDIO = "android:read_media_audio";
field public static final String OPSTR_READ_MEDIA_IMAGES = "android:read_media_images";
@@ -445,14 +444,37 @@
field public static final int UID_STATE_TOP = 200; // 0xc8
}
- public static final class AppOpsManager.HistoricalFeatureOps implements android.os.Parcelable {
+ public static final class AppOpsManager.AttributedHistoricalOps implements android.os.Parcelable {
method public int describeContents();
- method @Nullable public String getFeatureId();
method @Nullable public android.app.AppOpsManager.HistoricalOp getOp(@NonNull String);
method @NonNull public android.app.AppOpsManager.HistoricalOp getOpAt(@IntRange(from=0) int);
method @IntRange(from=0) public int getOpCount();
+ method @Nullable public String getTag();
method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalFeatureOps> CREATOR;
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.AttributedHistoricalOps> CREATOR;
+ }
+
+ public static final class AppOpsManager.AttributedOpEntry implements android.os.Parcelable {
+ method public int describeContents();
+ method public long getLastAccessBackgroundTime(int);
+ method public long getLastAccessForegroundTime(int);
+ method public long getLastAccessTime(int);
+ method public long getLastAccessTime(int, int, int);
+ method public long getLastBackgroundDuration(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastBackgroundProxyInfo(int);
+ method public long getLastDuration(int);
+ method public long getLastDuration(int, int, int);
+ method public long getLastForegroundDuration(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastForegroundProxyInfo(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int, int, int);
+ method public long getLastRejectBackgroundTime(int);
+ method public long getLastRejectForegroundTime(int);
+ method public long getLastRejectTime(int);
+ method public long getLastRejectTime(int, int, int);
+ method public boolean isRunning();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.AttributedOpEntry> CREATOR;
}
public static final class AppOpsManager.HistoricalOp implements android.os.Parcelable {
@@ -488,7 +510,7 @@
public static final class AppOpsManager.HistoricalOpsRequest.Builder {
ctor public AppOpsManager.HistoricalOpsRequest.Builder(long, long);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest build();
- method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setFeatureId(@Nullable String);
+ method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setAttributionTag(@Nullable String);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setFlags(int);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setOpNames(@Nullable java.util.List<java.lang.String>);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setPackageName(@Nullable String);
@@ -497,9 +519,9 @@
public static final class AppOpsManager.HistoricalPackageOps implements android.os.Parcelable {
method public int describeContents();
- method @IntRange(from=0) public int getFeatureCount();
- method @Nullable public android.app.AppOpsManager.HistoricalFeatureOps getFeatureOps(@NonNull String);
- method @NonNull public android.app.AppOpsManager.HistoricalFeatureOps getFeatureOpsAt(@IntRange(from=0) int);
+ method @Nullable public android.app.AppOpsManager.AttributedHistoricalOps getAttributedOps(@NonNull String);
+ method @NonNull public android.app.AppOpsManager.AttributedHistoricalOps getAttributedOpsAt(@IntRange(from=0) int);
+ method @IntRange(from=0) public int getAttributedOpsCount();
method @Nullable public android.app.AppOpsManager.HistoricalOp getOp(@NonNull String);
method @NonNull public android.app.AppOpsManager.HistoricalOp getOpAt(@IntRange(from=0) int);
method @IntRange(from=0) public int getOpCount();
@@ -520,8 +542,8 @@
public static final class AppOpsManager.OpEntry implements android.os.Parcelable {
method public int describeContents();
+ method @NonNull public java.util.Map<java.lang.String,android.app.AppOpsManager.AttributedOpEntry> getAttributedOpEntries();
method @Deprecated public long getDuration();
- method @NonNull public java.util.Map<java.lang.String,android.app.AppOpsManager.OpFeatureEntry> getFeatures();
method public long getLastAccessBackgroundTime(int);
method public long getLastAccessForegroundTime(int);
method public long getLastAccessTime(int);
@@ -551,36 +573,13 @@
public static final class AppOpsManager.OpEventProxyInfo implements android.os.Parcelable {
method public int describeContents();
- method @Nullable public String getFeatureId();
+ method @Nullable public String getAttributionTag();
method @Nullable public String getPackageName();
method @IntRange(from=0) public int getUid();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.OpEventProxyInfo> CREATOR;
}
- public static final class AppOpsManager.OpFeatureEntry implements android.os.Parcelable {
- method public int describeContents();
- method public long getLastAccessBackgroundTime(int);
- method public long getLastAccessForegroundTime(int);
- method public long getLastAccessTime(int);
- method public long getLastAccessTime(int, int, int);
- method public long getLastBackgroundDuration(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastBackgroundProxyInfo(int);
- method public long getLastDuration(int);
- method public long getLastDuration(int, int, int);
- method public long getLastForegroundDuration(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastForegroundProxyInfo(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int, int, int);
- method public long getLastRejectBackgroundTime(int);
- method public long getLastRejectForegroundTime(int);
- method public long getLastRejectTime(int);
- method public long getLastRejectTime(int, int, int);
- method public boolean isRunning();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.OpFeatureEntry> CREATOR;
- }
-
public static final class AppOpsManager.PackageOps implements android.os.Parcelable {
method public int describeContents();
method @NonNull public java.util.List<android.app.AppOpsManager.OpEntry> getOps();
@@ -685,7 +684,7 @@
public final class RuntimeAppOpAccessMessage implements android.os.Parcelable {
ctor public RuntimeAppOpAccessMessage(@IntRange(from=0L) int, @IntRange(from=0L) int, @NonNull String, @Nullable String, @NonNull String, int);
method public int describeContents();
- method @Nullable public String getFeatureId();
+ method @Nullable public String getAttributionTag();
method @NonNull public String getMessage();
method @NonNull public String getOp();
method @NonNull public String getPackageName();
@@ -702,12 +701,12 @@
public final class StatsManager {
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void addConfig(long, byte[]) throws android.app.StatsManager.StatsUnavailableException;
method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean addConfiguration(long, byte[]);
+ method @RequiresPermission(android.Manifest.permission.REGISTER_STATS_PULL_ATOM) public void clearPullAtomCallback(int);
method @Deprecated @Nullable @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public byte[] getData(long);
method @Deprecated @Nullable @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public byte[] getMetadata();
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public long[] getRegisteredExperimentIds() throws android.app.StatsManager.StatsUnavailableException;
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public byte[] getReports(long) throws android.app.StatsManager.StatsUnavailableException;
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public byte[] getStatsMetadata() throws android.app.StatsManager.StatsUnavailableException;
- method @RequiresPermission(android.Manifest.permission.REGISTER_STATS_PULL_ATOM) public void registerPullAtomCallback(int, @Nullable android.app.StatsManager.PullAtomMetadata, @NonNull java.util.concurrent.Executor, @NonNull android.app.StatsManager.StatsPullAtomCallback);
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void removeConfig(long) throws android.app.StatsManager.StatsUnavailableException;
method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean removeConfiguration(long);
method @NonNull @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public long[] setActiveConfigsChangedOperation(@Nullable android.app.PendingIntent) throws android.app.StatsManager.StatsUnavailableException;
@@ -715,7 +714,7 @@
method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean setBroadcastSubscriber(long, long, android.app.PendingIntent);
method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public boolean setDataFetchOperation(long, android.app.PendingIntent);
method @RequiresPermission(allOf={android.Manifest.permission.DUMP, android.Manifest.permission.PACKAGE_USAGE_STATS}) public void setFetchReportsOperation(android.app.PendingIntent, long) throws android.app.StatsManager.StatsUnavailableException;
- method @RequiresPermission(android.Manifest.permission.REGISTER_STATS_PULL_ATOM) public void unregisterPullAtomCallback(int);
+ method @RequiresPermission(android.Manifest.permission.REGISTER_STATS_PULL_ATOM) public void setPullAtomCallback(int, @Nullable android.app.StatsManager.PullAtomMetadata, @NonNull java.util.concurrent.Executor, @NonNull android.app.StatsManager.StatsPullAtomCallback);
field public static final String ACTION_STATSD_STARTED = "android.app.action.STATSD_STARTED";
field public static final String EXTRA_STATS_ACTIVE_CONFIG_KEYS = "android.app.extra.STATS_ACTIVE_CONFIG_KEYS";
field public static final String EXTRA_STATS_BROADCAST_SUBSCRIBER_COOKIES = "android.app.extra.STATS_BROADCAST_SUBSCRIBER_COOKIES";
@@ -729,14 +728,17 @@
}
public static class StatsManager.PullAtomMetadata {
+ method @Nullable public int[] getAdditiveFields();
+ method public long getCoolDownMillis();
+ method public long getTimeoutMillis();
}
public static class StatsManager.PullAtomMetadata.Builder {
ctor public StatsManager.PullAtomMetadata.Builder();
method @NonNull public android.app.StatsManager.PullAtomMetadata build();
method @NonNull public android.app.StatsManager.PullAtomMetadata.Builder setAdditiveFields(@NonNull int[]);
- method @NonNull public android.app.StatsManager.PullAtomMetadata.Builder setCoolDownNs(long);
- method @NonNull public android.app.StatsManager.PullAtomMetadata.Builder setTimeoutNs(long);
+ method @NonNull public android.app.StatsManager.PullAtomMetadata.Builder setCoolDownMillis(long);
+ method @NonNull public android.app.StatsManager.PullAtomMetadata.Builder setTimeoutMillis(long);
}
public static interface StatsManager.StatsPullAtomCallback {
@@ -751,7 +753,6 @@
public class StatusBarManager {
method @NonNull @RequiresPermission(android.Manifest.permission.STATUS_BAR) public android.app.StatusBarManager.DisableInfo getDisableInfo();
method @RequiresPermission(android.Manifest.permission.STATUS_BAR) public void setDisabledForSetup(boolean);
- method @RequiresPermission(android.Manifest.permission.STATUS_BAR) public void setDisabledForSimNetworkLock(boolean);
}
public static final class StatusBarManager.DisableInfo {
@@ -1365,7 +1366,6 @@
method @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) public void addRoleHolderAsUser(@NonNull String, @NonNull String, int, @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public boolean addRoleHolderFromController(@NonNull String, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) public void clearRoleHoldersAsUser(@NonNull String, int, @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
- method @Nullable public String getDefaultSmsPackage(int);
method @NonNull @RequiresPermission("com.android.permissioncontroller.permission.MANAGE_ROLES_FROM_CONTROLLER") public java.util.List<java.lang.String> getHeldRolesFromController(@NonNull String);
method @NonNull @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) public java.util.List<java.lang.String> getRoleHolders(@NonNull String);
method @NonNull @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) public java.util.List<java.lang.String> getRoleHoldersAsUser(@NonNull String, @NonNull android.os.UserHandle);
@@ -1755,8 +1755,8 @@
package android.content {
- public class ApexContext {
- method @NonNull public static android.content.ApexContext getApexContext(@NonNull String);
+ public class ApexEnvironment {
+ method @NonNull public static android.content.ApexEnvironment getApexEnvironment(@NonNull String);
method @NonNull public java.io.File getCredentialProtectedDataDirForUser(@NonNull android.os.UserHandle);
method @NonNull public java.io.File getDeviceProtectedDataDir();
method @NonNull public java.io.File getDeviceProtectedDataDirForUser(@NonNull android.os.UserHandle);
@@ -2011,7 +2011,6 @@
}
public final class InstallationFile {
- ctor public InstallationFile(int, @NonNull String, long, @Nullable byte[], @Nullable byte[]);
method public long getLengthBytes();
method public int getLocation();
method @Nullable public byte[] getMetadata();
@@ -2128,6 +2127,7 @@
public static class PackageInstaller.SessionInfo implements android.os.Parcelable {
method public boolean getAllocateAggressive();
method @Deprecated public boolean getAllowDowngrade();
+ method public int getAutoRevokePermissionsMode();
method public boolean getDontKillApp();
method public boolean getEnableRollback();
method @Nullable public String[] getGrantedRuntimePermissions();
@@ -2211,11 +2211,9 @@
field public static final String FEATURE_INCREMENTAL_DELIVERY = "android.software.incremental_delivery";
field public static final String FEATURE_REBOOT_ESCROW = "android.hardware.reboot_escrow";
field public static final String FEATURE_TELEPHONY_CARRIERLOCK = "android.hardware.telephony.carrierlock";
- field public static final int FLAGS_PERMISSION_RESERVED_PERMISSIONCONTROLLER = -268435456; // 0xf0000000
+ field public static final int FLAGS_PERMISSION_RESERVED_PERMISSION_CONTROLLER = -268435456; // 0xf0000000
field public static final int FLAG_PERMISSION_APPLY_RESTRICTION = 16384; // 0x4000
- field public static final int FLAG_PERMISSION_AUTO_REVOKED = 1048576; // 0x100000
- field public static final int FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED = 131072; // 0x20000
- field public static final int FLAG_PERMISSION_AUTO_REVOKE_USER_SET = 262144; // 0x40000
+ field public static final int FLAG_PERMISSION_AUTO_REVOKED = 131072; // 0x20000
field public static final int FLAG_PERMISSION_GRANTED_BY_DEFAULT = 32; // 0x20
field public static final int FLAG_PERMISSION_GRANTED_BY_ROLE = 32768; // 0x8000
field public static final int FLAG_PERMISSION_ONE_TIME = 65536; // 0x10000
@@ -2278,7 +2276,6 @@
field @Deprecated public static final int MASK_PERMISSION_FLAGS = 255; // 0xff
field public static final int MATCH_ANY_USER = 4194304; // 0x400000
field public static final int MATCH_FACTORY_ONLY = 2097152; // 0x200000
- field public static final int MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS = 536870912; // 0x20000000
field public static final int MATCH_INSTANT = 8388608; // 0x800000
field public static final int MODULE_APEX_NAME = 1; // 0x1
field public static final int RESTRICTION_HIDE_FROM_SUGGESTIONS = 1; // 0x1
@@ -2299,7 +2296,7 @@
method public void onPermissionsChanged(int);
}
- @IntDef(prefix={"FLAG_PERMISSION_"}, value={android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET, android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE, android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_INSTALLER_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_ROLE, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, android.content.pm.PackageManager.FLAG_PERMISSION_ONE_TIME, android.content.pm.PackageManager.FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED, android.content.pm.PackageManager.FLAG_PERMISSION_AUTO_REVOKE_USER_SET, android.content.pm.PackageManager.FLAG_PERMISSION_AUTO_REVOKED}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface PackageManager.PermissionFlags {
+ @IntDef(prefix={"FLAG_PERMISSION_"}, value={android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET, android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE, android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED, android.content.pm.PackageManager.FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_UPGRADE_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_RESTRICTION_INSTALLER_EXEMPT, android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION, android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_ROLE, android.content.pm.PackageManager.FLAG_PERMISSION_REVOKED_COMPAT, android.content.pm.PackageManager.FLAG_PERMISSION_ONE_TIME, android.content.pm.PackageManager.FLAG_PERMISSION_AUTO_REVOKED}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) public static @interface PackageManager.PermissionFlags {
}
public class PermissionGroupInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
@@ -2937,7 +2934,7 @@
public final class LightsManager.LightsSession implements java.lang.AutoCloseable {
method @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_LIGHTS) public void close();
- method @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_LIGHTS) public void setLights(@NonNull android.hardware.lights.LightsRequest);
+ method @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_LIGHTS) public void requestLights(@NonNull android.hardware.lights.LightsRequest);
}
public final class LightsRequest {
@@ -4984,7 +4981,7 @@
package android.media.tv.tuner.filter {
- public class AlpFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
+ public final class AlpFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_TV_TUNER) public static android.media.tv.tuner.filter.AlpFilterConfiguration.Builder builder(@NonNull android.content.Context);
method public int getLengthType();
method public int getPacketType();
@@ -4999,10 +4996,11 @@
field public static final int PACKET_TYPE_SIGNALING = 4; // 0x4
}
- public static class AlpFilterConfiguration.Builder extends android.media.tv.tuner.filter.FilterConfiguration.Builder<android.media.tv.tuner.filter.AlpFilterConfiguration.Builder> {
+ public static final class AlpFilterConfiguration.Builder {
method @NonNull public android.media.tv.tuner.filter.AlpFilterConfiguration build();
method @NonNull public android.media.tv.tuner.filter.AlpFilterConfiguration.Builder setLengthType(int);
method @NonNull public android.media.tv.tuner.filter.AlpFilterConfiguration.Builder setPacketType(int);
+ method @NonNull public android.media.tv.tuner.filter.AlpFilterConfiguration.Builder setSettings(@Nullable android.media.tv.tuner.filter.Settings);
}
public class AudioDescriptor {
@@ -5090,15 +5088,11 @@
method public abstract int getType();
}
- public abstract static class FilterConfiguration.Builder<T extends android.media.tv.tuner.filter.FilterConfiguration.Builder<T>> {
- method @NonNull public T setSettings(@Nullable android.media.tv.tuner.filter.Settings);
- }
-
public abstract class FilterEvent {
ctor public FilterEvent();
}
- public class IpFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
+ public final class IpFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_TV_TUNER) public static android.media.tv.tuner.filter.IpFilterConfiguration.Builder builder(@NonNull android.content.Context);
method @NonNull @Size(min=4, max=16) public byte[] getDstIpAddress();
method public int getDstPort();
@@ -5108,11 +5102,12 @@
method public boolean isPassthrough();
}
- public static class IpFilterConfiguration.Builder extends android.media.tv.tuner.filter.FilterConfiguration.Builder<android.media.tv.tuner.filter.IpFilterConfiguration.Builder> {
+ public static final class IpFilterConfiguration.Builder {
method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration build();
method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration.Builder setDstIpAddress(@NonNull byte[]);
method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration.Builder setDstPort(int);
method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration.Builder setPassthrough(boolean);
+ method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration.Builder setSettings(@Nullable android.media.tv.tuner.filter.Settings);
method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration.Builder setSrcIpAddress(@NonNull byte[]);
method @NonNull public android.media.tv.tuner.filter.IpFilterConfiguration.Builder setSrcPort(int);
}
@@ -5136,15 +5131,16 @@
method public boolean isSecureMemory();
}
- public class MmtpFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
+ public final class MmtpFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_TV_TUNER) public static android.media.tv.tuner.filter.MmtpFilterConfiguration.Builder builder(@NonNull android.content.Context);
method public int getMmtpPacketId();
method public int getType();
}
- public static class MmtpFilterConfiguration.Builder extends android.media.tv.tuner.filter.FilterConfiguration.Builder<android.media.tv.tuner.filter.MmtpFilterConfiguration.Builder> {
+ public static final class MmtpFilterConfiguration.Builder {
method @NonNull public android.media.tv.tuner.filter.MmtpFilterConfiguration build();
method @NonNull public android.media.tv.tuner.filter.MmtpFilterConfiguration.Builder setMmtpPacketId(int);
+ method @NonNull public android.media.tv.tuner.filter.MmtpFilterConfiguration.Builder setSettings(@Nullable android.media.tv.tuner.filter.Settings);
}
public class MmtpRecordEvent extends android.media.tv.tuner.filter.FilterEvent {
@@ -5279,7 +5275,7 @@
field public static final long TIMESTAMP_UNAVAILABLE = -1L; // 0xffffffffffffffffL
}
- public class TlvFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
+ public final class TlvFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_TV_TUNER) public static android.media.tv.tuner.filter.TlvFilterConfiguration.Builder builder(@NonNull android.content.Context);
method public int getPacketType();
method public int getType();
@@ -5292,21 +5288,23 @@
field public static final int PACKET_TYPE_SIGNALING = 254; // 0xfe
}
- public static class TlvFilterConfiguration.Builder extends android.media.tv.tuner.filter.FilterConfiguration.Builder<android.media.tv.tuner.filter.TlvFilterConfiguration.Builder> {
+ public static final class TlvFilterConfiguration.Builder {
method @NonNull public android.media.tv.tuner.filter.TlvFilterConfiguration build();
method @NonNull public android.media.tv.tuner.filter.TlvFilterConfiguration.Builder setCompressedIpPacket(boolean);
method @NonNull public android.media.tv.tuner.filter.TlvFilterConfiguration.Builder setPacketType(int);
method @NonNull public android.media.tv.tuner.filter.TlvFilterConfiguration.Builder setPassthrough(boolean);
+ method @NonNull public android.media.tv.tuner.filter.TlvFilterConfiguration.Builder setSettings(@Nullable android.media.tv.tuner.filter.Settings);
}
- public class TsFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
+ public final class TsFilterConfiguration extends android.media.tv.tuner.filter.FilterConfiguration {
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_TV_TUNER) public static android.media.tv.tuner.filter.TsFilterConfiguration.Builder builder(@NonNull android.content.Context);
method public int getTpid();
method public int getType();
}
- public static class TsFilterConfiguration.Builder extends android.media.tv.tuner.filter.FilterConfiguration.Builder<android.media.tv.tuner.filter.TsFilterConfiguration.Builder> {
+ public static final class TsFilterConfiguration.Builder {
method @NonNull public android.media.tv.tuner.filter.TsFilterConfiguration build();
+ method @NonNull public android.media.tv.tuner.filter.TsFilterConfiguration.Builder setSettings(@Nullable android.media.tv.tuner.filter.Settings);
method @NonNull public android.media.tv.tuner.filter.TsFilterConfiguration.Builder setTpid(int);
}
@@ -5361,8 +5359,9 @@
field public static final int SIGNAL_TYPE_UNDEFINED = 0; // 0x0
}
- public static class AnalogFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.AnalogFrontendSettings.Builder> {
+ public static class AnalogFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.AnalogFrontendSettings build();
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.AnalogFrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.AnalogFrontendSettings.Builder setSifStandard(int);
method @NonNull public android.media.tv.tuner.frontend.AnalogFrontendSettings.Builder setSignalType(int);
}
@@ -5426,10 +5425,11 @@
field public static final int TIME_INTERLEAVE_MODE_UNDEFINED = 0; // 0x0
}
- public static class Atsc3FrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.Atsc3FrontendSettings.Builder> {
+ public static class Atsc3FrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.Atsc3FrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.Atsc3FrontendSettings.Builder setBandwidth(int);
method @NonNull public android.media.tv.tuner.frontend.Atsc3FrontendSettings.Builder setDemodOutputFormat(int);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.Atsc3FrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.Atsc3FrontendSettings.Builder setPlpSettings(@NonNull android.media.tv.tuner.frontend.Atsc3PlpSettings[]);
}
@@ -5470,8 +5470,9 @@
field public static final int MODULATION_UNDEFINED = 0; // 0x0
}
- public static class AtscFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.AtscFrontendSettings.Builder> {
+ public static class AtscFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.AtscFrontendSettings build();
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.AtscFrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.AtscFrontendSettings.Builder setModulation(int);
}
@@ -5484,7 +5485,7 @@
public class DvbcFrontendSettings extends android.media.tv.tuner.frontend.FrontendSettings {
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_TV_TUNER) public static android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder builder(@NonNull android.content.Context);
method public int getAnnex();
- method public long getFec();
+ method public long getInnerFec();
method public int getModulation();
method public int getOuterFec();
method public int getSpectralInversion();
@@ -5509,10 +5510,11 @@
field public static final int SPECTRAL_INVERSION_UNDEFINED = 0; // 0x0
}
- public static class DvbcFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder> {
+ public static class DvbcFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setAnnex(int);
- method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setFec(long);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setFrequency(int);
+ method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setInnerFec(long);
method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setModulation(int);
method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setOuterFec(int);
method @NonNull public android.media.tv.tuner.frontend.DvbcFrontendSettings.Builder setSpectralInversion(int);
@@ -5587,9 +5589,10 @@
field public static final int VCM_MODE_UNDEFINED = 0; // 0x0
}
- public static class DvbsFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.DvbsFrontendSettings.Builder> {
+ public static class DvbsFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.DvbsFrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.DvbsFrontendSettings.Builder setCodeRate(@Nullable android.media.tv.tuner.frontend.DvbsCodeRate);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.DvbsFrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.DvbsFrontendSettings.Builder setInputStreamId(int);
method @NonNull public android.media.tv.tuner.frontend.DvbsFrontendSettings.Builder setModulation(int);
method @NonNull public android.media.tv.tuner.frontend.DvbsFrontendSettings.Builder setPilot(int);
@@ -5616,8 +5619,8 @@
method public int getConstellation();
method public int getGuardInterval();
method public int getHierarchy();
- method public int getHpCodeRate();
- method public int getLpCodeRate();
+ method public int getHighPriorityCodeRate();
+ method public int getLowPriorityCodeRate();
method public int getPlpGroupId();
method public int getPlpId();
method public int getPlpMode();
@@ -5645,20 +5648,20 @@
field public static final int CODERATE_8_9 = 512; // 0x200
field public static final int CODERATE_AUTO = 1; // 0x1
field public static final int CODERATE_UNDEFINED = 0; // 0x0
+ field public static final int CONSTELLATION_16QAM = 4; // 0x4
+ field public static final int CONSTELLATION_256QAM = 16; // 0x10
+ field public static final int CONSTELLATION_64QAM = 8; // 0x8
field public static final int CONSTELLATION_AUTO = 1; // 0x1
- field public static final int CONSTELLATION_CONSTELLATION_16QAM = 4; // 0x4
- field public static final int CONSTELLATION_CONSTELLATION_256QAM = 16; // 0x10
- field public static final int CONSTELLATION_CONSTELLATION_64QAM = 8; // 0x8
- field public static final int CONSTELLATION_CONSTELLATION_QPSK = 2; // 0x2
+ field public static final int CONSTELLATION_QPSK = 2; // 0x2
field public static final int CONSTELLATION_UNDEFINED = 0; // 0x0
+ field public static final int GUARD_INTERVAL_19_128 = 64; // 0x40
+ field public static final int GUARD_INTERVAL_19_256 = 128; // 0x80
+ field public static final int GUARD_INTERVAL_1_128 = 32; // 0x20
+ field public static final int GUARD_INTERVAL_1_16 = 4; // 0x4
+ field public static final int GUARD_INTERVAL_1_32 = 2; // 0x2
+ field public static final int GUARD_INTERVAL_1_4 = 16; // 0x10
+ field public static final int GUARD_INTERVAL_1_8 = 8; // 0x8
field public static final int GUARD_INTERVAL_AUTO = 1; // 0x1
- field public static final int GUARD_INTERVAL_INTERVAL_19_128 = 64; // 0x40
- field public static final int GUARD_INTERVAL_INTERVAL_19_256 = 128; // 0x80
- field public static final int GUARD_INTERVAL_INTERVAL_1_128 = 32; // 0x20
- field public static final int GUARD_INTERVAL_INTERVAL_1_16 = 4; // 0x4
- field public static final int GUARD_INTERVAL_INTERVAL_1_32 = 2; // 0x2
- field public static final int GUARD_INTERVAL_INTERVAL_1_4 = 16; // 0x10
- field public static final int GUARD_INTERVAL_INTERVAL_1_8 = 8; // 0x8
field public static final int GUARD_INTERVAL_UNDEFINED = 0; // 0x0
field public static final int HIERARCHY_1_INDEPTH = 64; // 0x40
field public static final int HIERARCHY_1_NATIVE = 4; // 0x4
@@ -5686,15 +5689,16 @@
field public static final int TRANSMISSION_MODE_UNDEFINED = 0; // 0x0
}
- public static class DvbtFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder> {
+ public static class DvbtFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setBandwidth(int);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setConstellation(int);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setGuardInterval(int);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setHierarchy(int);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setHighPriority(boolean);
- method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setHpCodeRate(int);
- method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setLpCodeRate(int);
+ method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setHighPriorityCodeRate(int);
+ method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setLowPriorityCodeRate(int);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setMiso(boolean);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setPlpGroupId(int);
method @NonNull public android.media.tv.tuner.frontend.DvbtFrontendSettings.Builder setPlpId(int);
@@ -5770,17 +5774,13 @@
field public static final int TYPE_UNDEFINED = 0; // 0x0
}
- public abstract static class FrontendSettings.Builder<T extends android.media.tv.tuner.frontend.FrontendSettings.Builder<T>> {
- method @IntRange(from=1) @NonNull public T setFrequency(int);
- }
-
public class FrontendStatus {
method public int getAgc();
method @NonNull public android.media.tv.tuner.frontend.FrontendStatus.Atsc3PlpInfo[] getAtsc3PlpInfo();
method public int getBer();
- method public long getFec();
method public int getFreqOffset();
method public int getHierarchy();
+ method public long getInnerFec();
method @NonNull public boolean[] getLayerErrors();
method public int getLnbVoltage();
method public int getMer();
@@ -5865,9 +5865,10 @@
field public static final int ROLLOFF_UNDEFINED = 0; // 0x0
}
- public static class Isdbs3FrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.Isdbs3FrontendSettings.Builder> {
+ public static class Isdbs3FrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.Isdbs3FrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.Isdbs3FrontendSettings.Builder setCodeRate(int);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.Isdbs3FrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.Isdbs3FrontendSettings.Builder setModulation(int);
method @NonNull public android.media.tv.tuner.frontend.Isdbs3FrontendSettings.Builder setRolloff(int);
method @NonNull public android.media.tv.tuner.frontend.Isdbs3FrontendSettings.Builder setStreamId(int);
@@ -5907,9 +5908,10 @@
field public static final int STREAM_ID_TYPE_RELATIVE_NUMBER = 1; // 0x1
}
- public static class IsdbsFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.IsdbsFrontendSettings.Builder> {
+ public static class IsdbsFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.IsdbsFrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.IsdbsFrontendSettings.Builder setCodeRate(int);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.IsdbsFrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbsFrontendSettings.Builder setModulation(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbsFrontendSettings.Builder setRolloff(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbsFrontendSettings.Builder setStreamId(int);
@@ -5952,10 +5954,11 @@
field public static final int MODULATION_UNDEFINED = 0; // 0x0
}
- public static class IsdbtFrontendSettings.Builder extends android.media.tv.tuner.frontend.FrontendSettings.Builder<android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder> {
+ public static class IsdbtFrontendSettings.Builder {
method @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings build();
method @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder setBandwidth(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder setCodeRate(int);
+ method @IntRange(from=1) @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder setFrequency(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder setGuardInterval(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder setMode(int);
method @NonNull public android.media.tv.tuner.frontend.IsdbtFrontendSettings.Builder setModulation(int);
@@ -6086,7 +6089,7 @@
method @Deprecated @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public String getCaptivePortalServerUrl();
method @Deprecated @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void getLatestTetheringEntitlementResult(int, boolean, @NonNull java.util.concurrent.Executor, @NonNull android.net.ConnectivityManager.OnTetheringEntitlementResultListener);
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.TETHER_PRIVILEGED, android.Manifest.permission.WRITE_SETTINGS}) public boolean isTetheringSupported();
- method @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) public int registerNetworkProvider(@NonNull android.net.NetworkProvider);
+ method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_FACTORY}) public int registerNetworkProvider(@NonNull android.net.NetworkProvider);
method @Deprecated @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void registerTetheringEventCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.ConnectivityManager.OnTetheringEventCallback);
method @Deprecated public void requestNetwork(@NonNull android.net.NetworkRequest, @NonNull android.net.ConnectivityManager.NetworkCallback, int, int, @NonNull android.os.Handler);
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_AIRPLANE_MODE, android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD, android.Manifest.permission.NETWORK_STACK}) public void setAirplaneMode(boolean);
@@ -6095,7 +6098,7 @@
method @Deprecated @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void startTethering(int, boolean, android.net.ConnectivityManager.OnStartTetheringCallback);
method @Deprecated @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void startTethering(int, boolean, android.net.ConnectivityManager.OnStartTetheringCallback, android.os.Handler);
method @Deprecated @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void stopTethering(int);
- method @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) public void unregisterNetworkProvider(@NonNull android.net.NetworkProvider);
+ method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_FACTORY}) public void unregisterNetworkProvider(@NonNull android.net.NetworkProvider);
method @Deprecated @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED) public void unregisterTetheringEventCallback(@NonNull android.net.ConnectivityManager.OnTetheringEventCallback);
field public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC = "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
field public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT = "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
@@ -6125,7 +6128,7 @@
}
public class EthernetManager {
- method @NonNull public android.net.EthernetManager.TetheredInterfaceRequest requestTetheredInterface(@NonNull android.net.EthernetManager.TetheredInterfaceCallback);
+ method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_STACK, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public android.net.EthernetManager.TetheredInterfaceRequest requestTetheredInterface(@NonNull java.util.concurrent.Executor, @NonNull android.net.EthernetManager.TetheredInterfaceCallback);
}
public static interface EthernetManager.TetheredInterfaceCallback {
@@ -6283,7 +6286,6 @@
method @Nullable public android.net.Network getNetwork();
method public void onAddKeepalivePacketFilter(int, @NonNull android.net.KeepalivePacketData);
method public void onAutomaticReconnectDisabled();
- method public void onBandwidthUpdateRequested();
method public void onNetworkUnwanted();
method public void onRemoveKeepalivePacketFilter(int);
method public void onSaveAcceptUnvalidated(boolean);
@@ -6297,23 +6299,17 @@
method public void sendNetworkScore(int);
method public void sendSocketKeepaliveEvent(int, int);
method public void setConnected();
- method @Deprecated public void setLegacyExtraInfo(@Nullable String);
- method @Deprecated public void setLegacySubtype(int, @NonNull String);
method public void unregister();
field public static final int VALIDATION_STATUS_NOT_VALID = 2; // 0x2
field public static final int VALIDATION_STATUS_VALID = 1; // 0x1
- field public final int providerId;
}
public final class NetworkAgentConfig implements android.os.Parcelable {
method public int describeContents();
method public int getLegacyType();
method @NonNull public String getLegacyTypeName();
- method @Nullable public String getSubscriberId();
method public boolean isExplicitlySelected();
- method public boolean isNat64DetectionEnabled();
method public boolean isPartialConnectivityAcceptable();
- method public boolean isProvisioningNotificationEnabled();
method public boolean isUnvalidatedConnectivityAcceptable();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.NetworkAgentConfig> CREATOR;
@@ -6322,18 +6318,14 @@
public static class NetworkAgentConfig.Builder {
ctor public NetworkAgentConfig.Builder();
method @NonNull public android.net.NetworkAgentConfig build();
- method @NonNull public android.net.NetworkAgentConfig.Builder disableNat64Detection();
- method @NonNull public android.net.NetworkAgentConfig.Builder disableProvisioningNotification();
method @NonNull public android.net.NetworkAgentConfig.Builder setExplicitlySelected(boolean);
method @NonNull public android.net.NetworkAgentConfig.Builder setLegacyType(int);
method @NonNull public android.net.NetworkAgentConfig.Builder setLegacyTypeName(@NonNull String);
method @NonNull public android.net.NetworkAgentConfig.Builder setPartialConnectivityAcceptable(boolean);
- method @NonNull public android.net.NetworkAgentConfig.Builder setSubscriberId(@Nullable String);
method @NonNull public android.net.NetworkAgentConfig.Builder setUnvalidatedConnectivityAcceptable(boolean);
}
public final class NetworkCapabilities implements android.os.Parcelable {
- method public boolean deduceRestrictedCapability();
method @NonNull public java.util.List<java.lang.Integer> getAdministratorUids();
method @Nullable public String getSSID();
method @NonNull public int[] getTransportTypes();
@@ -6358,27 +6350,9 @@
field public final android.net.WifiKey wifiKey;
}
- public class NetworkPolicyManager {
- method @NonNull public android.telephony.SubscriptionPlan[] getSubscriptionPlans(int, @NonNull String);
- method @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY) public void registerSubscriptionCallback(@NonNull android.net.NetworkPolicyManager.SubscriptionCallback);
- method public void setSubscriptionOverride(int, int, int, long, @NonNull String);
- method public void setSubscriptionPlans(int, @NonNull android.telephony.SubscriptionPlan[], @NonNull String);
- method @RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY) public void unregisterSubscriptionCallback(@NonNull android.net.NetworkPolicyManager.SubscriptionCallback);
- field public static final int SUBSCRIPTION_OVERRIDE_CONGESTED = 2; // 0x2
- field public static final int SUBSCRIPTION_OVERRIDE_UNMETERED = 1; // 0x1
- }
-
- public static class NetworkPolicyManager.SubscriptionCallback {
- ctor public NetworkPolicyManager.SubscriptionCallback();
- method public void onSubscriptionOverride(int, int, int);
- method public void onSubscriptionPlansChanged(int, @NonNull android.telephony.SubscriptionPlan[]);
- }
-
public class NetworkProvider {
ctor public NetworkProvider(@NonNull android.content.Context, @NonNull android.os.Looper, @NonNull String);
method @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) public void declareNetworkRequestUnfulfillable(@NonNull android.net.NetworkRequest);
- method @Nullable public android.os.Messenger getMessenger();
- method @NonNull public String getName();
method public int getProviderId();
method public void onNetworkRequested(@NonNull android.net.NetworkRequest, int, int);
method public void onRequestWithdrawn(@NonNull android.net.NetworkRequest);
@@ -6591,6 +6565,9 @@
field public static final int TETHER_ERROR_UNKNOWN_IFACE = 1; // 0x1
field public static final int TETHER_ERROR_UNSUPPORTED = 3; // 0x3
field public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7; // 0x7
+ field public static final int TETHER_HARDWARE_OFFLOAD_FAILED = 2; // 0x2
+ field public static final int TETHER_HARDWARE_OFFLOAD_STARTED = 1; // 0x1
+ field public static final int TETHER_HARDWARE_OFFLOAD_STOPPED = 0; // 0x0
}
public static interface TetheringManager.OnTetheringEntitlementResultListener {
@@ -6607,6 +6584,7 @@
ctor public TetheringManager.TetheringEventCallback();
method public void onClientsChanged(@NonNull java.util.Collection<android.net.TetheredClient>);
method public void onError(@NonNull String, int);
+ method public void onOffloadStatusChanged(int);
method @Deprecated public void onTetherableInterfaceRegexpsChanged(@NonNull android.net.TetheringManager.TetheringInterfaceRegexps);
method public void onTetherableInterfacesChanged(@NonNull java.util.List<java.lang.String>);
method public void onTetheredInterfacesChanged(@NonNull java.util.List<java.lang.String>);
@@ -7150,7 +7128,7 @@
method @NonNull public java.util.List<android.net.MacAddress> getBlockedClientList();
method public int getChannel();
method public int getMaxNumberOfClients();
- method public int getShutdownTimeoutMillis();
+ method public long getShutdownTimeoutMillis();
method public boolean isAutoShutdownEnabled();
method public boolean isClientControlByUserEnabled();
method @Nullable public android.net.wifi.WifiConfiguration toWifiConfiguration();
@@ -7164,16 +7142,17 @@
ctor public SoftApConfiguration.Builder();
ctor public SoftApConfiguration.Builder(@NonNull android.net.wifi.SoftApConfiguration);
method @NonNull public android.net.wifi.SoftApConfiguration build();
- method @NonNull public android.net.wifi.SoftApConfiguration.Builder enableClientControlByUser(boolean);
+ method @NonNull public android.net.wifi.SoftApConfiguration.Builder setAllowedClientList(@NonNull java.util.List<android.net.MacAddress>);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setAutoShutdownEnabled(boolean);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setBand(int);
+ method @NonNull public android.net.wifi.SoftApConfiguration.Builder setBlockedClientList(@NonNull java.util.List<android.net.MacAddress>);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setBssid(@Nullable android.net.MacAddress);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setChannel(int, int);
- method @NonNull public android.net.wifi.SoftApConfiguration.Builder setClientList(@NonNull java.util.List<android.net.MacAddress>, @NonNull java.util.List<android.net.MacAddress>);
+ method @NonNull public android.net.wifi.SoftApConfiguration.Builder setClientControlByUserEnabled(boolean);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setHiddenSsid(boolean);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setMaxNumberOfClients(@IntRange(from=0) int);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setPassphrase(@Nullable String, int);
- method @NonNull public android.net.wifi.SoftApConfiguration.Builder setShutdownTimeoutMillis(@IntRange(from=0) int);
+ method @NonNull public android.net.wifi.SoftApConfiguration.Builder setShutdownTimeoutMillis(@IntRange(from=0) long);
method @NonNull public android.net.wifi.SoftApConfiguration.Builder setSsid(@Nullable String);
}
@@ -7234,7 +7213,6 @@
field @Deprecated public int numScorerOverride;
field @Deprecated public int numScorerOverrideAndSwitchedNetwork;
field @Deprecated public boolean requirePmf;
- field @Deprecated @Nullable public String saePasswordId;
field @Deprecated public boolean shared;
field @Deprecated public boolean useExternalScores;
}
@@ -7322,17 +7300,17 @@
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD, android.Manifest.permission.NETWORK_STACK}) public void connect(int, @Nullable android.net.wifi.WifiManager.ActionListener);
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD, android.Manifest.permission.NETWORK_STACK}) public void disable(int, @Nullable android.net.wifi.WifiManager.ActionListener);
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_STACK}) public void disableEphemeralNetwork(@NonNull String);
- method @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL) public void factoryReset();
+ method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void factoryReset();
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD, android.Manifest.permission.NETWORK_STACK}) public void forget(int, @Nullable android.net.wifi.WifiManager.ActionListener);
method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public java.util.List<android.util.Pair<android.net.wifi.WifiConfiguration,java.util.Map<java.lang.Integer,java.util.List<android.net.wifi.ScanResult>>>> getAllMatchingWifiConfigs(@NonNull java.util.List<android.net.wifi.ScanResult>);
- method @Nullable @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL) public String getCountryCode();
+ method @Nullable @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public String getCountryCode();
method @Nullable @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public android.net.Network getCurrentNetwork();
method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public String[] getFactoryMacAddresses();
method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public java.util.Map<android.net.wifi.hotspot2.OsuProvider,java.util.List<android.net.wifi.ScanResult>> getMatchingOsuProviders(@Nullable java.util.List<android.net.wifi.ScanResult>);
method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public java.util.Map<android.net.wifi.hotspot2.OsuProvider,android.net.wifi.hotspot2.PasspointConfiguration> getMatchingPasspointConfigsForOsuProviders(@NonNull java.util.Set<android.net.wifi.hotspot2.OsuProvider>);
method @NonNull @RequiresPermission(allOf={android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_WIFI_STATE}) public java.util.Map<android.net.wifi.WifiNetworkSuggestion,java.util.List<android.net.wifi.ScanResult>> getMatchingScanResults(@NonNull java.util.List<android.net.wifi.WifiNetworkSuggestion>, @Nullable java.util.List<android.net.wifi.ScanResult>);
method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_WIFI_STATE, android.Manifest.permission.READ_WIFI_CREDENTIAL}) public java.util.List<android.net.wifi.WifiConfiguration> getPrivilegedConfiguredNetworks();
- method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public android.net.wifi.SoftApConfiguration getSoftApConfiguration();
+ method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public android.net.wifi.SoftApConfiguration getSoftApConfiguration();
method @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public void getWifiActivityEnergyInfoAsync(@NonNull java.util.concurrent.Executor, @NonNull android.net.wifi.WifiManager.OnWifiActivityEnergyInfoListener);
method @Deprecated @Nullable @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public android.net.wifi.WifiConfiguration getWifiApConfiguration();
method @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE) public int getWifiApState();
@@ -7453,9 +7431,9 @@
method public void onWifiUsabilityStats(int, boolean, @NonNull android.net.wifi.WifiUsabilityStatsEntry);
}
- public static interface WifiManager.ScoreChangeCallback {
- method public void onScoreChange(int, int);
- method public void onTriggerUpdateOfWifiUsabilityStats(int);
+ public static interface WifiManager.ScoreUpdateObserver {
+ method public void notifyScoreUpdate(int, int);
+ method public void triggerUpdateOfWifiUsabilityStats(int);
}
public static interface WifiManager.SoftApCallback {
@@ -7475,30 +7453,13 @@
}
public static interface WifiManager.WifiConnectedNetworkScorer {
- method public void setScoreChangeCallback(@NonNull android.net.wifi.WifiManager.ScoreChangeCallback);
- method public void start(int);
- method public void stop(int);
+ method public void onSetScoreUpdateObserver(@NonNull android.net.wifi.WifiManager.ScoreUpdateObserver);
+ method public void onStart(int);
+ method public void onStop(int);
}
public final class WifiMigration {
- method @Nullable public static android.net.wifi.WifiMigration.ConfigStoreMigrationData loadFromConfigStore();
method @NonNull public static android.net.wifi.WifiMigration.SettingsMigrationData loadFromSettings(@NonNull android.content.Context);
- method public static void removeConfigStore();
- }
-
- public static final class WifiMigration.ConfigStoreMigrationData implements android.os.Parcelable {
- method public int describeContents();
- method @Nullable public java.util.List<android.net.wifi.WifiConfiguration> getUserSavedNetworkConfigurations();
- method @Nullable public android.net.wifi.SoftApConfiguration getUserSoftApConfiguration();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.WifiMigration.ConfigStoreMigrationData> CREATOR;
- }
-
- public static final class WifiMigration.ConfigStoreMigrationData.Builder {
- ctor public WifiMigration.ConfigStoreMigrationData.Builder();
- method @NonNull public android.net.wifi.WifiMigration.ConfigStoreMigrationData build();
- method @NonNull public android.net.wifi.WifiMigration.ConfigStoreMigrationData.Builder setUserSavedNetworkConfigurations(@NonNull java.util.List<android.net.wifi.WifiConfiguration>);
- method @NonNull public android.net.wifi.WifiMigration.ConfigStoreMigrationData.Builder setUserSoftApConfiguration(@NonNull android.net.wifi.SoftApConfiguration);
}
public static final class WifiMigration.SettingsMigrationData implements android.os.Parcelable {
@@ -7809,9 +7770,6 @@
method public int getMaxNumberTxSpatialStreams();
method public boolean isChannelWidthSupported(int);
method public boolean isWifiStandardSupported(int);
- method public void setChannelWidthSupported(int, boolean);
- method public void setMaxNumberRxSpatialStreams(int);
- method public void setMaxNumberTxSpatialStreams(int);
method public void setWifiStandardSupport(int, boolean);
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.net.wifi.nl80211.DeviceWiphyCapabilities> CREATOR;
@@ -7982,7 +7940,7 @@
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void factoryReset(@NonNull android.net.wifi.p2p.WifiP2pManager.Channel, @Nullable android.net.wifi.p2p.WifiP2pManager.ActionListener);
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.READ_WIFI_CREDENTIAL}) public void requestPersistentGroupInfo(@NonNull android.net.wifi.p2p.WifiP2pManager.Channel, @Nullable android.net.wifi.p2p.WifiP2pManager.PersistentGroupInfoListener);
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.OVERRIDE_WIFI_CONFIG}) public void setDeviceName(@NonNull android.net.wifi.p2p.WifiP2pManager.Channel, @NonNull String, @Nullable android.net.wifi.p2p.WifiP2pManager.ActionListener);
- method @RequiresPermission(allOf={android.Manifest.permission.CONNECTIVITY_INTERNAL, android.Manifest.permission.CONFIGURE_WIFI_DISPLAY}) public void setMiracastMode(int);
+ method @RequiresPermission(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY) public void setMiracastMode(int);
method @RequiresPermission(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY) public void setWfdInfo(@NonNull android.net.wifi.p2p.WifiP2pManager.Channel, @NonNull android.net.wifi.p2p.WifiP2pWfdInfo, @Nullable android.net.wifi.p2p.WifiP2pManager.ActionListener);
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.OVERRIDE_WIFI_CONFIG}) public void setWifiP2pChannels(@NonNull android.net.wifi.p2p.WifiP2pManager.Channel, int, int, @Nullable android.net.wifi.p2p.WifiP2pManager.ActionListener);
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void startListening(@NonNull android.net.wifi.p2p.WifiP2pManager.Channel, @Nullable android.net.wifi.p2p.WifiP2pManager.ActionListener);
@@ -8220,13 +8178,15 @@
field public static final String ACTION_UPDATE_CARRIER_PROVISIONING_URLS = "android.intent.action.UPDATE_CARRIER_PROVISIONING_URLS";
field public static final String ACTION_UPDATE_CONVERSATION_ACTIONS = "android.intent.action.UPDATE_CONVERSATION_ACTIONS";
field public static final String ACTION_UPDATE_CT_LOGS = "android.intent.action.UPDATE_CT_LOGS";
- field public static final String ACTION_UPDATE_EMERGENCY_NUMBER_DB = "android.os.action.UPDATE_EMERGENCY_NUMBER_DB";
+ field @RequiresPermission("android.permission.UPDATE_CONFIG") public static final String ACTION_UPDATE_EMERGENCY_NUMBER_DB = "android.os.action.UPDATE_EMERGENCY_NUMBER_DB";
field public static final String ACTION_UPDATE_INTENT_FIREWALL = "android.intent.action.UPDATE_INTENT_FIREWALL";
field public static final String ACTION_UPDATE_LANG_ID = "android.intent.action.UPDATE_LANG_ID";
field public static final String ACTION_UPDATE_NETWORK_WATCHLIST = "android.intent.action.UPDATE_NETWORK_WATCHLIST";
field public static final String ACTION_UPDATE_PINS = "android.intent.action.UPDATE_PINS";
field public static final String ACTION_UPDATE_SMART_SELECTION = "android.intent.action.UPDATE_SMART_SELECTION";
field public static final String ACTION_UPDATE_SMS_SHORT_CODES = "android.intent.action.UPDATE_SMS_SHORT_CODES";
+ field public static final String EXTRA_REQUIRED_HASH = "android.os.extra.REQUIRED_HASH";
+ field public static final String EXTRA_VERSION = "android.os.extra.VERSION";
}
public class Environment {
@@ -8464,10 +8424,6 @@
method public boolean hasSingleFileDescriptor();
}
- public class ParcelFileDescriptor implements java.io.Closeable android.os.Parcelable {
- method @NonNull public static android.os.ParcelFileDescriptor wrap(@NonNull android.os.ParcelFileDescriptor, @NonNull android.os.Handler, @NonNull android.os.ParcelFileDescriptor.OnCloseListener) throws java.io.IOException;
- }
-
public final class PowerManager {
method @RequiresPermission(allOf={android.Manifest.permission.READ_DREAM_STATE, android.Manifest.permission.WRITE_DREAM_STATE}) public void dream(long);
method @RequiresPermission(android.Manifest.permission.DEVICE_POWER) public boolean forceSuspend();
@@ -8940,12 +8896,14 @@
method @BinderThread public abstract void onRevokeRuntimePermissions(@NonNull java.util.Map<java.lang.String,java.util.List<java.lang.String>>, boolean, int, @NonNull String, @NonNull java.util.function.Consumer<java.util.Map<java.lang.String,java.util.List<java.lang.String>>>);
method @BinderThread public abstract void onSetRuntimePermissionGrantStateByDeviceAdmin(@NonNull String, @NonNull String, @NonNull String, int, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @BinderThread public void onStageAndApplyRuntimePermissionsBackup(@NonNull android.os.UserHandle, @NonNull java.io.InputStream, @NonNull Runnable);
- method @BinderThread public void onUpdateUserSensitivePermissionFlags();
+ method @BinderThread public void onUpdateUserSensitivePermissionFlags(int, @NonNull Runnable);
field public static final String SERVICE_INTERFACE = "android.permission.PermissionControllerService";
}
public final class PermissionManager {
- method @IntRange(from=0) @RequiresPermission(anyOf={android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, "android.permission.UPGRADE_RUNTIME_PERMISSIONS"}) public int getRuntimePermissionsVersion();
+ method @NonNull @RequiresPermission(android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY) public java.util.Set<java.lang.String> getAutoRevokeExemptionGrantedPackages();
+ method @NonNull @RequiresPermission(android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY) public java.util.Set<java.lang.String> getAutoRevokeExemptionRequestedPackages();
+ method @IntRange(from=0) @RequiresPermission(anyOf={android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, android.Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS}) public int getRuntimePermissionsVersion();
method @NonNull public java.util.List<android.permission.PermissionManager.SplitPermissionInfo> getSplitPermissions();
method @RequiresPermission(android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS) public void grantDefaultPermissionsToEnabledCarrierApps(@NonNull String[], @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @RequiresPermission(android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS) public void grantDefaultPermissionsToEnabledImsServices(@NonNull String[], @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
@@ -8953,7 +8911,7 @@
method @RequiresPermission(android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS) public void grantDefaultPermissionsToLuiApp(@NonNull String, @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @RequiresPermission(android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS) public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(@NonNull String[], @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @RequiresPermission(android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS) public void revokeDefaultPermissionsFromLuiApps(@NonNull String[], @NonNull android.os.UserHandle, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
- method @RequiresPermission(anyOf={android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, "android.permission.UPGRADE_RUNTIME_PERMISSIONS"}) public void setRuntimePermissionsVersion(@IntRange(from=0) int);
+ method @RequiresPermission(anyOf={android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, android.Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS}) public void setRuntimePermissionsVersion(@IntRange(from=0) int);
method @RequiresPermission(android.Manifest.permission.MANAGE_ONE_TIME_PERMISSION_SESSIONS) public void startOneTimePermissionSession(@NonNull String, long, int, int);
method @RequiresPermission(android.Manifest.permission.MANAGE_ONE_TIME_PERMISSION_SESSIONS) public void stopOneTimePermissionSession(@NonNull String);
}
@@ -9067,18 +9025,6 @@
package android.provider {
- public class BlockedNumberContract {
- field public static final String METHOD_NOTIFY_EMERGENCY_CONTACT = "notify_emergency_contact";
- field public static final String METHOD_SHOULD_SYSTEM_BLOCK_NUMBER = "should_system_block_number";
- field public static final String RES_BLOCK_STATUS = "block_status";
- field public static final int STATUS_BLOCKED_IN_LIST = 1; // 0x1
- field public static final int STATUS_BLOCKED_NOT_IN_CONTACTS = 5; // 0x5
- field public static final int STATUS_BLOCKED_PAYPHONE = 4; // 0x4
- field public static final int STATUS_BLOCKED_RESTRICTED = 2; // 0x2
- field public static final int STATUS_BLOCKED_UNKNOWN_NUMBER = 3; // 0x3
- field public static final int STATUS_NOT_BLOCKED = 0; // 0x0
- }
-
@Deprecated public static final class ContactsContract.MetadataSync implements android.provider.BaseColumns android.provider.ContactsContract.MetadataSyncColumns {
field @Deprecated public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_metadata";
field @Deprecated public static final String CONTENT_TYPE = "vnd.android.cursor.dir/contact_metadata";
@@ -9128,6 +9074,7 @@
field public static final String NAMESPACE_ATTENTION_MANAGER_SERVICE = "attention_manager_service";
field public static final String NAMESPACE_AUTOFILL = "autofill";
field public static final String NAMESPACE_BIOMETRICS = "biometrics";
+ field public static final String NAMESPACE_BLOBSTORE = "blobstore";
field public static final String NAMESPACE_CONNECTIVITY = "connectivity";
field public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture";
field @Deprecated public static final String NAMESPACE_DEX_BOOT = "dex_boot";
@@ -9200,9 +9147,9 @@
public final class MediaStore {
method @NonNull public static android.net.Uri rewriteToLegacy(@NonNull android.net.Uri);
- method @NonNull public static android.net.Uri scanFile(@NonNull android.content.ContentResolver, @NonNull java.io.File);
- method public static void scanVolume(@NonNull android.content.ContentResolver, @NonNull String);
- method public static void waitForIdle(@NonNull android.content.ContentResolver);
+ method @NonNull @WorkerThread public static android.net.Uri scanFile(@NonNull android.content.ContentResolver, @NonNull java.io.File);
+ method @WorkerThread public static void scanVolume(@NonNull android.content.ContentResolver, @NonNull String);
+ method @WorkerThread public static void waitForIdle(@NonNull android.content.ContentResolver);
field public static final String AUTHORITY_LEGACY = "media_legacy";
field @NonNull public static final android.net.Uri AUTHORITY_LEGACY_URI;
}
@@ -9376,7 +9323,6 @@
field public static final String AUTOFILL_USER_DATA_MAX_VALUE_LENGTH = "autofill_user_data_max_value_length";
field public static final String AUTOFILL_USER_DATA_MIN_VALUE_LENGTH = "autofill_user_data_min_value_length";
field public static final String AUTO_REVOKE_DISABLED = "auto_revoke_disabled";
- field public static final String CARRIER_APPS_HANDLED = "carrier_apps_handled";
field public static final String COMPLETED_CATEGORY_PREFIX = "suggested.completed_category.";
field public static final String DOZE_ALWAYS_ON = "doze_always_on";
field public static final String HUSH_GESTURE_USED = "hush_gesture_used";
@@ -9389,7 +9335,6 @@
field public static final String LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS = "lock_screen_allow_private_notifications";
field public static final String LOCK_SCREEN_SHOW_NOTIFICATIONS = "lock_screen_show_notifications";
field public static final String ODI_CAPTIONS_ENABLED = "odi_captions_enabled";
- field public static final String SECURE_FRP_MODE = "secure_frp_mode";
field public static final String THEME_CUSTOMIZATION_OVERLAY_PACKAGES = "theme_customization_overlay_packages";
field public static final String USER_SETUP_COMPLETE = "user_setup_complete";
field public static final int USER_SETUP_PERSONALIZATION_COMPLETE = 10; // 0xa
@@ -9435,20 +9380,12 @@
public static final class Telephony.Carriers implements android.provider.BaseColumns {
field public static final String APN_SET_ID = "apn_set_id";
- field @Deprecated public static final String BEARER_BITMASK = "bearer_bitmask";
field public static final int CARRIER_EDITED = 4; // 0x4
- field @NonNull public static final android.net.Uri DPC_URI;
field public static final String EDITED_STATUS = "edited";
- field public static final int INVALID_APN_ID = -1; // 0xffffffff
field public static final String MAX_CONNECTIONS = "max_conns";
field public static final String MODEM_PERSIST = "modem_cognitive";
field public static final String MTU = "mtu";
field public static final int NO_APN_SET_ID = 0; // 0x0
- field public static final String PROFILE_ID = "profile_id";
- field public static final String SKIP_464XLAT = "skip_464xlat";
- field public static final int SKIP_464XLAT_DEFAULT = -1; // 0xffffffff
- field public static final int SKIP_464XLAT_DISABLE = 0; // 0x0
- field public static final int SKIP_464XLAT_ENABLE = 1; // 0x1
field public static final String TIME_LIMIT_FOR_MAX_CONNECTIONS = "max_conns_time";
field public static final int UNEDITED = 0; // 0x0
field public static final int USER_DELETED = 2; // 0x2
@@ -9813,7 +9750,7 @@
public static final class Dataset.Builder {
ctor public Dataset.Builder(@NonNull android.service.autofill.InlinePresentation);
- method @NonNull public android.service.autofill.Dataset.Builder setInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
+ method @NonNull public android.service.autofill.Dataset.Builder setFieldInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
}
public abstract class InlineSuggestionRenderService extends android.app.Service {
@@ -9863,10 +9800,10 @@
public static final class FillResponse.Builder {
ctor public FillResponse.Builder();
method @NonNull public android.service.autofill.augmented.FillResponse build();
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setClientState(@Nullable android.os.Bundle);
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@Nullable android.service.autofill.augmented.FillWindow);
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineActions(@Nullable java.util.List<android.service.autofill.InlinePresentation>);
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineSuggestions(@Nullable java.util.List<android.service.autofill.Dataset>);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setClientState(@NonNull android.os.Bundle);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@NonNull android.service.autofill.augmented.FillWindow);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineActions(@NonNull java.util.List<android.service.autofill.InlineAction>);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineSuggestions(@NonNull java.util.List<android.service.autofill.Dataset>);
}
public final class FillWindow implements java.lang.AutoCloseable {
@@ -9974,7 +9911,7 @@
}
public static final class DataLoaderService.FileSystemConnector {
- method public void writeData(@NonNull String, long, long, @NonNull android.os.ParcelFileDescriptor) throws java.io.IOException;
+ method @RequiresPermission(android.Manifest.permission.INSTALL_PACKAGES) public void writeData(@NonNull String, long, long, @NonNull android.os.ParcelFileDescriptor) throws java.io.IOException;
}
}
@@ -10652,14 +10589,7 @@
}
public final class PhoneAccount implements android.os.Parcelable {
- field public static final int CAPABILITY_EMERGENCY_CALLS_ONLY = 128; // 0x80
- field public static final int CAPABILITY_EMERGENCY_PREFERRED = 8192; // 0x2000
- field public static final int CAPABILITY_EMERGENCY_VIDEO_CALLING = 512; // 0x200
field public static final int CAPABILITY_MULTI_USER = 32; // 0x20
- field public static final String EXTRA_ALWAYS_USE_VOIP_AUDIO_MODE = "android.telecom.extra.ALWAYS_USE_VOIP_AUDIO_MODE";
- field public static final String EXTRA_PLAY_CALL_RECORDING_TONE = "android.telecom.extra.PLAY_CALL_RECORDING_TONE";
- field public static final String EXTRA_SORT_ORDER = "android.telecom.extra.SORT_ORDER";
- field public static final String EXTRA_SUPPORTS_VIDEO_CALLING_FALLBACK = "android.telecom.extra.SUPPORTS_VIDEO_CALLING_FALLBACK";
}
public static class PhoneAccount.Builder {
@@ -10745,20 +10675,13 @@
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean isInEmergencyCall();
method @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isRinging();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setUserSelectedOutgoingPhoneAccount(@Nullable android.telecom.PhoneAccountHandle);
- field public static final String ACTION_CURRENT_TTY_MODE_CHANGED = "android.telecom.action.CURRENT_TTY_MODE_CHANGED";
- field public static final String ACTION_TTY_PREFERRED_MODE_CHANGED = "android.telecom.action.TTY_PREFERRED_MODE_CHANGED";
field public static final int CALL_SOURCE_EMERGENCY_DIALPAD = 1; // 0x1
field public static final int CALL_SOURCE_EMERGENCY_SHORTCUT = 2; // 0x2
field public static final int CALL_SOURCE_UNSPECIFIED = 0; // 0x0
field public static final String EXTRA_CALL_BACK_INTENT = "android.telecom.extra.CALL_BACK_INTENT";
- field public static final String EXTRA_CALL_SOURCE = "android.telecom.extra.CALL_SOURCE";
- field public static final String EXTRA_CALL_TECHNOLOGY_TYPE = "android.telecom.extra.CALL_TECHNOLOGY_TYPE";
field public static final String EXTRA_CLEAR_MISSED_CALLS_INTENT = "android.telecom.extra.CLEAR_MISSED_CALLS_INTENT";
field public static final String EXTRA_CONNECTION_SERVICE = "android.telecom.extra.CONNECTION_SERVICE";
- field public static final String EXTRA_CURRENT_TTY_MODE = "android.telecom.extra.CURRENT_TTY_MODE";
field public static final String EXTRA_IS_USER_INTENT_EMERGENCY_CALL = "android.telecom.extra.IS_USER_INTENT_EMERGENCY_CALL";
- field public static final String EXTRA_TTY_PREFERRED_MODE = "android.telecom.extra.TTY_PREFERRED_MODE";
- field public static final String EXTRA_UNKNOWN_CALL_HANDLE = "android.telecom.extra.UNKNOWN_CALL_HANDLE";
field public static final int TTY_MODE_FULL = 1; // 0x1
field public static final int TTY_MODE_HCO = 2; // 0x2
field public static final int TTY_MODE_OFF = 0; // 0x0
@@ -10912,19 +10835,6 @@
method @NonNull public java.util.List<android.telephony.CbGeoUtils.LatLng> getVertices();
}
- public final class CdmaEriInformation implements android.os.Parcelable {
- method public int describeContents();
- method public int getEriIconIndex();
- method public int getEriIconMode();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CdmaEriInformation> CREATOR;
- field public static final int ERI_FLASH = 2; // 0x2
- field public static final int ERI_ICON_MODE_FLASH = 1; // 0x1
- field public static final int ERI_ICON_MODE_NORMAL = 0; // 0x0
- field public static final int ERI_OFF = 1; // 0x1
- field public static final int ERI_ON = 0; // 0x0
- }
-
public class CellBroadcastIntents {
method public static void sendSmsCbReceivedBroadcast(@NonNull android.content.Context, @Nullable android.os.UserHandle, @NonNull android.telephony.SmsCbMessage, @Nullable android.content.BroadcastReceiver, @Nullable android.os.Handler, int, int);
field public static final String ACTION_AREA_INFO_UPDATED = "android.telephony.action.AREA_INFO_UPDATED";
@@ -10982,7 +10892,6 @@
public final class DataSpecificRegistrationInfo implements android.os.Parcelable {
method public int describeContents();
method @NonNull public android.telephony.LteVopsSupportInfo getLteVopsSupportInfo();
- method public boolean isUsingCarrierAggregation();
method public void writeToParcel(android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.telephony.DataSpecificRegistrationInfo> CREATOR;
}
@@ -11220,19 +11129,6 @@
field @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public static final int LISTEN_VOICE_ACTIVATION_STATE = 131072; // 0x20000
}
- public final class PinResult implements android.os.Parcelable {
- ctor public PinResult(int, int);
- method public int describeContents();
- method public int getAttemptsRemaining();
- method @NonNull public static android.telephony.PinResult getDefaultFailedResult();
- method public int getType();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PinResult> CREATOR;
- field public static final int PIN_RESULT_TYPE_FAILURE = 2; // 0x2
- field public static final int PIN_RESULT_TYPE_INCORRECT = 1; // 0x1
- field public static final int PIN_RESULT_TYPE_SUCCESS = 0; // 0x0
- }
-
public final class PreciseCallState implements android.os.Parcelable {
ctor public PreciseCallState(int, int, int, int, int);
method public int describeContents();
@@ -11362,13 +11258,9 @@
public class ServiceState implements android.os.Parcelable {
method public void fillInNotifierBundle(@NonNull android.os.Bundle);
- method public int getDataNetworkType();
- method public int getDataRegistrationState();
- method public boolean getDataRoamingFromRegistration();
method @Nullable public android.telephony.NetworkRegistrationInfo getNetworkRegistrationInfo(int, int);
method @NonNull public java.util.List<android.telephony.NetworkRegistrationInfo> getNetworkRegistrationInfoListForDomain(int);
method @NonNull public java.util.List<android.telephony.NetworkRegistrationInfo> getNetworkRegistrationInfoListForTransportType(int);
- method public int getNrFrequencyRange();
method @NonNull public static android.telephony.ServiceState newFromBundle(@NonNull android.os.Bundle);
field public static final int ROAMING_TYPE_DOMESTIC = 2; // 0x2
field public static final int ROAMING_TYPE_INTERNATIONAL = 3; // 0x3
@@ -11511,7 +11403,6 @@
method @NonNull @RequiresPermission(android.Manifest.permission.ACCESS_MESSAGES_ON_ICC) public java.util.List<android.telephony.SmsMessage> getMessagesFromIcc();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getPremiumSmsConsent(@NonNull String);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getSmsCapacityOnIcc();
- method public void sendMultipartTextMessage(@NonNull String, @Nullable String, @NonNull java.util.List<java.lang.String>, @Nullable java.util.List<android.app.PendingIntent>, @Nullable java.util.List<android.app.PendingIntent>, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void sendMultipartTextMessageWithoutPersisting(String, String, java.util.List<java.lang.String>, java.util.List<android.app.PendingIntent>, java.util.List<android.app.PendingIntent>);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setPremiumSmsConsent(@NonNull String, int);
field public static final int PREMIUM_SMS_CONSENT_ALWAYS_ALLOW = 3; // 0x3
@@ -11599,9 +11490,7 @@
}
public class TelephonyManager {
- method public int addDevicePolicyOverrideApn(@NonNull android.content.Context, @NonNull android.telephony.data.ApnSetting);
method @Deprecated @RequiresPermission(android.Manifest.permission.CALL_PHONE) public void call(String, String);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int changeIccLockPassword(@NonNull String, @NonNull String);
method public int checkCarrierPrivilegesForPackage(String);
method public int checkCarrierPrivilegesForPackageAnyPhone(String);
method public void dial(String);
@@ -11612,6 +11501,7 @@
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getAidForAppType(int);
method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.List<android.service.carrier.CarrierIdentifier> getAllowedCarriers(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public long getAllowedNetworkTypes();
+ method @Nullable @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public android.content.ComponentName getAndUpdateDefaultRespondViaMessageApplication();
method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.CallForwardingInfo getCallForwarding(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getCallWaitingStatus();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.ImsiEncryptionInfo getCarrierInfoForImsiEncryption(int);
@@ -11620,26 +11510,21 @@
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getCarrierPrivilegeStatus(int);
method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.List<java.lang.String> getCarrierPrivilegedPackagesForAllActiveSubscriptions();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.CarrierRestrictionRules getCarrierRestrictionRules();
- method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.CdmaEriInformation getCdmaEriInformation();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String getCdmaMdn();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String getCdmaMdn(int);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String getCdmaMin();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public String getCdmaMin(int);
method public String getCdmaPrlVersion();
- method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getCdmaRoamingMode();
method public int getCurrentPhoneType();
method public int getCurrentPhoneType(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getDataActivationState();
method @Deprecated public boolean getDataEnabled();
method @Deprecated public boolean getDataEnabled(int);
- method @Nullable public static android.content.ComponentName getDefaultRespondViaMessageApplication(@NonNull android.content.Context, boolean);
- method @NonNull public static String getDefaultSimCountryIso();
- method @NonNull public java.util.List<android.telephony.data.ApnSetting> getDevicePolicyOverrideApns(@NonNull android.content.Context);
+ method @Nullable @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public android.content.ComponentName getDefaultRespondViaMessageApplication();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getDeviceSoftwareVersion(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean getEmergencyCallbackMode();
- method public int getEmergencyNumberDbVersion();
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getEmergencyNumberDbVersion();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getIsimDomain();
- method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String[] getIsimImpu();
method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getIsimIst();
method @NonNull @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.Map<java.lang.Integer,java.lang.Integer> getLogicalToPhysicalSlotMapping();
method public int getMaxNumberOfSimultaneouslyActiveSims();
@@ -11666,16 +11551,13 @@
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isAnyRadioPoweredOn();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isApnMetered(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isApplicationOnUicc(int);
- method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isDataAllowedInVoiceCall();
- method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isDataConnectionEnabled();
+ method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isDataConnectionAllowed();
method public boolean isDataConnectivityPossible();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isDataEnabledForApn(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isEmergencyAssistanceEnabled();
- method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) @WorkerThread public boolean isIccLockEnabled();
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isIdle();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isInEmergencySmsMode();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isLteCdmaEvdoGsmWcdmaEnabled();
- method public boolean isModemEnabledForSlot(int);
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isOffhook();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isOpportunisticNetworkEnabled();
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isPotentialEmergencyNumber(@NonNull String);
@@ -11685,7 +11567,6 @@
method @Deprecated @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PHONE_STATE}) public boolean isVideoCallingEnabled();
method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean isVisualVoicemailEnabled(android.telecom.PhoneAccountHandle);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean matchesCurrentSimOperator(@NonNull String, int, @Nullable String);
- method public boolean modifyDevicePolicyOverrideApn(@NonNull android.content.Context, int, @NonNull android.telephony.data.ApnSetting);
method public boolean needsOtaServiceProvisioning();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void notifyOtaEmergencyNumberDbInstalled();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void notifyUserActivity();
@@ -11697,6 +11578,7 @@
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void resetAllCarrierActions();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void resetCarrierKeysForImsiEncryption();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) @WorkerThread public void resetIms(int);
+ method @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public void resetOtaEmergencyNumberDbFilePath();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean resetRadioConfig();
method @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL) public void resetSettings();
method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setAllowedCarriers(int, java.util.List<android.service.carrier.CarrierIdentifier>);
@@ -11706,13 +11588,9 @@
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setCallWaitingStatus(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setCarrierDataEnabled(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setCarrierRestrictionRules(@NonNull android.telephony.CarrierRestrictionRules);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setCdmaRoamingMode(int);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setCdmaSubscriptionMode(int);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDataActivationState(int);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setDataAllowedDuringVoiceCall(boolean);
method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDataEnabled(int, boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setDataRoamingEnabled(boolean);
- method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setIccLockEnabled(boolean, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setMultiSimCarrierRestriction(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setOpportunisticNetworkState(boolean);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean setPreferredNetworkTypeBitmask(long);
@@ -11727,15 +11605,13 @@
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setVoiceActivationState(int);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void shutdownAllRadios();
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean supplyPin(String);
- method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.telephony.PinResult supplyPinReportPinResult(@NonNull String);
method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int[] supplyPinReportResult(String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean supplyPuk(String, String);
- method @Nullable @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public android.telephony.PinResult supplyPukReportPinResult(@NonNull String, @NonNull String);
method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int[] supplyPukReportResult(String, String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean switchSlots(int[]);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void toggleRadioOnOff();
+ method @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public void updateOtaEmergencyNumberDbFilePath(@NonNull android.os.ParcelFileDescriptor);
method public void updateServiceLocation();
- method @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION) public void updateTestOtaEmergencyNumberDbFilePath(@NonNull String);
field @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public static final String ACTION_ANOMALY_REPORTED = "android.telephony.action.ANOMALY_REPORTED";
field public static final String ACTION_CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE = "com.android.internal.telephony.CARRIER_SIGNAL_DEFAULT_NETWORK_AVAILABLE";
field public static final String ACTION_CARRIER_SIGNAL_PCO_VALUE = "com.android.internal.telephony.CARRIER_SIGNAL_PCO_VALUE";
@@ -11764,10 +11640,6 @@
field public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1; // 0x1
field public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0; // 0x0
field public static final int CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED = -1; // 0xffffffff
- field public static final int CDMA_SUBSCRIPTION_NV = 1; // 0x1
- field public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0; // 0x0
- field public static final int CDMA_SUBSCRIPTION_UNKNOWN = -1; // 0xffffffff
- field public static final int CHANGE_ICC_LOCK_SUCCESS = 2147483647; // 0x7fffffff
field public static final String EXTRA_ANOMALY_DESCRIPTION = "android.telephony.extra.ANOMALY_DESCRIPTION";
field public static final String EXTRA_ANOMALY_ID = "android.telephony.extra.ANOMALY_ID";
field @Deprecated public static final String EXTRA_APN_PROTOCOL = "apnProto";
@@ -11823,7 +11695,6 @@
field public static final long NETWORK_TYPE_BITMASK_TD_SCDMA = 65536L; // 0x10000L
field public static final long NETWORK_TYPE_BITMASK_UMTS = 4L; // 0x4L
field public static final long NETWORK_TYPE_BITMASK_UNKNOWN = 0L; // 0x0L
- field public static final int PHONE_TYPE_THIRD_PARTY = 4; // 0x4
field public static final int RADIO_POWER_OFF = 0; // 0x0
field public static final int RADIO_POWER_ON = 1; // 0x1
field public static final int RADIO_POWER_UNAVAILABLE = 2; // 0x2
@@ -11903,23 +11774,6 @@
package android.telephony.data {
- public class ApnSetting implements android.os.Parcelable {
- method @NonNull public static String getApnTypesStringFromBitmask(int);
- field public static final String TYPE_ALL_STRING = "*";
- field public static final String TYPE_CBS_STRING = "cbs";
- field public static final String TYPE_DEFAULT_STRING = "default";
- field public static final String TYPE_DUN_STRING = "dun";
- field public static final String TYPE_EMERGENCY_STRING = "emergency";
- field public static final String TYPE_FOTA_STRING = "fota";
- field public static final String TYPE_HIPRI_STRING = "hipri";
- field public static final String TYPE_IA_STRING = "ia";
- field public static final String TYPE_IMS_STRING = "ims";
- field public static final String TYPE_MCX_STRING = "mcx";
- field public static final String TYPE_MMS_STRING = "mms";
- field public static final String TYPE_SUPL_STRING = "supl";
- field public static final String TYPE_XCAP_STRING = "xcap";
- }
-
public final class DataCallResponse implements android.os.Parcelable {
method public int describeContents();
method @NonNull public java.util.List<android.net.LinkAddress> getAddresses();
@@ -12245,7 +12099,7 @@
method public int getEmergencyServiceCategories();
method @NonNull public java.util.List<java.lang.String> getEmergencyUrns();
method public android.telephony.ims.ImsStreamMediaProfile getMediaProfile();
- method @Nullable public android.os.Bundle getProprietaryCallExtras();
+ method @NonNull public android.os.Bundle getProprietaryCallExtras();
method public int getRestrictCause();
method public int getServiceType();
method public static int getVideoStateFromCallType(int);
@@ -12407,10 +12261,6 @@
field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsExternalCallState> CREATOR;
}
- public class ImsManager {
- field public static final String ACTION_FORBIDDEN_NO_SERVICE_AUTHORIZATION = "com.android.internal.intent.action.ACTION_FORBIDDEN_NO_SERVICE_AUTHORIZATION";
- }
-
public class ImsMmTelManager implements android.telephony.ims.RegistrationManager {
method @Deprecated @NonNull @RequiresPermission(anyOf={android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, android.Manifest.permission.READ_PRECISE_PHONE_STATE}) public static android.telephony.ims.ImsMmTelManager createForSubscriptionId(int);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getFeatureState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>) throws android.telephony.ims.ImsException;
@@ -12676,82 +12526,12 @@
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) @WorkerThread public int setProvisioningStringValue(int, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) @WorkerThread public void setRcsProvisioningStatusForCapability(int, boolean);
method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void unregisterProvisioningChangedCallback(@NonNull android.telephony.ims.ProvisioningManager.Callback);
- field public static final int KEY_1X_EPDG_TIMER_SEC = 64; // 0x40
- field public static final int KEY_1X_THRESHOLD = 59; // 0x3b
- field public static final int KEY_AMR_BANDWIDTH_EFFICIENT_PAYLOAD_TYPE = 50; // 0x32
- field public static final int KEY_AMR_CODEC_MODE_SET_VALUES = 0; // 0x0
- field public static final int KEY_AMR_DEFAULT_ENCODING_MODE = 53; // 0x35
- field public static final int KEY_AMR_OCTET_ALIGNED_PAYLOAD_TYPE = 49; // 0x31
- field public static final int KEY_AMR_WB_BANDWIDTH_EFFICIENT_PAYLOAD_TYPE = 48; // 0x30
- field public static final int KEY_AMR_WB_CODEC_MODE_SET_VALUES = 1; // 0x1
- field public static final int KEY_AMR_WB_OCTET_ALIGNED_PAYLOAD_TYPE = 47; // 0x2f
- field public static final int KEY_DTMF_NB_PAYLOAD_TYPE = 52; // 0x34
- field public static final int KEY_DTMF_WB_PAYLOAD_TYPE = 51; // 0x33
- field public static final int KEY_EAB_PROVISIONING_STATUS = 25; // 0x19
- field public static final int KEY_ENABLE_SILENT_REDIAL = 6; // 0x6
- field public static final int KEY_LOCAL_BREAKOUT_PCSCF_ADDRESS = 31; // 0x1f
- field public static final int KEY_LTE_EPDG_TIMER_SEC = 62; // 0x3e
- field public static final int KEY_LTE_THRESHOLD_1 = 56; // 0x38
- field public static final int KEY_LTE_THRESHOLD_2 = 57; // 0x39
- field public static final int KEY_LTE_THRESHOLD_3 = 58; // 0x3a
- field public static final int KEY_MINIMUM_SIP_SESSION_EXPIRATION_TIMER_SEC = 3; // 0x3
- field public static final int KEY_MOBILE_DATA_ENABLED = 29; // 0x1d
- field public static final int KEY_MULTIENDPOINT_ENABLED = 65; // 0x41
- field public static final int KEY_RCS_AVAILABILITY_CACHE_EXPIRATION_SEC = 19; // 0x13
- field public static final int KEY_RCS_CAPABILITIES_CACHE_EXPIRATION_SEC = 18; // 0x12
- field public static final int KEY_RCS_CAPABILITIES_POLL_INTERVAL_SEC = 20; // 0x14
- field public static final int KEY_RCS_CAPABILITY_DISCOVERY_ENABLED = 17; // 0x11
- field public static final int KEY_RCS_CAPABILITY_POLL_LIST_SUB_EXP_SEC = 23; // 0x17
- field public static final int KEY_RCS_MAX_NUM_ENTRIES_IN_RCL = 22; // 0x16
- field public static final int KEY_RCS_PUBLISH_SOURCE_THROTTLE_MS = 21; // 0x15
- field public static final int KEY_RCS_PUBLISH_TIMER_EXTENDED_SEC = 16; // 0x10
- field public static final int KEY_RCS_PUBLISH_TIMER_SEC = 15; // 0xf
- field public static final int KEY_REGISTRATION_DOMAIN_NAME = 12; // 0xc
- field public static final int KEY_REGISTRATION_RETRY_BASE_TIME_SEC = 33; // 0x21
- field public static final int KEY_REGISTRATION_RETRY_MAX_TIME_SEC = 34; // 0x22
- field public static final int KEY_RTP_SPEECH_END_PORT = 36; // 0x24
- field public static final int KEY_RTP_SPEECH_START_PORT = 35; // 0x23
- field public static final int KEY_RTT_ENABLED = 66; // 0x42
- field public static final int KEY_SIP_ACK_RECEIPT_WAIT_TIME_MS = 43; // 0x2b
- field public static final int KEY_SIP_ACK_RETRANSMIT_WAIT_TIME_MS = 44; // 0x2c
- field public static final int KEY_SIP_INVITE_ACK_WAIT_TIME_MS = 38; // 0x26
- field public static final int KEY_SIP_INVITE_CANCELLATION_TIMER_MS = 4; // 0x4
- field public static final int KEY_SIP_INVITE_REQUEST_TRANSMIT_INTERVAL_MS = 37; // 0x25
- field public static final int KEY_SIP_INVITE_RESPONSE_RETRANSMIT_INTERVAL_MS = 42; // 0x2a
- field public static final int KEY_SIP_INVITE_RESPONSE_RETRANSMIT_WAIT_TIME_MS = 39; // 0x27
- field public static final int KEY_SIP_KEEP_ALIVE_ENABLED = 32; // 0x20
- field public static final int KEY_SIP_NON_INVITE_REQUEST_RETRANSMISSION_WAIT_TIME_MS = 45; // 0x2d
- field public static final int KEY_SIP_NON_INVITE_REQUEST_RETRANSMIT_INTERVAL_MS = 40; // 0x28
- field public static final int KEY_SIP_NON_INVITE_RESPONSE_RETRANSMISSION_WAIT_TIME_MS = 46; // 0x2e
- field public static final int KEY_SIP_NON_INVITE_TRANSACTION_TIMEOUT_TIMER_MS = 41; // 0x29
- field public static final int KEY_SIP_SESSION_TIMER_SEC = 2; // 0x2
- field public static final int KEY_SMS_FORMAT = 13; // 0xd
- field public static final int KEY_SMS_OVER_IP_ENABLED = 14; // 0xe
- field public static final int KEY_SMS_PUBLIC_SERVICE_IDENTITY = 54; // 0x36
- field public static final int KEY_T1_TIMER_VALUE_MS = 7; // 0x7
- field public static final int KEY_T2_TIMER_VALUE_MS = 8; // 0x8
- field public static final int KEY_TF_TIMER_VALUE_MS = 9; // 0x9
- field public static final int KEY_TRANSITION_TO_LTE_DELAY_MS = 5; // 0x5
- field public static final int KEY_USE_GZIP_FOR_LIST_SUBSCRIPTION = 24; // 0x18
- field public static final int KEY_VIDEO_QUALITY = 55; // 0x37
- field public static final int KEY_VOICE_OVER_WIFI_ENABLED_OVERRIDE = 28; // 0x1c
field public static final int KEY_VOICE_OVER_WIFI_MODE_OVERRIDE = 27; // 0x1b
field public static final int KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE = 26; // 0x1a
- field public static final int KEY_VOLTE_PROVISIONING_STATUS = 10; // 0xa
- field public static final int KEY_VOLTE_USER_OPT_IN_STATUS = 30; // 0x1e
- field public static final int KEY_VT_PROVISIONING_STATUS = 11; // 0xb
- field public static final int KEY_WIFI_EPDG_TIMER_SEC = 63; // 0x3f
- field public static final int KEY_WIFI_THRESHOLD_A = 60; // 0x3c
- field public static final int KEY_WIFI_THRESHOLD_B = 61; // 0x3d
- field public static final int PROVISIONING_RESULT_UNKNOWN = -1; // 0xffffffff
field public static final int PROVISIONING_VALUE_DISABLED = 0; // 0x0
field public static final int PROVISIONING_VALUE_ENABLED = 1; // 0x1
- field public static final int SMS_FORMAT_3GPP = 1; // 0x1
- field public static final int SMS_FORMAT_3GPP2 = 0; // 0x0
field public static final String STRING_QUERY_RESULT_ERROR_GENERIC = "STRING_QUERY_RESULT_ERROR_GENERIC";
field public static final String STRING_QUERY_RESULT_ERROR_NOT_READY = "STRING_QUERY_RESULT_ERROR_NOT_READY";
- field public static final int VIDEO_QUALITY_HIGH = 1; // 0x1
- field public static final int VIDEO_QUALITY_LOW = 0; // 0x0
}
public static class ProvisioningManager.Callback {
@@ -12760,56 +12540,6 @@
method public void onProvisioningStringChanged(int, @NonNull String);
}
- public final class RcsContactUceCapability implements android.os.Parcelable {
- method public int describeContents();
- method @NonNull public java.util.List<java.lang.String> getCapableExtensionTags();
- method @NonNull public android.net.Uri getContactUri();
- method @Nullable public android.net.Uri getServiceUri(long);
- method public boolean isCapable(long);
- method public boolean isCapable(@NonNull String);
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field public static final int CAPABILITY_CALL_COMPOSER = 4194304; // 0x400000
- field public static final int CAPABILITY_CHAT_BOT = 67108864; // 0x4000000
- field public static final int CAPABILITY_CHAT_BOT_ROLE = 134217728; // 0x8000000
- field public static final int CAPABILITY_CHAT_SESSION = 2; // 0x2
- field public static final int CAPABILITY_CHAT_SESSION_STORE_FORWARD = 4; // 0x4
- field public static final int CAPABILITY_CHAT_STANDALONE = 1; // 0x1
- field public static final int CAPABILITY_DISCOVERY_VIA_PRESENCE = 4096; // 0x1000
- field public static final int CAPABILITY_FILE_TRANSFER = 8; // 0x8
- field public static final int CAPABILITY_FILE_TRANSFER_HTTP = 64; // 0x40
- field public static final int CAPABILITY_FILE_TRANSFER_SMS = 128; // 0x80
- field public static final int CAPABILITY_FILE_TRANSFER_STORE_FORWARD = 32; // 0x20
- field public static final int CAPABILITY_FILE_TRANSFER_THUMBNAIL = 16; // 0x10
- field public static final int CAPABILITY_GEOLOCATION_PULL = 131072; // 0x20000
- field public static final int CAPABILITY_GEOLOCATION_PULL_FILE_TRANSFER = 262144; // 0x40000
- field public static final int CAPABILITY_GEOLOCATION_PUSH = 32768; // 0x8000
- field public static final int CAPABILITY_GEOLOCATION_PUSH_SMS = 65536; // 0x10000
- field public static final int CAPABILITY_IMAGE_SHARE = 256; // 0x100
- field public static final int CAPABILITY_IP_VIDEO_CALL = 16384; // 0x4000
- field public static final int CAPABILITY_IP_VOICE_CALL = 8192; // 0x2000
- field public static final int CAPABILITY_MMTEL_CALL_COMPOSER = 1073741824; // 0x40000000
- field public static final int CAPABILITY_PLUG_IN = 268435456; // 0x10000000
- field public static final int CAPABILITY_POST_CALL = 8388608; // 0x800000
- field public static final int CAPABILITY_RCS_VIDEO_CALL = 1048576; // 0x100000
- field public static final int CAPABILITY_RCS_VIDEO_ONLY_CALL = 2097152; // 0x200000
- field public static final int CAPABILITY_RCS_VOICE_CALL = 524288; // 0x80000
- field public static final int CAPABILITY_SHARED_MAP = 16777216; // 0x1000000
- field public static final int CAPABILITY_SHARED_SKETCH = 33554432; // 0x2000000
- field public static final int CAPABILITY_SOCIAL_PRESENCE = 2048; // 0x800
- field public static final int CAPABILITY_STANDALONE_CHAT_BOT = 536870912; // 0x20000000
- field public static final int CAPABILITY_VIDEO_SHARE = 1024; // 0x400
- field public static final int CAPABILITY_VIDEO_SHARE_DURING_CS_CALL = 512; // 0x200
- field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.RcsContactUceCapability> CREATOR;
- }
-
- public static class RcsContactUceCapability.Builder {
- ctor public RcsContactUceCapability.Builder(@NonNull android.net.Uri);
- method @NonNull public android.telephony.ims.RcsContactUceCapability.Builder add(long, @NonNull android.net.Uri);
- method @NonNull public android.telephony.ims.RcsContactUceCapability.Builder add(long);
- method @NonNull public android.telephony.ims.RcsContactUceCapability.Builder add(@NonNull String);
- method @NonNull public android.telephony.ims.RcsContactUceCapability build();
- }
-
public class RcsUceAdapter {
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setUceSettingEnabled(boolean) throws android.telephony.ims.ImsException;
}
@@ -13056,24 +12786,12 @@
method public int transact(android.os.Bundle);
method public int updateCallBarring(int, int, String[]);
method public int updateCallBarringForServiceClass(int, int, String[], int);
- method public int updateCallBarringWithPassword(int, int, @Nullable String[], int, @NonNull String);
method public int updateCallForward(int, int, String, int, int);
method public int updateCallWaiting(boolean, int);
method public int updateClip(boolean);
method public int updateClir(int);
method public int updateColp(boolean);
method public int updateColr(int);
- field public static final int CALL_BARRING_ALL = 7; // 0x7
- field public static final int CALL_BARRING_ALL_INCOMING = 1; // 0x1
- field public static final int CALL_BARRING_ALL_OUTGOING = 2; // 0x2
- field public static final int CALL_BARRING_ANONYMOUS_INCOMING = 6; // 0x6
- field public static final int CALL_BARRING_INCOMING_ALL_SERVICES = 9; // 0x9
- field public static final int CALL_BARRING_OUTGOING_ALL_SERVICES = 8; // 0x8
- field public static final int CALL_BARRING_OUTGOING_INTL = 3; // 0x3
- field public static final int CALL_BARRING_OUTGOING_INTL_EXCL_HOME = 4; // 0x4
- field public static final int CALL_BARRING_SPECIFIC_INCOMING_CALLS = 10; // 0xa
- field public static final int CALL_BLOCKING_INCOMING_WHEN_ROAMING = 5; // 0x5
- field public static final int INVALID_RESULT = -1; // 0xffffffff
}
}
@@ -13278,6 +12996,7 @@
method public long getEventTime();
method @Nullable public android.view.autofill.AutofillId getId();
method @Nullable public java.util.List<android.view.autofill.AutofillId> getIds();
+ method @Nullable public android.graphics.Insets getInsets();
method @Nullable public CharSequence getText();
method public int getType();
method @Nullable public android.view.contentcapture.ViewNode getViewNode();
@@ -13288,6 +13007,7 @@
field public static final int TYPE_SESSION_RESUMED = 7; // 0x7
field public static final int TYPE_VIEW_APPEARED = 1; // 0x1
field public static final int TYPE_VIEW_DISAPPEARED = 2; // 0x2
+ field public static final int TYPE_VIEW_INSETS_CHANGED = 9; // 0x9
field public static final int TYPE_VIEW_TEXT_CHANGED = 3; // 0x3
field public static final int TYPE_VIEW_TREE_APPEARED = 5; // 0x5
field public static final int TYPE_VIEW_TREE_APPEARING = 4; // 0x4
diff --git a/api/system-lint-baseline.txt b/api/system-lint-baseline.txt
index 55333cf..10c96a3 100644
--- a/api/system-lint-baseline.txt
+++ b/api/system-lint-baseline.txt
@@ -246,12 +246,6 @@
-ResourceValueFieldName: android.R.array#config_sms_enabled_locking_shift_tables:
- Expected resource name in `android.R.array` to be in the `fooBarBaz` style, was `config_sms_enabled_locking_shift_tables`
-ResourceValueFieldName: android.R.array#config_sms_enabled_single_shift_tables:
- Expected resource name in `android.R.array` to be in the `fooBarBaz` style, was `config_sms_enabled_single_shift_tables`
-
-
SamShouldBeLast: android.accounts.AccountManager#addAccount(String, String, String[], android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler):
SamShouldBeLast: android.accounts.AccountManager#addOnAccountsUpdatedListener(android.accounts.OnAccountsUpdateListener, android.os.Handler, boolean):
diff --git a/api/system-removed.txt b/api/system-removed.txt
index 07b8969..23e2499 100644
--- a/api/system-removed.txt
+++ b/api/system-removed.txt
@@ -11,6 +11,12 @@
public class AppOpsManager {
method @Deprecated @NonNull @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS) public java.util.List<android.app.AppOpsManager.PackageOps> getOpsForPackage(int, @NonNull String, @Nullable int[]);
+ method @Deprecated public void setNotedAppOpsCollector(@Nullable android.app.AppOpsManager.AppOpsCollector);
+ }
+
+ @Deprecated public abstract static class AppOpsManager.AppOpsCollector extends android.app.AppOpsManager.OnOpNotedCallback {
+ ctor public AppOpsManager.AppOpsCollector();
+ method @NonNull public java.util.concurrent.Executor getAsyncNotedExecutor();
}
public class Notification implements android.os.Parcelable {
diff --git a/api/test-current.txt b/api/test-current.txt
index a42710d..a1a652f 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -21,6 +21,7 @@
field public static final String REMOVE_TASKS = "android.permission.REMOVE_TASKS";
field public static final String SUSPEND_APPS = "android.permission.SUSPEND_APPS";
field public static final String TEST_MANAGE_ROLLBACKS = "android.permission.TEST_MANAGE_ROLLBACKS";
+ field public static final String UPGRADE_RUNTIME_PERMISSIONS = "android.permission.UPGRADE_RUNTIME_PERMISSIONS";
field public static final String WRITE_DEVICE_CONFIG = "android.permission.WRITE_DEVICE_CONFIG";
field @Deprecated public static final String WRITE_MEDIA_STORAGE = "android.permission.WRITE_MEDIA_STORAGE";
field public static final String WRITE_OBB = "android.permission.WRITE_OBB";
@@ -82,6 +83,7 @@
method public static void resumeAppSwitches() throws android.os.RemoteException;
method @RequiresPermission(android.Manifest.permission.CHANGE_CONFIGURATION) public void scheduleApplicationInfoChanged(java.util.List<java.lang.String>, int);
method @RequiresPermission("android.permission.MANAGE_USERS") public boolean switchUser(@NonNull android.os.UserHandle);
+ method @RequiresPermission(android.Manifest.permission.CHANGE_CONFIGURATION) public boolean updateMccMncConfiguration(@NonNull String, @NonNull String);
field public static final int PROCESS_CAPABILITY_ALL = 7; // 0x7
field public static final int PROCESS_CAPABILITY_ALL_EXPLICIT = 1; // 0x1
field public static final int PROCESS_CAPABILITY_ALL_IMPLICIT = 6; // 0x6
@@ -262,14 +264,37 @@
field public static final int UID_STATE_TOP = 200; // 0xc8
}
- public static final class AppOpsManager.HistoricalFeatureOps implements android.os.Parcelable {
+ public static final class AppOpsManager.AttributedHistoricalOps implements android.os.Parcelable {
method public int describeContents();
- method @Nullable public String getFeatureId();
method @Nullable public android.app.AppOpsManager.HistoricalOp getOp(@NonNull String);
method @NonNull public android.app.AppOpsManager.HistoricalOp getOpAt(@IntRange(from=0) int);
method @IntRange(from=0) public int getOpCount();
+ method @Nullable public String getTag();
method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalFeatureOps> CREATOR;
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.AttributedHistoricalOps> CREATOR;
+ }
+
+ public static final class AppOpsManager.AttributedOpEntry implements android.os.Parcelable {
+ method public int describeContents();
+ method public long getLastAccessBackgroundTime(int);
+ method public long getLastAccessForegroundTime(int);
+ method public long getLastAccessTime(int);
+ method public long getLastAccessTime(int, int, int);
+ method public long getLastBackgroundDuration(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastBackgroundProxyInfo(int);
+ method public long getLastDuration(int);
+ method public long getLastDuration(int, int, int);
+ method public long getLastForegroundDuration(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastForegroundProxyInfo(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int);
+ method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int, int, int);
+ method public long getLastRejectBackgroundTime(int);
+ method public long getLastRejectForegroundTime(int);
+ method public long getLastRejectTime(int);
+ method public long getLastRejectTime(int, int, int);
+ method public boolean isRunning();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.AttributedOpEntry> CREATOR;
}
public static final class AppOpsManager.HistoricalOp implements android.os.Parcelable {
@@ -310,7 +335,7 @@
public static final class AppOpsManager.HistoricalOpsRequest.Builder {
ctor public AppOpsManager.HistoricalOpsRequest.Builder(long, long);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest build();
- method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setFeatureId(@Nullable String);
+ method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setAttributionTag(@Nullable String);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setFlags(int);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setOpNames(@Nullable java.util.List<java.lang.String>);
method @NonNull public android.app.AppOpsManager.HistoricalOpsRequest.Builder setPackageName(@Nullable String);
@@ -319,9 +344,9 @@
public static final class AppOpsManager.HistoricalPackageOps implements android.os.Parcelable {
method public int describeContents();
- method @IntRange(from=0) public int getFeatureCount();
- method @Nullable public android.app.AppOpsManager.HistoricalFeatureOps getFeatureOps(@NonNull String);
- method @NonNull public android.app.AppOpsManager.HistoricalFeatureOps getFeatureOpsAt(@IntRange(from=0) int);
+ method @Nullable public android.app.AppOpsManager.AttributedHistoricalOps getAttributedOps(@NonNull String);
+ method @NonNull public android.app.AppOpsManager.AttributedHistoricalOps getAttributedOpsAt(@IntRange(from=0) int);
+ method @IntRange(from=0) public int getAttributedOpsCount();
method @Nullable public android.app.AppOpsManager.HistoricalOp getOp(@NonNull String);
method @NonNull public android.app.AppOpsManager.HistoricalOp getOpAt(@IntRange(from=0) int);
method @IntRange(from=0) public int getOpCount();
@@ -342,8 +367,8 @@
public static final class AppOpsManager.OpEntry implements android.os.Parcelable {
method public int describeContents();
+ method @NonNull public java.util.Map<java.lang.String,android.app.AppOpsManager.AttributedOpEntry> getAttributedOpEntries();
method @Deprecated public long getDuration();
- method @NonNull public java.util.Map<java.lang.String,android.app.AppOpsManager.OpFeatureEntry> getFeatures();
method public long getLastAccessBackgroundTime(int);
method public long getLastAccessForegroundTime(int);
method public long getLastAccessTime(int);
@@ -373,36 +398,13 @@
public static final class AppOpsManager.OpEventProxyInfo implements android.os.Parcelable {
method public int describeContents();
- method @Nullable public String getFeatureId();
+ method @Nullable public String getAttributionTag();
method @Nullable public String getPackageName();
method @IntRange(from=0) public int getUid();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.OpEventProxyInfo> CREATOR;
}
- public static final class AppOpsManager.OpFeatureEntry implements android.os.Parcelable {
- method public int describeContents();
- method public long getLastAccessBackgroundTime(int);
- method public long getLastAccessForegroundTime(int);
- method public long getLastAccessTime(int);
- method public long getLastAccessTime(int, int, int);
- method public long getLastBackgroundDuration(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastBackgroundProxyInfo(int);
- method public long getLastDuration(int);
- method public long getLastDuration(int, int, int);
- method public long getLastForegroundDuration(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastForegroundProxyInfo(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int);
- method @Nullable public android.app.AppOpsManager.OpEventProxyInfo getLastProxyInfo(int, int, int);
- method public long getLastRejectBackgroundTime(int);
- method public long getLastRejectForegroundTime(int);
- method public long getLastRejectTime(int);
- method public long getLastRejectTime(int, int, int);
- method public boolean isRunning();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.app.AppOpsManager.OpFeatureEntry> CREATOR;
- }
-
public static final class AppOpsManager.PackageOps implements android.os.Parcelable {
method public int describeContents();
method @NonNull public java.util.List<android.app.AppOpsManager.OpEntry> getOps();
@@ -427,6 +429,7 @@
method public boolean isBlockableSystem();
method public boolean isImportanceLockedByCriticalDeviceFunction();
method public boolean isImportanceLockedByOEM();
+ method public void lockFields(int);
method public void setBlockableSystem(boolean);
method public void setDeleted(boolean);
method public void setFgServiceShown(boolean);
@@ -434,6 +437,7 @@
method public void setImportanceLockedByOEM(boolean);
method public void setImportantConversation(boolean);
method public void setOriginalImportance(int);
+ field public static final int USER_LOCKED_SOUND = 32; // 0x20
}
public final class NotificationChannelGroup implements android.os.Parcelable {
@@ -462,7 +466,7 @@
public final class RuntimeAppOpAccessMessage implements android.os.Parcelable {
ctor public RuntimeAppOpAccessMessage(@IntRange(from=0L) int, @IntRange(from=0L) int, @NonNull String, @Nullable String, @NonNull String, int);
method public int describeContents();
- method @Nullable public String getFeatureId();
+ method @Nullable public String getAttributionTag();
method @NonNull public String getMessage();
method @NonNull public String getOp();
method @NonNull public String getPackageName();
@@ -590,6 +594,27 @@
}
+package android.app.blob {
+
+ public class BlobStoreManager {
+ method @Nullable public android.app.blob.LeaseInfo getLeaseInfo(@NonNull android.app.blob.BlobHandle) throws java.io.IOException;
+ method @NonNull public java.util.List<android.app.blob.BlobHandle> getLeasedBlobs() throws java.io.IOException;
+ method public void waitForIdle(long) throws java.lang.InterruptedException, java.util.concurrent.TimeoutException;
+ }
+
+ public final class LeaseInfo implements android.os.Parcelable {
+ ctor public LeaseInfo(@NonNull String, long, @IdRes int, @Nullable CharSequence);
+ method public int describeContents();
+ method @Nullable public CharSequence getDescription();
+ method @IdRes public int getDescriptionResId();
+ method public long getExpiryTimeMillis();
+ method @NonNull public String getPackageName();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.blob.LeaseInfo> CREATOR;
+ }
+
+}
+
package android.app.prediction {
public final class AppPredictionContext implements android.os.Parcelable {
@@ -784,6 +809,8 @@
}
public abstract class ContentResolver {
+ method @NonNull public static android.net.Uri decodeFromFile(@NonNull java.io.File);
+ method @NonNull public static java.io.File encodeToFile(@NonNull android.net.Uri);
method public static String[] getSyncAdapterPackagesForAuthorityAsUser(String, int);
}
@@ -830,6 +857,7 @@
method @NonNull public android.content.integrity.RuleSet getCurrentRuleSet();
method @NonNull public String getCurrentRuleSetProvider();
method @NonNull public String getCurrentRuleSetVersion();
+ method @NonNull public java.util.List<java.lang.String> getWhitelistedRuleProviders();
method public void updateRuleSet(@NonNull android.content.integrity.RuleSet, @NonNull android.content.IntentSender);
field public static final String EXTRA_STATUS = "android.content.integrity.extra.STATUS";
field public static final int STATUS_FAILURE = 1; // 0x1
@@ -906,6 +934,7 @@
}
public static class PackageInstaller.SessionInfo implements android.os.Parcelable {
+ method public int getAutoRevokePermissionsMode();
method public int getRollbackDataPolicy();
method @NonNull public java.util.Set<java.lang.String> getWhitelistedRestrictedPermissions();
}
@@ -1268,7 +1297,7 @@
public final class LightsManager.LightsSession implements java.lang.AutoCloseable {
method @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_LIGHTS) public void close();
- method @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_LIGHTS) public void setLights(@NonNull android.hardware.lights.LightsRequest);
+ method @RequiresPermission(android.Manifest.permission.CONTROL_DEVICE_LIGHTS) public void requestLights(@NonNull android.hardware.lights.LightsRequest);
}
public final class LightsRequest {
@@ -1727,7 +1756,7 @@
}
public class EthernetManager {
- method @NonNull public android.net.EthernetManager.TetheredInterfaceRequest requestTetheredInterface(@NonNull android.net.EthernetManager.TetheredInterfaceCallback);
+ method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_STACK, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public android.net.EthernetManager.TetheredInterfaceRequest requestTetheredInterface(@NonNull java.util.concurrent.Executor, @NonNull android.net.EthernetManager.TetheredInterfaceCallback);
}
public static interface EthernetManager.TetheredInterfaceCallback {
@@ -1909,6 +1938,9 @@
field public static final int TETHER_ERROR_UNKNOWN_IFACE = 1; // 0x1
field public static final int TETHER_ERROR_UNSUPPORTED = 3; // 0x3
field public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7; // 0x7
+ field public static final int TETHER_HARDWARE_OFFLOAD_FAILED = 2; // 0x2
+ field public static final int TETHER_HARDWARE_OFFLOAD_STARTED = 1; // 0x1
+ field public static final int TETHER_HARDWARE_OFFLOAD_STOPPED = 0; // 0x0
}
public static interface TetheringManager.OnTetheringEntitlementResultListener {
@@ -1925,6 +1957,7 @@
ctor public TetheringManager.TetheringEventCallback();
method public void onClientsChanged(@NonNull java.util.Collection<android.net.TetheredClient>);
method public void onError(@NonNull String, int);
+ method public void onOffloadStatusChanged(int);
method @Deprecated public void onTetherableInterfaceRegexpsChanged(@NonNull android.net.TetheringManager.TetheringInterfaceRegexps);
method public void onTetherableInterfacesChanged(@NonNull java.util.List<java.lang.String>);
method public void onTetheredInterfacesChanged(@NonNull java.util.List<java.lang.String>);
@@ -2797,9 +2830,9 @@
}
public final class PermissionManager {
- method @IntRange(from=0) @RequiresPermission(anyOf={"android.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY", "android.permission.UPGRADE_RUNTIME_PERMISSIONS"}) public int getRuntimePermissionsVersion();
+ method @IntRange(from=0) @RequiresPermission(anyOf={"android.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY", android.Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS}) public int getRuntimePermissionsVersion();
method @NonNull public java.util.List<android.permission.PermissionManager.SplitPermissionInfo> getSplitPermissions();
- method @RequiresPermission(anyOf={"android.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY", "android.permission.UPGRADE_RUNTIME_PERMISSIONS"}) public void setRuntimePermissionsVersion(@IntRange(from=0) int);
+ method @RequiresPermission(anyOf={"android.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY", android.Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS}) public void setRuntimePermissionsVersion(@IntRange(from=0) int);
}
public static final class PermissionManager.SplitPermissionInfo {
@@ -2915,10 +2948,15 @@
method @NonNull public android.provider.DeviceConfig.Properties.Builder setString(@NonNull String, @Nullable String);
}
+ public final class DocumentsContract {
+ method public static boolean isManageMode(@NonNull android.net.Uri);
+ method @NonNull public static android.net.Uri setManageMode(@NonNull android.net.Uri);
+ }
+
public final class MediaStore {
- method @NonNull public static android.net.Uri scanFile(@NonNull android.content.ContentResolver, @NonNull java.io.File);
- method public static void scanVolume(@NonNull android.content.ContentResolver, @NonNull String);
- method public static void waitForIdle(@NonNull android.content.ContentResolver);
+ method @NonNull @WorkerThread public static android.net.Uri scanFile(@NonNull android.content.ContentResolver, @NonNull java.io.File);
+ method @WorkerThread public static void scanVolume(@NonNull android.content.ContentResolver, @NonNull String);
+ method @WorkerThread public static void waitForIdle(@NonNull android.content.ContentResolver);
}
public final class Settings {
@@ -3112,7 +3150,7 @@
public static final class Dataset.Builder {
ctor public Dataset.Builder(@NonNull android.service.autofill.InlinePresentation);
- method @NonNull public android.service.autofill.Dataset.Builder setInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
+ method @NonNull public android.service.autofill.Dataset.Builder setFieldInlinePresentation(@NonNull android.view.autofill.AutofillId, @Nullable android.view.autofill.AutofillValue, @Nullable java.util.regex.Pattern, @NonNull android.service.autofill.InlinePresentation);
}
public final class DateTransformation extends android.service.autofill.InternalTransformation implements android.os.Parcelable android.service.autofill.Transformation {
@@ -3223,10 +3261,10 @@
public static final class FillResponse.Builder {
ctor public FillResponse.Builder();
method @NonNull public android.service.autofill.augmented.FillResponse build();
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setClientState(@Nullable android.os.Bundle);
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@Nullable android.service.autofill.augmented.FillWindow);
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineActions(@Nullable java.util.List<android.service.autofill.InlinePresentation>);
- method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineSuggestions(@Nullable java.util.List<android.service.autofill.Dataset>);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setClientState(@NonNull android.os.Bundle);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setFillWindow(@NonNull android.service.autofill.augmented.FillWindow);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineActions(@NonNull java.util.List<android.service.autofill.InlineAction>);
+ method @NonNull public android.service.autofill.augmented.FillResponse.Builder setInlineSuggestions(@NonNull java.util.List<android.service.autofill.Dataset>);
}
public final class FillWindow implements java.lang.AutoCloseable {
@@ -3397,13 +3435,15 @@
package android.service.quickaccesswallet {
- public interface QuickAccessWalletClient {
+ public interface QuickAccessWalletClient extends java.io.Closeable {
method public void addWalletServiceEventListener(@NonNull android.service.quickaccesswallet.QuickAccessWalletClient.WalletServiceEventListener);
+ method public void addWalletServiceEventListener(@NonNull java.util.concurrent.Executor, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.WalletServiceEventListener);
method @NonNull public static android.service.quickaccesswallet.QuickAccessWalletClient create(@NonNull android.content.Context);
method @Nullable public android.content.Intent createWalletIntent();
method @Nullable public android.content.Intent createWalletSettingsIntent();
method public void disconnect();
method public void getWalletCards(@NonNull android.service.quickaccesswallet.GetWalletCardsRequest, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.OnWalletCardsRetrievedCallback);
+ method public void getWalletCards(@NonNull java.util.concurrent.Executor, @NonNull android.service.quickaccesswallet.GetWalletCardsRequest, @NonNull android.service.quickaccesswallet.QuickAccessWalletClient.OnWalletCardsRetrievedCallback);
method public boolean isWalletFeatureAvailable();
method public boolean isWalletFeatureAvailableWhenDeviceLocked();
method public boolean isWalletServiceAvailable();
@@ -3698,7 +3738,6 @@
public final class SmsManager {
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public int checkSmsShortCodeDestination(String, String);
- method public void sendMultipartTextMessage(@NonNull String, @Nullable String, @NonNull java.util.List<java.lang.String>, @Nullable java.util.List<android.app.PendingIntent>, @Nullable java.util.List<android.app.PendingIntent>, @NonNull String);
field public static final int SMS_CATEGORY_FREE_SHORT_CODE = 1; // 0x1
field public static final int SMS_CATEGORY_NOT_SHORT_CODE = 0; // 0x0
field public static final int SMS_CATEGORY_POSSIBLE_PREMIUM_SHORT_CODE = 3; // 0x3
@@ -3719,20 +3758,22 @@
public class TelephonyManager {
method public int addDevicePolicyOverrideApn(@NonNull android.content.Context, @NonNull android.telephony.data.ApnSetting);
method public int checkCarrierPrivilegesForPackage(String);
+ method @Nullable @RequiresPermission("android.permission.INTERACT_ACROSS_USERS") public android.content.ComponentName getAndUpdateDefaultRespondViaMessageApplication();
method public int getCarrierIdListVersion();
method public java.util.List<java.lang.String> getCarrierPackageNamesForIntent(android.content.Intent);
- method @Nullable public static android.content.ComponentName getDefaultRespondViaMessageApplication(@NonNull android.content.Context, boolean);
+ method @Nullable @RequiresPermission("android.permission.INTERACT_ACROSS_USERS") public android.content.ComponentName getDefaultRespondViaMessageApplication();
method @NonNull public java.util.List<android.telephony.data.ApnSetting> getDevicePolicyOverrideApns(@NonNull android.content.Context);
- method public int getEmergencyNumberDbVersion();
+ method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public int getEmergencyNumberDbVersion();
method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public String getLine1AlphaTag();
method public android.util.Pair<java.lang.Integer,java.lang.Integer> getRadioHalVersion();
method public boolean modifyDevicePolicyOverrideApn(@NonNull android.content.Context, int, @NonNull android.telephony.data.ApnSetting);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void refreshUiccProfile();
+ method @RequiresPermission("android.permission.READ_ACTIVE_EMERGENCY_SESSION") public void resetOtaEmergencyNumberDbFilePath();
method @Deprecated public void setCarrierTestOverride(String, String, String, String, String, String, String);
method public void setCarrierTestOverride(String, String, String, String, String, String, String, String, String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setSystemSelectionChannels(@NonNull java.util.List<android.telephony.RadioAccessSpecifier>, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setSystemSelectionChannels(@NonNull java.util.List<android.telephony.RadioAccessSpecifier>);
- method @RequiresPermission("android.permission.READ_ACTIVE_EMERGENCY_SESSION") public void updateTestOtaEmergencyNumberDbFilePath(@NonNull String);
+ method @RequiresPermission("android.permission.READ_ACTIVE_EMERGENCY_SESSION") public void updateOtaEmergencyNumberDbFilePath(@NonNull android.os.ParcelFileDescriptor);
field public static final int CARRIER_PRIVILEGE_STATUS_ERROR_LOADING_RULES = -2; // 0xfffffffe
field public static final int CARRIER_PRIVILEGE_STATUS_HAS_ACCESS = 1; // 0x1
field public static final int CARRIER_PRIVILEGE_STATUS_NO_ACCESS = 0; // 0x0
@@ -3833,7 +3874,7 @@
method public int getEmergencyServiceCategories();
method @NonNull public java.util.List<java.lang.String> getEmergencyUrns();
method public android.telephony.ims.ImsStreamMediaProfile getMediaProfile();
- method @Nullable public android.os.Bundle getProprietaryCallExtras();
+ method @NonNull public android.os.Bundle getProprietaryCallExtras();
method public int getRestrictCause();
method public int getServiceType();
method public static int getVideoStateFromCallType(int);
@@ -3996,10 +4037,6 @@
field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.ImsExternalCallState> CREATOR;
}
- public class ImsManager {
- field public static final String ACTION_FORBIDDEN_NO_SERVICE_AUTHORIZATION = "com.android.internal.intent.action.ACTION_FORBIDDEN_NO_SERVICE_AUTHORIZATION";
- }
-
public class ImsMmTelManager implements android.telephony.ims.RegistrationManager {
method @Deprecated @NonNull @RequiresPermission(anyOf={"android.permission.READ_PRIVILEGED_PHONE_STATE", android.Manifest.permission.READ_PRECISE_PHONE_STATE}) public static android.telephony.ims.ImsMmTelManager createForSubscriptionId(int);
method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void getFeatureState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>) throws android.telephony.ims.ImsException;
@@ -4261,82 +4298,12 @@
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) @WorkerThread public int setProvisioningStringValue(int, @NonNull String);
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) @WorkerThread public void setRcsProvisioningStatusForCapability(int, boolean);
method @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE") public void unregisterProvisioningChangedCallback(@NonNull android.telephony.ims.ProvisioningManager.Callback);
- field public static final int KEY_1X_EPDG_TIMER_SEC = 64; // 0x40
- field public static final int KEY_1X_THRESHOLD = 59; // 0x3b
- field public static final int KEY_AMR_BANDWIDTH_EFFICIENT_PAYLOAD_TYPE = 50; // 0x32
- field public static final int KEY_AMR_CODEC_MODE_SET_VALUES = 0; // 0x0
- field public static final int KEY_AMR_DEFAULT_ENCODING_MODE = 53; // 0x35
- field public static final int KEY_AMR_OCTET_ALIGNED_PAYLOAD_TYPE = 49; // 0x31
- field public static final int KEY_AMR_WB_BANDWIDTH_EFFICIENT_PAYLOAD_TYPE = 48; // 0x30
- field public static final int KEY_AMR_WB_CODEC_MODE_SET_VALUES = 1; // 0x1
- field public static final int KEY_AMR_WB_OCTET_ALIGNED_PAYLOAD_TYPE = 47; // 0x2f
- field public static final int KEY_DTMF_NB_PAYLOAD_TYPE = 52; // 0x34
- field public static final int KEY_DTMF_WB_PAYLOAD_TYPE = 51; // 0x33
- field public static final int KEY_EAB_PROVISIONING_STATUS = 25; // 0x19
- field public static final int KEY_ENABLE_SILENT_REDIAL = 6; // 0x6
- field public static final int KEY_LOCAL_BREAKOUT_PCSCF_ADDRESS = 31; // 0x1f
- field public static final int KEY_LTE_EPDG_TIMER_SEC = 62; // 0x3e
- field public static final int KEY_LTE_THRESHOLD_1 = 56; // 0x38
- field public static final int KEY_LTE_THRESHOLD_2 = 57; // 0x39
- field public static final int KEY_LTE_THRESHOLD_3 = 58; // 0x3a
- field public static final int KEY_MINIMUM_SIP_SESSION_EXPIRATION_TIMER_SEC = 3; // 0x3
- field public static final int KEY_MOBILE_DATA_ENABLED = 29; // 0x1d
- field public static final int KEY_MULTIENDPOINT_ENABLED = 65; // 0x41
- field public static final int KEY_RCS_AVAILABILITY_CACHE_EXPIRATION_SEC = 19; // 0x13
- field public static final int KEY_RCS_CAPABILITIES_CACHE_EXPIRATION_SEC = 18; // 0x12
- field public static final int KEY_RCS_CAPABILITIES_POLL_INTERVAL_SEC = 20; // 0x14
- field public static final int KEY_RCS_CAPABILITY_DISCOVERY_ENABLED = 17; // 0x11
- field public static final int KEY_RCS_CAPABILITY_POLL_LIST_SUB_EXP_SEC = 23; // 0x17
- field public static final int KEY_RCS_MAX_NUM_ENTRIES_IN_RCL = 22; // 0x16
- field public static final int KEY_RCS_PUBLISH_SOURCE_THROTTLE_MS = 21; // 0x15
- field public static final int KEY_RCS_PUBLISH_TIMER_EXTENDED_SEC = 16; // 0x10
- field public static final int KEY_RCS_PUBLISH_TIMER_SEC = 15; // 0xf
- field public static final int KEY_REGISTRATION_DOMAIN_NAME = 12; // 0xc
- field public static final int KEY_REGISTRATION_RETRY_BASE_TIME_SEC = 33; // 0x21
- field public static final int KEY_REGISTRATION_RETRY_MAX_TIME_SEC = 34; // 0x22
- field public static final int KEY_RTP_SPEECH_END_PORT = 36; // 0x24
- field public static final int KEY_RTP_SPEECH_START_PORT = 35; // 0x23
- field public static final int KEY_RTT_ENABLED = 66; // 0x42
- field public static final int KEY_SIP_ACK_RECEIPT_WAIT_TIME_MS = 43; // 0x2b
- field public static final int KEY_SIP_ACK_RETRANSMIT_WAIT_TIME_MS = 44; // 0x2c
- field public static final int KEY_SIP_INVITE_ACK_WAIT_TIME_MS = 38; // 0x26
- field public static final int KEY_SIP_INVITE_CANCELLATION_TIMER_MS = 4; // 0x4
- field public static final int KEY_SIP_INVITE_REQUEST_TRANSMIT_INTERVAL_MS = 37; // 0x25
- field public static final int KEY_SIP_INVITE_RESPONSE_RETRANSMIT_INTERVAL_MS = 42; // 0x2a
- field public static final int KEY_SIP_INVITE_RESPONSE_RETRANSMIT_WAIT_TIME_MS = 39; // 0x27
- field public static final int KEY_SIP_KEEP_ALIVE_ENABLED = 32; // 0x20
- field public static final int KEY_SIP_NON_INVITE_REQUEST_RETRANSMISSION_WAIT_TIME_MS = 45; // 0x2d
- field public static final int KEY_SIP_NON_INVITE_REQUEST_RETRANSMIT_INTERVAL_MS = 40; // 0x28
- field public static final int KEY_SIP_NON_INVITE_RESPONSE_RETRANSMISSION_WAIT_TIME_MS = 46; // 0x2e
- field public static final int KEY_SIP_NON_INVITE_TRANSACTION_TIMEOUT_TIMER_MS = 41; // 0x29
- field public static final int KEY_SIP_SESSION_TIMER_SEC = 2; // 0x2
- field public static final int KEY_SMS_FORMAT = 13; // 0xd
- field public static final int KEY_SMS_OVER_IP_ENABLED = 14; // 0xe
- field public static final int KEY_SMS_PUBLIC_SERVICE_IDENTITY = 54; // 0x36
- field public static final int KEY_T1_TIMER_VALUE_MS = 7; // 0x7
- field public static final int KEY_T2_TIMER_VALUE_MS = 8; // 0x8
- field public static final int KEY_TF_TIMER_VALUE_MS = 9; // 0x9
- field public static final int KEY_TRANSITION_TO_LTE_DELAY_MS = 5; // 0x5
- field public static final int KEY_USE_GZIP_FOR_LIST_SUBSCRIPTION = 24; // 0x18
- field public static final int KEY_VIDEO_QUALITY = 55; // 0x37
- field public static final int KEY_VOICE_OVER_WIFI_ENABLED_OVERRIDE = 28; // 0x1c
field public static final int KEY_VOICE_OVER_WIFI_MODE_OVERRIDE = 27; // 0x1b
field public static final int KEY_VOICE_OVER_WIFI_ROAMING_ENABLED_OVERRIDE = 26; // 0x1a
- field public static final int KEY_VOLTE_PROVISIONING_STATUS = 10; // 0xa
- field public static final int KEY_VOLTE_USER_OPT_IN_STATUS = 30; // 0x1e
- field public static final int KEY_VT_PROVISIONING_STATUS = 11; // 0xb
- field public static final int KEY_WIFI_EPDG_TIMER_SEC = 63; // 0x3f
- field public static final int KEY_WIFI_THRESHOLD_A = 60; // 0x3c
- field public static final int KEY_WIFI_THRESHOLD_B = 61; // 0x3d
- field public static final int PROVISIONING_RESULT_UNKNOWN = -1; // 0xffffffff
field public static final int PROVISIONING_VALUE_DISABLED = 0; // 0x0
field public static final int PROVISIONING_VALUE_ENABLED = 1; // 0x1
- field public static final int SMS_FORMAT_3GPP = 1; // 0x1
- field public static final int SMS_FORMAT_3GPP2 = 0; // 0x0
field public static final String STRING_QUERY_RESULT_ERROR_GENERIC = "STRING_QUERY_RESULT_ERROR_GENERIC";
field public static final String STRING_QUERY_RESULT_ERROR_NOT_READY = "STRING_QUERY_RESULT_ERROR_NOT_READY";
- field public static final int VIDEO_QUALITY_HIGH = 1; // 0x1
- field public static final int VIDEO_QUALITY_LOW = 0; // 0x0
}
public static class ProvisioningManager.Callback {
@@ -4345,56 +4312,6 @@
method public void onProvisioningStringChanged(int, @NonNull String);
}
- public final class RcsContactUceCapability implements android.os.Parcelable {
- method public int describeContents();
- method @NonNull public java.util.List<java.lang.String> getCapableExtensionTags();
- method @NonNull public android.net.Uri getContactUri();
- method @Nullable public android.net.Uri getServiceUri(long);
- method public boolean isCapable(long);
- method public boolean isCapable(@NonNull String);
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field public static final int CAPABILITY_CALL_COMPOSER = 4194304; // 0x400000
- field public static final int CAPABILITY_CHAT_BOT = 67108864; // 0x4000000
- field public static final int CAPABILITY_CHAT_BOT_ROLE = 134217728; // 0x8000000
- field public static final int CAPABILITY_CHAT_SESSION = 2; // 0x2
- field public static final int CAPABILITY_CHAT_SESSION_STORE_FORWARD = 4; // 0x4
- field public static final int CAPABILITY_CHAT_STANDALONE = 1; // 0x1
- field public static final int CAPABILITY_DISCOVERY_VIA_PRESENCE = 4096; // 0x1000
- field public static final int CAPABILITY_FILE_TRANSFER = 8; // 0x8
- field public static final int CAPABILITY_FILE_TRANSFER_HTTP = 64; // 0x40
- field public static final int CAPABILITY_FILE_TRANSFER_SMS = 128; // 0x80
- field public static final int CAPABILITY_FILE_TRANSFER_STORE_FORWARD = 32; // 0x20
- field public static final int CAPABILITY_FILE_TRANSFER_THUMBNAIL = 16; // 0x10
- field public static final int CAPABILITY_GEOLOCATION_PULL = 131072; // 0x20000
- field public static final int CAPABILITY_GEOLOCATION_PULL_FILE_TRANSFER = 262144; // 0x40000
- field public static final int CAPABILITY_GEOLOCATION_PUSH = 32768; // 0x8000
- field public static final int CAPABILITY_GEOLOCATION_PUSH_SMS = 65536; // 0x10000
- field public static final int CAPABILITY_IMAGE_SHARE = 256; // 0x100
- field public static final int CAPABILITY_IP_VIDEO_CALL = 16384; // 0x4000
- field public static final int CAPABILITY_IP_VOICE_CALL = 8192; // 0x2000
- field public static final int CAPABILITY_MMTEL_CALL_COMPOSER = 1073741824; // 0x40000000
- field public static final int CAPABILITY_PLUG_IN = 268435456; // 0x10000000
- field public static final int CAPABILITY_POST_CALL = 8388608; // 0x800000
- field public static final int CAPABILITY_RCS_VIDEO_CALL = 1048576; // 0x100000
- field public static final int CAPABILITY_RCS_VIDEO_ONLY_CALL = 2097152; // 0x200000
- field public static final int CAPABILITY_RCS_VOICE_CALL = 524288; // 0x80000
- field public static final int CAPABILITY_SHARED_MAP = 16777216; // 0x1000000
- field public static final int CAPABILITY_SHARED_SKETCH = 33554432; // 0x2000000
- field public static final int CAPABILITY_SOCIAL_PRESENCE = 2048; // 0x800
- field public static final int CAPABILITY_STANDALONE_CHAT_BOT = 536870912; // 0x20000000
- field public static final int CAPABILITY_VIDEO_SHARE = 1024; // 0x400
- field public static final int CAPABILITY_VIDEO_SHARE_DURING_CS_CALL = 512; // 0x200
- field @NonNull public static final android.os.Parcelable.Creator<android.telephony.ims.RcsContactUceCapability> CREATOR;
- }
-
- public static class RcsContactUceCapability.Builder {
- ctor public RcsContactUceCapability.Builder(@NonNull android.net.Uri);
- method @NonNull public android.telephony.ims.RcsContactUceCapability.Builder add(long, @NonNull android.net.Uri);
- method @NonNull public android.telephony.ims.RcsContactUceCapability.Builder add(long);
- method @NonNull public android.telephony.ims.RcsContactUceCapability.Builder add(@NonNull String);
- method @NonNull public android.telephony.ims.RcsContactUceCapability build();
- }
-
public class RcsUceAdapter {
method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setUceSettingEnabled(boolean) throws android.telephony.ims.ImsException;
}
@@ -4641,24 +4558,12 @@
method public int transact(android.os.Bundle);
method public int updateCallBarring(int, int, String[]);
method public int updateCallBarringForServiceClass(int, int, String[], int);
- method public int updateCallBarringWithPassword(int, int, @Nullable String[], int, @NonNull String);
method public int updateCallForward(int, int, String, int, int);
method public int updateCallWaiting(boolean, int);
method public int updateClip(boolean);
method public int updateClir(int);
method public int updateColp(boolean);
method public int updateColr(int);
- field public static final int CALL_BARRING_ALL = 7; // 0x7
- field public static final int CALL_BARRING_ALL_INCOMING = 1; // 0x1
- field public static final int CALL_BARRING_ALL_OUTGOING = 2; // 0x2
- field public static final int CALL_BARRING_ANONYMOUS_INCOMING = 6; // 0x6
- field public static final int CALL_BARRING_INCOMING_ALL_SERVICES = 9; // 0x9
- field public static final int CALL_BARRING_OUTGOING_ALL_SERVICES = 8; // 0x8
- field public static final int CALL_BARRING_OUTGOING_INTL = 3; // 0x3
- field public static final int CALL_BARRING_OUTGOING_INTL_EXCL_HOME = 4; // 0x4
- field public static final int CALL_BARRING_SPECIFIC_INCOMING_CALLS = 10; // 0xa
- field public static final int CALL_BLOCKING_INCOMING_WHEN_ROAMING = 5; // 0x5
- field public static final int INVALID_RESULT = -1; // 0xffffffff
}
}
@@ -4930,8 +4835,8 @@
}
public class SurfaceControlViewHost {
- method public void addView(@NonNull android.view.View, android.view.WindowManager.LayoutParams);
method public void relayout(android.view.WindowManager.LayoutParams);
+ method public void setView(@NonNull android.view.View, @NonNull android.view.WindowManager.LayoutParams);
}
@UiThread public class View implements android.view.accessibility.AccessibilityEventSource android.graphics.drawable.Drawable.Callback android.view.KeyEvent.Callback {
@@ -4947,7 +4852,7 @@
method public void resetRtlProperties();
method public boolean restoreFocusInCluster(int);
method public boolean restoreFocusNotInCluster();
- method public void setAutofilled(boolean);
+ method public void setAutofilled(boolean, boolean);
method public final void setFocusedInCluster();
method public void setIsRootNamespace(boolean);
method public final void setShowingLayoutBounds(boolean);
@@ -5061,6 +4966,7 @@
method public long getEventTime();
method @Nullable public android.view.autofill.AutofillId getId();
method @Nullable public java.util.List<android.view.autofill.AutofillId> getIds();
+ method @Nullable public android.graphics.Insets getInsets();
method @Nullable public CharSequence getText();
method public int getType();
method @Nullable public android.view.contentcapture.ViewNode getViewNode();
@@ -5071,6 +4977,7 @@
field public static final int TYPE_SESSION_RESUMED = 7; // 0x7
field public static final int TYPE_VIEW_APPEARED = 1; // 0x1
field public static final int TYPE_VIEW_DISAPPEARED = 2; // 0x2
+ field public static final int TYPE_VIEW_INSETS_CHANGED = 9; // 0x9
field public static final int TYPE_VIEW_TEXT_CHANGED = 3; // 0x3
field public static final int TYPE_VIEW_TREE_APPEARED = 5; // 0x5
field public static final int TYPE_VIEW_TREE_APPEARING = 4; // 0x4
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.cpp b/cmds/idmap2/idmap2d/Idmap2Service.cpp
index f84e4b5..8f5e49d 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.cpp
+++ b/cmds/idmap2/idmap2d/Idmap2Service.cpp
@@ -113,7 +113,7 @@
Status Idmap2Service::createIdmap(const std::string& target_apk_path,
const std::string& overlay_apk_path, int32_t fulfilled_policies,
bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
- std::unique_ptr<std::string>* _aidl_return) {
+ aidl::nullable<std::string>* _aidl_return) {
assert(_aidl_return);
SYSTRACE << "Idmap2Service::createIdmap " << target_apk_path << " " << overlay_apk_path;
_aidl_return->reset(nullptr);
@@ -155,7 +155,7 @@
return error("failed to write to idmap path " + idmap_path);
}
- *_aidl_return = std::make_unique<std::string>(idmap_path);
+ *_aidl_return = aidl::make_nullable<std::string>(idmap_path);
return ok();
}
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.h b/cmds/idmap2/idmap2d/Idmap2Service.h
index 94d2af4..b6f5136 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.h
+++ b/cmds/idmap2/idmap2d/Idmap2Service.h
@@ -19,9 +19,7 @@
#include <android-base/unique_fd.h>
#include <binder/BinderService.h>
-
-#include <memory>
-#include <string>
+#include <binder/Nullable.h>
#include "android/os/BnIdmap2.h"
@@ -46,7 +44,7 @@
binder::Status createIdmap(const std::string& target_apk_path,
const std::string& overlay_apk_path, int32_t fulfilled_policies,
bool enforce_overlayable, int32_t user_id,
- std::unique_ptr<std::string>* _aidl_return) override;
+ aidl::nullable<std::string>* _aidl_return) override;
};
} // namespace android::os
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index bd6ca47..33bfe51 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -113,8 +113,8 @@
"libbase",
"libcutils",
"libprotoutil",
- "libstatslog",
"libstatsmetadata",
+ "libstatslog_statsd",
"libsysutils",
"libutils",
],
@@ -171,6 +171,37 @@
],
}
+genrule {
+ name: "statslog_statsd.h",
+ tools: ["stats-log-api-gen"],
+ cmd: "$(location stats-log-api-gen) --header $(genDir)/statslog_statsd.h --module statsd --namespace android,os,statsd,util",
+ out: [
+ "statslog_statsd.h",
+ ],
+}
+
+genrule {
+ name: "statslog_statsd.cpp",
+ tools: ["stats-log-api-gen"],
+ cmd: "$(location stats-log-api-gen) --cpp $(genDir)/statslog_statsd.cpp --module statsd --namespace android,os,statsd,util --importHeader statslog_statsd.h",
+ out: [
+ "statslog_statsd.cpp",
+ ],
+}
+
+cc_library_static {
+ name: "libstatslog_statsd",
+ generated_sources: ["statslog_statsd.cpp"],
+ generated_headers: ["statslog_statsd.h"],
+ export_generated_headers: ["statslog_statsd.h"],
+ apex_available: [
+ "com.android.os.statsd",
+ "test_com.android.os.statsd",
+ ],
+ shared_libs: [
+ "libstatssocket",
+ ]
+}
// =========
// statsd
@@ -300,6 +331,7 @@
static_libs: [
"libgmock",
"libplatformprotos",
+ "libstatslog", //TODO(b/150976524): remove this when the tests no longer hardcode atoms.
"libstatssocket_private",
],
diff --git a/cmds/statsd/src/HashableDimensionKey.cpp b/cmds/statsd/src/HashableDimensionKey.cpp
index d95d594..23d8f59 100644
--- a/cmds/statsd/src/HashableDimensionKey.cpp
+++ b/cmds/statsd/src/HashableDimensionKey.cpp
@@ -40,53 +40,62 @@
* Recursive helper function that populates a parent StatsDimensionsValueParcel
* with children StatsDimensionsValueParcels.
*
+ * \param parent parcel that will be populated with children
+ * \param childDepth depth of children FieldValues
+ * \param childPrefix expected FieldValue prefix of children
* \param dims vector of FieldValues stored by HashableDimensionKey
- * \param index positions in dims vector to start reading children from
- * \param depth level of parent parcel in the full StatsDimensionsValueParcel
- * tree
+ * \param index position in dims to start reading children from
*/
-static void populateStatsDimensionsValueParcelChildren(StatsDimensionsValueParcel &parentParcel,
- const vector<FieldValue>& dims, size_t& index,
- int depth, int prefix) {
+static void populateStatsDimensionsValueParcelChildren(StatsDimensionsValueParcel& parent,
+ int childDepth, int childPrefix,
+ const vector<FieldValue>& dims,
+ size_t& index) {
+ if (childDepth > 2) {
+ ALOGE("Depth > 2 not supported by StatsDimensionsValueParcel.");
+ return;
+ }
+
while (index < dims.size()) {
const FieldValue& dim = dims[index];
int fieldDepth = dim.mField.getDepth();
- int fieldPrefix = dim.mField.getPrefix(depth);
- StatsDimensionsValueParcel childParcel;
- childParcel.field = dim.mField.getPosAtDepth(depth);
- if (depth > 2) {
- ALOGE("Depth > 2 not supported by StatsDimensionsValueParcel.");
- return;
- }
- if (depth == fieldDepth && prefix == fieldPrefix) {
+ int fieldPrefix = dim.mField.getPrefix(childDepth);
+
+ StatsDimensionsValueParcel child;
+ child.field = dim.mField.getPosAtDepth(childDepth);
+
+ if (fieldDepth == childDepth && fieldPrefix == childPrefix) {
switch (dim.mValue.getType()) {
case INT:
- childParcel.valueType = STATS_DIMENSIONS_VALUE_INT_TYPE;
- childParcel.intValue = dim.mValue.int_value;
+ child.valueType = STATS_DIMENSIONS_VALUE_INT_TYPE;
+ child.intValue = dim.mValue.int_value;
break;
case LONG:
- childParcel.valueType = STATS_DIMENSIONS_VALUE_LONG_TYPE;
- childParcel.longValue = dim.mValue.long_value;
+ child.valueType = STATS_DIMENSIONS_VALUE_LONG_TYPE;
+ child.longValue = dim.mValue.long_value;
break;
case FLOAT:
- childParcel.valueType = STATS_DIMENSIONS_VALUE_FLOAT_TYPE;
- childParcel.floatValue = dim.mValue.float_value;
+ child.valueType = STATS_DIMENSIONS_VALUE_FLOAT_TYPE;
+ child.floatValue = dim.mValue.float_value;
break;
case STRING:
- childParcel.valueType = STATS_DIMENSIONS_VALUE_STRING_TYPE;
- childParcel.stringValue = dim.mValue.str_value;
+ child.valueType = STATS_DIMENSIONS_VALUE_STRING_TYPE;
+ child.stringValue = dim.mValue.str_value;
break;
default:
ALOGE("Encountered FieldValue with unsupported value type.");
break;
}
index++;
- parentParcel.tupleValue.push_back(childParcel);
- } else if (fieldDepth > depth && fieldPrefix == prefix) {
- childParcel.valueType = STATS_DIMENSIONS_VALUE_TUPLE_TYPE;
- populateStatsDimensionsValueParcelChildren(childParcel, dims, index, depth + 1,
- dim.mField.getPrefix(depth + 1));
- parentParcel.tupleValue.push_back(childParcel);
+ parent.tupleValue.push_back(child);
+ } else if (fieldDepth > childDepth && fieldPrefix == childPrefix) {
+ // This FieldValue is not a child of the current parent, but it is
+ // an indirect descendant. Thus, create a direct child of TUPLE_TYPE
+ // and recurse to parcel the indirect descendants.
+ child.valueType = STATS_DIMENSIONS_VALUE_TUPLE_TYPE;
+ populateStatsDimensionsValueParcelChildren(child, childDepth + 1,
+ dim.mField.getPrefix(childDepth + 1), dims,
+ index);
+ parent.tupleValue.push_back(child);
} else {
return;
}
@@ -94,17 +103,21 @@
}
StatsDimensionsValueParcel HashableDimensionKey::toStatsDimensionsValueParcel() const {
- StatsDimensionsValueParcel parcel;
+ StatsDimensionsValueParcel root;
if (mValues.size() == 0) {
- return parcel;
+ return root;
}
- parcel.field = mValues[0].mField.getTag();
- parcel.valueType = STATS_DIMENSIONS_VALUE_TUPLE_TYPE;
+ root.field = mValues[0].mField.getTag();
+ root.valueType = STATS_DIMENSIONS_VALUE_TUPLE_TYPE;
+ // Children of the root correspond to top-level (depth = 0) FieldValues.
+ int childDepth = 0;
+ int childPrefix = 0;
size_t index = 0;
- populateStatsDimensionsValueParcelChildren(parcel, mValues, index, /*depth=*/0, /*prefix=*/0);
- return parcel;
+ populateStatsDimensionsValueParcelChildren(root, childDepth, childPrefix, mValues, index);
+
+ return root;
}
android::hash_t hashDimension(const HashableDimensionKey& value) {
diff --git a/cmds/statsd/src/StatsLogProcessor.cpp b/cmds/statsd/src/StatsLogProcessor.cpp
index 649c004..69b9fc7 100644
--- a/cmds/statsd/src/StatsLogProcessor.cpp
+++ b/cmds/statsd/src/StatsLogProcessor.cpp
@@ -34,7 +34,7 @@
#include "state/StateManager.h"
#include "stats_log_util.h"
#include "stats_util.h"
-#include "statslog.h"
+#include "statslog_statsd.h"
#include "storage/StorageManager.h"
using namespace android;
@@ -287,17 +287,17 @@
int64_t firstId = trainInfo->experimentIds.at(0);
auto& ids = trainInfo->experimentIds;
switch (trainInfo->status) {
- case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
+ case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
if (find(ids.begin(), ids.end(), firstId + 1) == ids.end()) {
ids.push_back(firstId + 1);
}
break;
- case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
+ case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
if (find(ids.begin(), ids.end(), firstId + 2) == ids.end()) {
ids.push_back(firstId + 2);
}
break;
- case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
+ case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
if (find(ids.begin(), ids.end(), firstId + 3) == ids.end()) {
ids.push_back(firstId + 3);
}
@@ -366,13 +366,13 @@
int64_t firstId = trainInfoOnDisk.experimentIds[0];
auto& ids = trainInfoOnDisk.experimentIds;
switch (rollbackTypeIn) {
- case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
+ case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
if (find(ids.begin(), ids.end(), firstId + 4) == ids.end()) {
ids.push_back(firstId + 4);
}
StorageManager::writeTrainInfo(trainInfoOnDisk);
break;
- case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
+ case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
if (find(ids.begin(), ids.end(), firstId + 5) == ids.end()) {
ids.push_back(firstId + 5);
}
@@ -405,13 +405,13 @@
// Hard-coded logic to update train info on disk and fill in any information
// this log event may be missing.
- if (event->GetTagId() == android::util::BINARY_PUSH_STATE_CHANGED) {
+ if (event->GetTagId() == android::os::statsd::util::BINARY_PUSH_STATE_CHANGED) {
onBinaryPushStateChangedEventLocked(event);
}
// Hard-coded logic to update experiment ids on disk for certain rollback
// types and fill the rollback atom with experiment ids
- if (event->GetTagId() == android::util::WATCHDOG_ROLLBACK_OCCURRED) {
+ if (event->GetTagId() == android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED) {
onWatchdogRollbackOccurredLocked(event);
}
@@ -429,7 +429,7 @@
// Hard-coded logic to update the isolated uid's in the uid-map.
// The field numbers need to be currently updated by hand with atoms.proto
- if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
+ if (event->GetTagId() == android::os::statsd::util::ISOLATED_UID_CHANGED) {
onIsolatedUidChangedEventLocked(*event);
}
@@ -446,7 +446,7 @@
}
- if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
+ if (event->GetTagId() != android::os::statsd::util::ISOLATED_UID_CHANGED) {
// Map the isolated uid to host uid if necessary.
mapIsolatedUidToHostUidIfNecessaryLocked(event);
}
diff --git a/cmds/statsd/src/StatsService.cpp b/cmds/statsd/src/StatsService.cpp
index 7ab6c71..07579bb 100644
--- a/cmds/statsd/src/StatsService.cpp
+++ b/cmds/statsd/src/StatsService.cpp
@@ -32,7 +32,7 @@
#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
#include <private/android_filesystem_config.h>
-#include <statslog.h>
+#include <statslog_statsd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/system_properties.h>
@@ -767,7 +767,8 @@
}
if (good) {
dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
- android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
+ android::os::statsd::util::stats_write(
+ android::os::statsd::util::APP_BREADCRUMB_REPORTED, uid, label, state);
} else {
print_cmd_help(out);
return UNKNOWN_ERROR;
@@ -930,8 +931,6 @@
ENFORCE_UID(AID_SYSTEM);
VLOG("StatsService::informOnePackage was called");
- // TODO(b/149254662): This is gross. We should consider changing statsd
- // internals to use std::string.
String16 utf16App = String16(app.c_str());
String16 utf16VersionString = String16(versionString.c_str());
String16 utf16Installer = String16(installer.c_str());
@@ -1190,19 +1189,20 @@
Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
// Permission check not necessary as it's meant for applications to write to
// statsd.
- android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
+ android::os::statsd::util::stats_write(android::os::statsd::util::APP_BREADCRUMB_REPORTED,
(int32_t) AIBinder_getCallingUid(), label,
state);
return Status::ok();
}
-Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
- int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
- const shared_ptr<IPullAtomCallback>& pullerCallback) {
+Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownMillis,
+ int64_t timeoutMillis,
+ const std::vector<int32_t>& additiveFields,
+ const shared_ptr<IPullAtomCallback>& pullerCallback) {
ENFORCE_UID(AID_SYSTEM);
-
VLOG("StatsService::registerPullAtomCallback called.");
- mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
+ mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
+ MillisToNano(timeoutMillis), additiveFields,
pullerCallback);
return Status::ok();
}
diff --git a/cmds/statsd/src/StatsService.h b/cmds/statsd/src/StatsService.h
index e6723c8..c256e1f 100644
--- a/cmds/statsd/src/StatsService.h
+++ b/cmds/statsd/src/StatsService.h
@@ -167,8 +167,9 @@
/**
* Binder call to register a callback function for a pulled atom.
*/
- virtual Status registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
- int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
+ virtual Status registerPullAtomCallback(
+ int32_t uid, int32_t atomTag, int64_t coolDownMillis, int64_t timeoutMillis,
+ const std::vector<int32_t>& additiveFields,
const shared_ptr<IPullAtomCallback>& pullerCallback) override;
/**
diff --git a/cmds/statsd/src/anomaly/AlarmMonitor.cpp b/cmds/statsd/src/anomaly/AlarmMonitor.cpp
index 02291181..b632d04 100644
--- a/cmds/statsd/src/anomaly/AlarmMonitor.cpp
+++ b/cmds/statsd/src/anomaly/AlarmMonitor.cpp
@@ -38,8 +38,6 @@
void AlarmMonitor::setStatsCompanionService(
shared_ptr<IStatsCompanionService> statsCompanionService) {
std::lock_guard<std::mutex> lock(mLock);
- // TODO(b/149254662): determine if tmpForLock is needed now that we have moved
- // from sp to shared_ptr
shared_ptr<IStatsCompanionService> tmpForLock = mStatsCompanionService;
mStatsCompanionService = statsCompanionService;
if (statsCompanionService == nullptr) {
diff --git a/cmds/statsd/src/anomaly/AlarmTracker.cpp b/cmds/statsd/src/anomaly/AlarmTracker.cpp
index 019a9f7..5722f92 100644
--- a/cmds/statsd/src/anomaly/AlarmTracker.cpp
+++ b/cmds/statsd/src/anomaly/AlarmTracker.cpp
@@ -23,7 +23,6 @@
#include "stats_util.h"
#include "storage/StorageManager.h"
-#include <statslog.h>
#include <time.h>
namespace android {
diff --git a/cmds/statsd/src/anomaly/AnomalyTracker.cpp b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
index 7ace44e..a21abbf 100644
--- a/cmds/statsd/src/anomaly/AnomalyTracker.cpp
+++ b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
@@ -25,7 +25,7 @@
#include "subscriber/SubscriberReporter.h"
#include <inttypes.h>
-#include <statslog.h>
+#include <statslog_statsd.h>
#include <time.h>
namespace android {
@@ -235,8 +235,8 @@
StatsdStats::getInstance().noteAnomalyDeclared(mConfigKey, mAlert.id());
// TODO(b/110564268): This should also take in the const MetricDimensionKey& key?
- android::util::stats_write(android::util::ANOMALY_DETECTED, mConfigKey.GetUid(),
- mConfigKey.GetId(), mAlert.id());
+ util::stats_write(util::ANOMALY_DETECTED, mConfigKey.GetUid(),
+ mConfigKey.GetId(), mAlert.id());
}
void AnomalyTracker::detectAndDeclareAnomaly(const int64_t& timestampNs,
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index e58e7bc..713e923 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -122,10 +122,10 @@
SettingChanged setting_changed = 41 [(module) = "framework"];
ActivityForegroundStateChanged activity_foreground_state_changed =
42 [(module) = "framework"];
- IsolatedUidChanged isolated_uid_changed = 43 [(module) = "framework"];
+ IsolatedUidChanged isolated_uid_changed = 43 [(module) = "framework", (module) = "statsd"];
PacketWakeupOccurred packet_wakeup_occurred = 44 [(module) = "framework"];
WallClockTimeShifted wall_clock_time_shifted = 45 [(module) = "framework"];
- AnomalyDetected anomaly_detected = 46;
+ AnomalyDetected anomaly_detected = 46 [(module) = "statsd"];
AppBreadcrumbReported app_breadcrumb_reported =
47 [(allow_from_any_uid) = true, (module) = "statsd"];
AppStartOccurred app_start_occurred = 48 [(module) = "framework"];
@@ -138,7 +138,7 @@
AppStartMemoryStateCaptured app_start_memory_state_captured = 55 [(module) = "framework"];
ShutdownSequenceReported shutdown_sequence_reported = 56 [(module) = "framework"];
BootSequenceReported boot_sequence_reported = 57;
- DaveyOccurred davey_occurred = 58 [(allow_from_any_uid) = true];
+ DaveyOccurred davey_occurred = 58 [(allow_from_any_uid) = true, (module) = "statsd"];
OverlayStateChanged overlay_state_changed = 59 [(module) = "framework"];
ForegroundServiceStateChanged foreground_service_state_changed
= 60 [(module) = "framework"];
@@ -166,7 +166,7 @@
LowMemReported low_mem_reported = 81 [(module) = "framework"];
GenericAtom generic_atom = 82;
KeyValuePairsAtom key_value_pairs_atom =
- 83 [(allow_from_any_uid) = true, (module) = "framework"];
+ 83 [(allow_from_any_uid) = true, (module) = "framework", (module) = "statsd"];
VibratorStateChanged vibrator_state_changed = 84 [(module) = "framework"];
DeferredJobStatsReported deferred_job_stats_reported = 85 [(module) = "framework"];
ThermalThrottlingStateChanged thermal_throttling = 86 [deprecated=true];
@@ -242,7 +242,8 @@
AdbConnectionChanged adb_connection_changed = 144 [(module) = "framework"];
SpeechDspStatReported speech_dsp_stat_reported = 145;
UsbContaminantReported usb_contaminant_reported = 146 [(module) = "framework"];
- WatchdogRollbackOccurred watchdog_rollback_occurred = 147 [(module) = "framework"];
+ WatchdogRollbackOccurred watchdog_rollback_occurred =
+ 147 [(module) = "framework", (module) = "statsd"];
BiometricSystemHealthIssueDetected biometric_system_health_issue_detected =
148 [(module) = "framework"];
BubbleUIChanged bubble_ui_changed = 149 [(module) = "sysui"];
@@ -401,7 +402,7 @@
}
// Pulled events will start at field 10000.
- // Next: 10076
+ // Next: 10080
oneof pulled {
WifiBytesTransfer wifi_bytes_transfer = 10000 [(module) = "framework"];
WifiBytesTransferByFgBg wifi_bytes_transfer_by_fg_bg = 10001 [(module) = "framework"];
@@ -412,7 +413,8 @@
SubsystemSleepState subsystem_sleep_state = 10005;
CpuTimePerFreq cpu_time_per_freq = 10008 [(module) = "framework"];
CpuTimePerUid cpu_time_per_uid = 10009 [(module) = "framework"];
- CpuTimePerUidFreq cpu_time_per_uid_freq = 10010 [(module) = "framework"];
+ CpuTimePerUidFreq cpu_time_per_uid_freq =
+ 10010 [(module) = "framework", (module) = "statsd"];
WifiActivityInfo wifi_activity_info = 10011 [(module) = "framework"];
ModemActivityInfo modem_activity_info = 10012 [(module) = "framework"];
BluetoothActivityInfo bluetooth_activity_info = 10007 [(module) = "framework"];
@@ -425,9 +427,9 @@
RemainingBatteryCapacity remaining_battery_capacity = 10019 [(module) = "framework"];
FullBatteryCapacity full_battery_capacity = 10020 [(module) = "framework"];
Temperature temperature = 10021 [(module) = "framework"];
- BinderCalls binder_calls = 10022 [(module) = "framework"];
+ BinderCalls binder_calls = 10022 [(module) = "framework", (module) = "statsd"];
BinderCallsExceptions binder_calls_exceptions = 10023 [(module) = "framework"];
- LooperStats looper_stats = 10024 [(module) = "framework"];
+ LooperStats looper_stats = 10024 [(module) = "framework", (module) = "statsd"];
DiskStats disk_stats = 10025 [(module) = "framework"];
DirectoryUsage directory_usage = 10026 [(module) = "framework"];
AppSize app_size = 10027 [(module) = "framework"];
@@ -455,7 +457,7 @@
NumFacesEnrolled num_faces_enrolled = 10048 [(module) = "framework"];
RoleHolder role_holder = 10049 [(module) = "framework"];
DangerousPermissionState dangerous_permission_state = 10050 [(module) = "framework"];
- TrainInfo train_info = 10051;
+ TrainInfo train_info = 10051 [(module) = "statsd"];
TimeZoneDataInfo time_zone_data_info = 10052 [(module) = "framework"];
ExternalStorageInfo external_storage_info = 10053 [(module) = "framework"];
GpuStatsGlobalInfo gpu_stats_global_info = 10054;
@@ -483,7 +485,11 @@
PackageNotificationChannelGroupPreferences package_notification_channel_group_preferences =
10073 [(module) = "framework"];
GnssStats gnss_stats = 10074 [(module) = "framework"];
- AppFeaturesOps app_features_ops = 10075 [(module) = "framework"];
+ AttributedAppOps attributed_app_ops = 10075 [(module) = "framework"];
+ VoiceCallSession voice_call_session = 10076 [(module) = "telephony"];
+ VoiceCallRatUsage voice_call_rat_usage = 10077 [(module) = "telephony"];
+ SimSlotState sim_slot_state = 10078 [(module) = "telephony"];
+ SupportedRadioAccessFamily supported_radio_access_family = 10079 [(module) = "telephony"];
}
// DO NOT USE field numbers above 100,000 in AOSP.
@@ -3326,16 +3332,12 @@
optional int32 uid = 1 [(is_uid) = true];
// The operation's name.
- // To the extent possible, preserve the mapping from AppOpsManager.OP_ constants.
- // Only these named ops are actually logged.
- enum AppOpName {
- OP_NONE = -1; // Also represents UNKNOWN.
- OP_COARSE_LOCATION = 0;
- OP_FINE_LOCATION = 1;
- OP_CAMERA = 26;
- OP_RECORD_AUDIO = 27;
- }
- optional AppOpName app_op_name = 2 [default = OP_NONE];
+ // Only following four ops are logged
+ // COARSE_LOCATION = 0
+ // FINE_LOCATION = 1
+ // CAMERA = 26
+ // RECORD_AUDIO = 27
+ optional android.app.AppOpEnum app_op_name = 2 [default = APP_OP_NONE];
// The uid's permission mode for accessing the AppOp during this fgs session.
enum Mode {
@@ -3600,9 +3602,10 @@
// See NotificationSectionsManager.PriorityBucket.
enum NotificationSection {
SECTION_UNKNOWN = 0;
- SECTION_PEOPLE = 1;
- SECTION_ALERTING = 2;
- SECTION_SILENT = 3;
+ SECTION_HEADS_UP = 1;
+ SECTION_PEOPLE = 2;
+ SECTION_ALERTING = 3;
+ SECTION_SILENT = 4;
}
optional NotificationSection section = 6;
}
@@ -4474,8 +4477,7 @@
* after an OTA.
*
* Logged from:
- * - system/core/fs_mgr/libsnapshot/snapshot.cpp
- * - system/core/fs_mgr/libsnapshot/snapshotctl.cpp
+ * - system/update_engine/cleanup_previous_update_action.cc
*/
message SnapshotMergeReported {
// Keep in sync with
@@ -7565,8 +7567,8 @@
// Name of the package performing the op
optional string package_name = 2;
- // operation id; maps to the OP_* constants in AppOpsManager.java
- optional int32 op_id = 3;
+ // operation id
+ optional android.app.AppOpEnum op_id = 3 [default = APP_OP_NONE];
// The number of times the op was granted while the app was in the
// foreground (only for trusted requests)
@@ -7597,21 +7599,22 @@
}
/**
- * Historical app ops data per package and features.
+ * Historical app ops data per package and attribution tag.
*/
-message AppFeaturesOps {
+message AttributedAppOps {
// Uid of the package requesting the op
optional int32 uid = 1 [(is_uid) = true];
// Name of the package performing the op
optional string package_name = 2;
- // feature id; provided by developer when accessing related API, limited at 50 chars by API.
- // Features must be provided through manifest using <feature> tag available in R and above.
- optional string feature_id = 3;
+ // tag; provided by developer when accessing related API, limited at 50 chars by API.
+ // Attributions must be provided through manifest using <attribution> tag available in R and
+ // above.
+ optional string tag = 3;
- // operation id; maps to the OPSTR_* constants in AppOpsManager.java
- optional string op = 4;
+ // operation id
+ optional android.app.AppOpEnum op = 4 [default = APP_OP_NONE];
// The number of times the op was granted while the app was in the
// foreground (only for trusted requests)
@@ -7639,6 +7642,9 @@
// Whether AppOps is guarded by Runtime permission
optional bool is_runtime_permission = 11;
+
+ // Sampling rate used on device, from 0 to 100
+ optional int32 sampling_rate = 12;
}
/**
@@ -8467,9 +8473,11 @@
// operation string id per OPSTR_ constants in AppOpsManager.java
optional string op = 3;
- // feature id; provided by developer when accessing related API, limited at 50 chars by API.
- // Features must be provided through manifest using <feature> tag available in R and above.
- optional string feature_id = 4;
+ // attribution_tag; provided by developer when accessing related API, limited at 50 chars by
+ // API.
+ // Attributions must be provided through manifest using <attribution> tag available in R and
+ // above.
+ optional string attribution_tag = 4;
// message related to app op access, limited to 600 chars by API
optional string message = 5;
@@ -8478,6 +8486,7 @@
DEFAULT = 0;
UNIFORM = 1;
RARELY_USED = 2;
+ BOOT_TIME_SAMPLING = 3;
}
// sampling strategy used to collect this message
@@ -8666,6 +8675,154 @@
}
/**
+ * Pulls information for a single voice call.
+ *
+ * Each pull creates multiple atoms, one for each call. The sequence is randomized when pulled.
+ *
+ * Pulled from:
+ * frameworks/opt/telephony/src/java/com/android/internal/telephony/metrics/PersistPullers.java
+ */
+message VoiceCallSession {
+ // Bearer (IMS or CS) when the call started.
+ optional android.telephony.CallBearerEnum bearer_at_start = 1;
+
+ // Bearer (IMS or CS) when the call ended.
+ // The bearer may change during the call, e.g. due to SRVCC.
+ optional android.telephony.CallBearerEnum bearer_at_end = 2;
+
+ // Direction of the call (incoming or outgoing).
+ optional android.telephony.CallDirectionEnum direction = 3;
+
+ // Time spent setting up the call.
+ optional android.telephony.CallSetupDurationEnum setup_duration = 4;
+
+ // Whether the call ended before the setup was completed.
+ optional bool setup_failed = 5;
+
+ // IMS reason code or CS disconnect cause.
+ // For IMS, see: frameworks/base/telephony/java/android/telephony/ims/ImsReasonInfo.java
+ // For CS, see: frameworks/base/telephony/java/android/telephony/DisconnectCause.java
+ optional int32 disconnect_reason_code = 6;
+
+ // IMS extra code or CS precise disconnect cause.
+ // For IMS, this code is vendor-specific
+ // For CS, see: frameworks/base/telephony/java/android/telephony/PreciseDisconnectCause.java
+ optional int32 disconnect_extra_code = 7;
+
+ // IMS extra message or CS vendor cause.
+ optional string disconnect_extra_message = 8;
+
+ // Radio access technology (RAT) used when call started.
+ optional android.telephony.NetworkTypeEnum rat_at_start = 9;
+
+ // Radio access technology (RAT) used when call terminated.
+ optional android.telephony.NetworkTypeEnum rat_at_end = 10;
+
+ // Number of times RAT changed during the call.
+ optional int64 rat_switch_count = 11;
+
+ // A bitmask of all codecs used during the call.
+ // See: frameworks/opt/telephony/src/java/com/android/internal/telephony/metrics/VoiceCallSessionStats.java
+ optional int64 codec_bitmask = 12;
+
+ // Number of other calls going on during call setup, for the same SIM slot.
+ optional int32 concurrent_call_count_at_start = 13;
+
+ // Number of other calls going on during call termination, for the same SIM slot.
+ optional int32 concurrent_call_count_at_end = 14;
+
+ // Index of the SIM is used, 0 for single-SIM devices.
+ optional int32 sim_slot_index = 15;
+
+ // Whether the device was in multi-SIM mode (with multiple active SIM profiles).
+ optional bool is_multi_sim = 16;
+
+ // Whether the call was made with an eSIM profile.
+ optional bool is_esim = 17;
+
+ // Carrier ID of the SIM card.
+ // See https://source.android.com/devices/tech/config/carrierid.
+ optional int32 carrier_id = 18;
+
+ // Whether an SRVCC has been completed successfully.
+ // SRVCC (CS fallback) should be recorded in the IMS call since there will be no more SRVCC
+ // events once the call is switched to CS.
+ optional bool srvcc_completed = 19;
+
+ // Number of SRVCC failures.
+ optional int64 srvcc_failure_count = 20;
+
+ // Number of SRVCC cancellations.
+ optional int64 srvcc_cancellation_count = 21;
+
+ // Whether the Real-Time Text (RTT) was ever used in the call.
+ optional bool rtt_enabled = 22;
+
+ // Whether this was an emergency call.
+ optional bool is_emergency = 23;
+
+ // Whether the call was performed while roaming.
+ optional bool is_roaming = 24;
+}
+
+/**
+ * Pulls voice call radio access technology (RAT) usage.
+ *
+ * Each pull creates multiple atoms, one for each carrier/RAT, the order of which is irrelevant to
+ * time. The atom will be skipped if not enough data is available.
+ *
+ * Pulled from:
+ * frameworks/opt/telephony/src/java/com/android/internal/telephony/metrics/PersistPullers.java
+ */
+message VoiceCallRatUsage {
+ // Carrier ID (https://source.android.com/devices/tech/config/carrierid).
+ optional int32 carrier_id = 1;
+
+ // Radio access technology.
+ optional android.telephony.NetworkTypeEnum rat = 2;
+
+ // Total duration that voice calls spent on this carrier and RAT.
+ optional int64 total_duration_seconds = 3;
+
+ // Total number of calls using this carrier and RAT.
+ // A call is counted once even if it used the RAT multiple times.
+ optional int64 call_count = 4;
+}
+
+/**
+ * Pulls the number of active SIM slots and SIMs/eSIM profiles.
+ *
+ * Pulled from:
+ * frameworks/opt/telephony/src/java/com/android/internal/telephony/metrics/NonPersistPullers.java
+ */
+message SimSlotState {
+ // Number of active SIM slots (both physical and eSIM profiles) in the device.
+ optional int32 active_slot_count = 1;
+
+ // Number of SIM cards (both physical and active eSIM profiles).
+ // This number is always equal to or less than the number of active SIM slots.
+ optional int32 sim_count = 2;
+
+ // Number of active eSIM profiles.
+ // This number is always equal to or less than the number of SIMs.
+ optional int32 esim_count = 3;
+}
+
+/**
+ * Pulls supported cellular radio access technologies.
+ *
+ * This atom reports the capabilities of the device, rather than the network it has access to.
+ *
+ * Pulled from:
+ * frameworks/opt/telephony/src/java/com/android/internal/telephony/metrics/NonPersistPullers.java
+ */
+message SupportedRadioAccessFamily {
+ // A bitmask of supported radio technologies.
+ // See android.telephony.TelephonyManager.NetworkTypeBitMask.
+ optional int64 network_type_bitmask = 1;
+}
+
+/**
* Logs gnss stats from location service provider
*
* Pulled from:
diff --git a/cmds/statsd/src/config/ConfigManager.cpp b/cmds/statsd/src/config/ConfigManager.cpp
index 9bdb588..6d9c644 100644
--- a/cmds/statsd/src/config/ConfigManager.cpp
+++ b/cmds/statsd/src/config/ConfigManager.cpp
@@ -54,20 +54,22 @@
shared_ptr<IPendingIntentRef> mPir;
};
-static void configReceiverDied(void* cookie) {
+void ConfigManager::configReceiverDied(void* cookie) {
auto cookie_ = static_cast<ConfigReceiverDeathCookie*>(cookie);
- sp<ConfigManager> configManager = cookie_->mConfigManager;
- ConfigKey configKey = cookie_->mConfigKey;
- shared_ptr<IPendingIntentRef> pir = cookie_->mPir;
+ sp<ConfigManager>& thiz = cookie_->mConfigManager;
+ ConfigKey& configKey = cookie_->mConfigKey;
+ shared_ptr<IPendingIntentRef>& pir = cookie_->mPir;
- // TODO(b/149254662): Fix threading. This currently fails if a new
- // pir gets set between the get and the remove.
- if (configManager->GetConfigReceiver(configKey) == pir) {
- configManager->RemoveConfigReceiver(configKey);
+ // Erase the mapping from the config key to the config receiver (pir) if the
+ // mapping still exists.
+ lock_guard<mutex> lock(thiz->mMutex);
+ auto it = thiz->mConfigReceivers.find(configKey);
+ if (it != thiz->mConfigReceivers.end() && it->second == pir) {
+ thiz->mConfigReceivers.erase(configKey);
}
- // The death recipient corresponding to this specific pir can never
- // be triggered again, so free up resources.
- // TODO(b/149254662): Investigate other options to manage the memory.
+
+ // The death recipient corresponding to this specific pir can never be
+ // triggered again, so free up resources.
delete cookie_;
}
@@ -83,26 +85,29 @@
shared_ptr<IPendingIntentRef> mPir;
};
-static void activeConfigChangedReceiverDied(void* cookie) {
+void ConfigManager::activeConfigChangedReceiverDied(void* cookie) {
auto cookie_ = static_cast<ActiveConfigChangedReceiverDeathCookie*>(cookie);
- sp<ConfigManager> configManager = cookie_->mConfigManager;
+ sp<ConfigManager>& thiz = cookie_->mConfigManager;
int uid = cookie_->mUid;
- shared_ptr<IPendingIntentRef> pir = cookie_->mPir;
+ shared_ptr<IPendingIntentRef>& pir = cookie_->mPir;
- // TODO(b/149254662): Fix threading. This currently fails if a new
- // pir gets set between the get and the remove.
- if (configManager->GetActiveConfigsChangedReceiver(uid) == pir) {
- configManager->RemoveActiveConfigsChangedReceiver(uid);
+ // Erase the mapping from the config key to the active config changed
+ // receiver (pir) if the mapping still exists.
+ lock_guard<mutex> lock(thiz->mMutex);
+ auto it = thiz->mActiveConfigsChangedReceivers.find(uid);
+ if (it != thiz->mActiveConfigsChangedReceivers.end() && it->second == pir) {
+ thiz->mActiveConfigsChangedReceivers.erase(uid);
}
+
// The death recipient corresponding to this specific pir can never
// be triggered again, so free up resources.
delete cookie_;
}
-ConfigManager::ConfigManager():
+ConfigManager::ConfigManager() :
mConfigReceiverDeathRecipient(AIBinder_DeathRecipient_new(configReceiverDied)),
mActiveConfigChangedReceiverDeathRecipient(
- AIBinder_DeathRecipient_new(activeConfigChangedReceiverDied)) {
+ AIBinder_DeathRecipient_new(activeConfigChangedReceiverDied)) {
}
ConfigManager::~ConfigManager() {
@@ -189,8 +194,10 @@
void ConfigManager::SetActiveConfigsChangedReceiver(const int uid,
const shared_ptr<IPendingIntentRef>& pir) {
- lock_guard<mutex> lock(mMutex);
- mActiveConfigsChangedReceivers[uid] = pir;
+ {
+ lock_guard<mutex> lock(mMutex);
+ mActiveConfigsChangedReceivers[uid] = pir;
+ }
AIBinder_linkToDeath(pir->asBinder().get(), mActiveConfigChangedReceiverDeathRecipient.get(),
new ActiveConfigChangedReceiverDeathCookie(this, uid, pir));
}
diff --git a/cmds/statsd/src/config/ConfigManager.h b/cmds/statsd/src/config/ConfigManager.h
index 824e588..40146b1 100644
--- a/cmds/statsd/src/config/ConfigManager.h
+++ b/cmds/statsd/src/config/ConfigManager.h
@@ -161,6 +161,19 @@
// IPendingIntentRef dies.
::ndk::ScopedAIBinder_DeathRecipient mConfigReceiverDeathRecipient;
::ndk::ScopedAIBinder_DeathRecipient mActiveConfigChangedReceiverDeathRecipient;
+
+ /**
+ * Death recipient callback that is called when a config receiver dies.
+ * The cookie is a pointer to a ConfigReceiverDeathCookie.
+ */
+ static void configReceiverDied(void* cookie);
+
+ /**
+ * Death recipient callback that is called when an active config changed
+ * receiver dies. The cookie is a pointer to an
+ * ActiveConfigChangedReceiverDeathCookie.
+ */
+ static void activeConfigChangedReceiverDied(void* cookie);
};
} // namespace statsd
diff --git a/cmds/statsd/src/external/StatsPullerManager.cpp b/cmds/statsd/src/external/StatsPullerManager.cpp
index 1c38542..8b6a5a1 100644
--- a/cmds/statsd/src/external/StatsPullerManager.cpp
+++ b/cmds/statsd/src/external/StatsPullerManager.cpp
@@ -32,7 +32,7 @@
#include "../statscompanion_util.h"
#include "StatsCallbackPuller.h"
#include "TrainInfoPuller.h"
-#include "statslog.h"
+#include "statslog_statsd.h"
using std::shared_ptr;
using std::vector;
@@ -47,7 +47,7 @@
StatsPullerManager::StatsPullerManager()
: kAllPullAtomInfo({
// TrainInfo.
- {{.atomTag = android::util::TRAIN_INFO}, new TrainInfoPuller()},
+ {{.atomTag = util::TRAIN_INFO}, new TrainInfoPuller()},
}),
mNextPullTimeNs(NO_ALARM_UPDATE) {
}
@@ -85,12 +85,9 @@
return;
}
- // TODO(b/149254662): Why are we creating a copy here? This is different
- // from the other places where we create a copy because we don't reassign
- // mStatsCompanionService so a destructor can't implicitly be called...
- shared_ptr<IStatsCompanionService> statsCompanionServiceCopy = mStatsCompanionService;
- if (statsCompanionServiceCopy != nullptr) {
- statsCompanionServiceCopy->setPullingAlarm(mNextPullTimeNs / 1000000);
+ // TODO(b/151045771): do not hold a lock while making a binder call
+ if (mStatsCompanionService != nullptr) {
+ mStatsCompanionService->setPullingAlarm(mNextPullTimeNs / 1000000);
} else {
VLOG("StatsCompanionService not available. Alarm not set.");
}
@@ -99,8 +96,6 @@
void StatsPullerManager::SetStatsCompanionService(
shared_ptr<IStatsCompanionService> statsCompanionService) {
- // TODO(b/149254662): Why are we using AutoMutex instead of lock_guard?
- // Additionally, do we need the temporary shared_ptr to prevent deadlocks?
AutoMutex _l(mLock);
shared_ptr<IStatsCompanionService> tmpForLock = mStatsCompanionService;
mStatsCompanionService = statsCompanionService;
diff --git a/cmds/statsd/src/external/TrainInfoPuller.cpp b/cmds/statsd/src/external/TrainInfoPuller.cpp
index a7d8d4e..3837f4a 100644
--- a/cmds/statsd/src/external/TrainInfoPuller.cpp
+++ b/cmds/statsd/src/external/TrainInfoPuller.cpp
@@ -22,7 +22,7 @@
#include "TrainInfoPuller.h"
#include "logd/LogEvent.h"
#include "stats_log_util.h"
-#include "statslog.h"
+#include "statslog_statsd.h"
#include "storage/StorageManager.h"
using std::make_shared;
@@ -33,7 +33,7 @@
namespace statsd {
TrainInfoPuller::TrainInfoPuller() :
- StatsPuller(android::util::TRAIN_INFO) {
+ StatsPuller(util::TRAIN_INFO) {
}
bool TrainInfoPuller::PullInternal(vector<shared_ptr<LogEvent>>* data) {
diff --git a/cmds/statsd/src/guardrail/StatsdStats.cpp b/cmds/statsd/src/guardrail/StatsdStats.cpp
index 3054b6d..2bd13d7 100644
--- a/cmds/statsd/src/guardrail/StatsdStats.cpp
+++ b/cmds/statsd/src/guardrail/StatsdStats.cpp
@@ -20,7 +20,7 @@
#include <android/util/ProtoOutputStream.h>
#include "../stats_log_util.h"
-#include "statslog.h"
+#include "statslog_statsd.h"
#include "storage/StorageManager.h"
namespace android {
@@ -113,9 +113,9 @@
const int FIELD_ID_ACTIVATION_BROADCAST_GUARDRAIL_TIME = 2;
const std::map<int, std::pair<size_t, size_t>> StatsdStats::kAtomDimensionKeySizeLimitMap = {
- {android::util::BINDER_CALLS, {6000, 10000}},
- {android::util::LOOPER_STATS, {1500, 2500}},
- {android::util::CPU_TIME_PER_UID_FREQ, {6000, 10000}},
+ {util::BINDER_CALLS, {6000, 10000}},
+ {util::LOOPER_STATS, {1500, 2500}},
+ {util::CPU_TIME_PER_UID_FREQ, {6000, 10000}},
};
StatsdStats::StatsdStats() {
diff --git a/cmds/statsd/src/logd/LogEvent.cpp b/cmds/statsd/src/logd/LogEvent.cpp
index 974e203..b515d0a 100644
--- a/cmds/statsd/src/logd/LogEvent.cpp
+++ b/cmds/statsd/src/logd/LogEvent.cpp
@@ -18,7 +18,7 @@
#include "logd/LogEvent.h"
#include "stats_log_util.h"
-#include "statslog.h"
+#include "statslog_statsd.h"
#include <android/binder_ibinder.h>
#include <android-base/stringprintf.h>
@@ -100,7 +100,7 @@
const std::map<int32_t, float>& float_map) {
mLogdTimestampNs = wallClockTimestampNs;
mElapsedTimestampNs = elapsedTimestampNs;
- mTagId = android::util::KEY_VALUE_PAIRS_ATOM;
+ mTagId = util::KEY_VALUE_PAIRS_ATOM;
mLogUid = uid;
int pos[] = {1, 1, 1};
@@ -153,7 +153,7 @@
const std::vector<uint8_t>& experimentIds, int32_t userId) {
mLogdTimestampNs = getWallClockNs();
mElapsedTimestampNs = getElapsedRealtimeNs();
- mTagId = android::util::BINARY_PUSH_STATE_CHANGED;
+ mTagId = util::BINARY_PUSH_STATE_CHANGED;
mLogUid = AIBinder_getCallingUid();
mLogPid = AIBinder_getCallingPid();
@@ -172,7 +172,7 @@
const InstallTrainInfo& trainInfo) {
mLogdTimestampNs = wallClockTimestampNs;
mElapsedTimestampNs = elapsedTimestampNs;
- mTagId = android::util::TRAIN_INFO;
+ mTagId = util::TRAIN_INFO;
mValues.push_back(
FieldValue(Field(mTagId, getSimpleField(1)), Value(trainInfo.trainVersionCode)));
@@ -350,17 +350,19 @@
return false;
}
-void LogEvent::parseInt32(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseInt32(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
int32_t value = readNextValue<int32_t>();
addToValues(pos, depth, value, last);
+ parseAnnotations(numAnnotations);
}
-void LogEvent::parseInt64(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseInt64(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
int64_t value = readNextValue<int64_t>();
addToValues(pos, depth, value, last);
+ parseAnnotations(numAnnotations);
}
-void LogEvent::parseString(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseString(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
int32_t numBytes = readNextValue<int32_t>();
if ((uint32_t)numBytes > mRemainingLen) {
mValid = false;
@@ -371,20 +373,23 @@
mBuf += numBytes;
mRemainingLen -= numBytes;
addToValues(pos, depth, value, last);
+ parseAnnotations(numAnnotations);
}
-void LogEvent::parseFloat(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseFloat(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
float value = readNextValue<float>();
addToValues(pos, depth, value, last);
+ parseAnnotations(numAnnotations);
}
-void LogEvent::parseBool(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseBool(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
// cast to int32_t because FieldValue does not support bools
int32_t value = (int32_t)readNextValue<uint8_t>();
addToValues(pos, depth, value, last);
+ parseAnnotations(numAnnotations);
}
-void LogEvent::parseByteArray(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseByteArray(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
int32_t numBytes = readNextValue<int32_t>();
if ((uint32_t)numBytes > mRemainingLen) {
mValid = false;
@@ -395,9 +400,10 @@
mBuf += numBytes;
mRemainingLen -= numBytes;
addToValues(pos, depth, value, last);
+ parseAnnotations(numAnnotations);
}
-void LogEvent::parseKeyValuePairs(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseKeyValuePairs(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations) {
int32_t numPairs = readNextValue<uint8_t>();
for (pos[1] = 1; pos[1] <= numPairs; pos[1]++) {
@@ -405,56 +411,79 @@
// parse key
pos[2] = 1;
- parseInt32(pos, 2, last);
+ parseInt32(pos, /*depth=*/2, last, /*numAnnotations=*/0);
// parse value
last[2] = true;
- uint8_t typeId = getTypeId(readNextValue<uint8_t>());
- switch (typeId) {
+
+ uint8_t typeInfo = readNextValue<uint8_t>();
+ switch (getTypeId(typeInfo)) {
case INT32_TYPE:
pos[2] = 2; // pos[2] determined by index of type in KeyValuePair in atoms.proto
- parseInt32(pos, 2, last);
+ parseInt32(pos, /*depth=*/2, last, /*numAnnotations=*/0);
break;
case INT64_TYPE:
pos[2] = 3;
- parseInt64(pos, 2, last);
+ parseInt64(pos, /*depth=*/2, last, /*numAnnotations=*/0);
break;
case STRING_TYPE:
pos[2] = 4;
- parseString(pos, 2, last);
+ parseString(pos, /*depth=*/2, last, /*numAnnotations=*/0);
break;
case FLOAT_TYPE:
pos[2] = 5;
- parseFloat(pos, 2, last);
+ parseFloat(pos, /*depth=*/2, last, /*numAnnotations=*/0);
break;
default:
mValid = false;
}
}
+ parseAnnotations(numAnnotations);
+
pos[1] = pos[2] = 1;
last[1] = last[2] = false;
}
-void LogEvent::parseAttributionChain(int32_t* pos, int32_t depth, bool* last) {
+void LogEvent::parseAttributionChain(int32_t* pos, int32_t depth, bool* last,
+ uint8_t numAnnotations) {
int32_t numNodes = readNextValue<uint8_t>();
for (pos[1] = 1; pos[1] <= numNodes; pos[1]++) {
last[1] = (pos[1] == numNodes);
// parse uid
pos[2] = 1;
- parseInt32(pos, 2, last);
+ parseInt32(pos, /*depth=*/2, last, /*numAnnotations=*/0);
// parse tag
pos[2] = 2;
last[2] = true;
- parseString(pos, 2, last);
+ parseString(pos, /*depth=*/2, last, /*numAnnotations=*/0);
}
+ parseAnnotations(numAnnotations);
+
pos[1] = pos[2] = 1;
last[1] = last[2] = false;
}
+// TODO(b/151109630): store annotation information within LogEvent
+void LogEvent::parseAnnotations(uint8_t numAnnotations) {
+ for (uint8_t i = 0; i < numAnnotations; i++) {
+ /*uint8_t annotationId = */ readNextValue<uint8_t>();
+ uint8_t annotationType = readNextValue<uint8_t>();
+ switch (annotationType) {
+ case BOOL_TYPE:
+ /*bool annotationValue = */ readNextValue<uint8_t>();
+ break;
+ case INT32_TYPE:
+ /*int32_t annotationValue =*/ readNextValue<int32_t>();
+ break;
+ default:
+ mValid = false;
+ }
+ }
+}
// This parsing logic is tied to the encoding scheme used in StatsEvent.java and
// stats_event.c
@@ -475,6 +504,7 @@
typeInfo = readNextValue<uint8_t>();
if (getTypeId(typeInfo) != INT64_TYPE) mValid = false;
mElapsedTimestampNs = readNextValue<int64_t>();
+ parseAnnotations(getNumAnnotations(typeInfo)); // atom-level annotations
numElements--;
typeInfo = readNextValue<uint8_t>();
@@ -484,37 +514,36 @@
for (pos[0] = 1; pos[0] <= numElements && mValid; pos[0]++) {
+ last[0] = (pos[0] == numElements);
+
typeInfo = readNextValue<uint8_t>();
uint8_t typeId = getTypeId(typeInfo);
- last[0] = (pos[0] == numElements);
-
// TODO(b/144373276): handle errors passed to the socket
- // TODO(b/144373257): parse annotations
switch(typeId) {
case BOOL_TYPE:
- parseBool(pos, 0, last);
+ parseBool(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case INT32_TYPE:
- parseInt32(pos, 0, last);
+ parseInt32(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case INT64_TYPE:
- parseInt64(pos, 0, last);
+ parseInt64(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case FLOAT_TYPE:
- parseFloat(pos, 0, last);
+ parseFloat(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case BYTE_ARRAY_TYPE:
- parseByteArray(pos, 0, last);
+ parseByteArray(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case STRING_TYPE:
- parseString(pos, 0, last);
+ parseString(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case KEY_VALUE_PAIRS_TYPE:
- parseKeyValuePairs(pos, 0, last);
+ parseKeyValuePairs(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
case ATTRIBUTION_CHAIN_TYPE:
- parseAttributionChain(pos, 0, last);
+ parseAttributionChain(pos, /*depth=*/0, last, getNumAnnotations(typeInfo));
break;
default:
mValid = false;
@@ -531,7 +560,7 @@
}
uint8_t LogEvent::getNumAnnotations(uint8_t typeInfo) {
- return (typeInfo >> 4) & 0x0F;
+ return (typeInfo >> 4) & 0x0F; // num annotations in upper 4 bytes
}
int64_t LogEvent::GetLong(size_t key, status_t* err) const {
diff --git a/cmds/statsd/src/logd/LogEvent.h b/cmds/statsd/src/logd/LogEvent.h
index 3940aa8..6537f13 100644
--- a/cmds/statsd/src/logd/LogEvent.h
+++ b/cmds/statsd/src/logd/LogEvent.h
@@ -232,14 +232,15 @@
*/
LogEvent(const LogEvent&);
- void parseInt32(int32_t* pos, int32_t depth, bool* last);
- void parseInt64(int32_t* pos, int32_t depth, bool* last);
- void parseString(int32_t* pos, int32_t depth, bool* last);
- void parseFloat(int32_t* pos, int32_t depth, bool* last);
- void parseBool(int32_t* pos, int32_t depth, bool* last);
- void parseByteArray(int32_t* pos, int32_t depth, bool* last);
- void parseKeyValuePairs(int32_t* pos, int32_t depth, bool* last);
- void parseAttributionChain(int32_t* pos, int32_t depth, bool* last);
+ void parseInt32(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseInt64(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseString(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseFloat(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseBool(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseByteArray(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseKeyValuePairs(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseAttributionChain(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations);
+ void parseAnnotations(uint8_t numAnnotations);
/**
* The below three variables are only valid during the execution of
@@ -328,4 +329,3 @@
} // namespace statsd
} // namespace os
} // namespace android
-
diff --git a/cmds/statsd/src/metrics/MetricsManager.cpp b/cmds/statsd/src/metrics/MetricsManager.cpp
index 536700f..6f54ea7 100644
--- a/cmds/statsd/src/metrics/MetricsManager.cpp
+++ b/cmds/statsd/src/metrics/MetricsManager.cpp
@@ -31,7 +31,7 @@
#include "state/StateManager.h"
#include "stats_log_util.h"
#include "stats_util.h"
-#include "statslog.h"
+#include "statslog_statsd.h"
using android::util::FIELD_COUNT_REPEATED;
using android::util::FIELD_TYPE_INT32;
@@ -291,7 +291,7 @@
}
bool MetricsManager::eventSanityCheck(const LogEvent& event) {
- if (event.GetTagId() == android::util::APP_BREADCRUMB_REPORTED) {
+ if (event.GetTagId() == util::APP_BREADCRUMB_REPORTED) {
// Check that app breadcrumb reported fields are valid.
status_t err = NO_ERROR;
@@ -318,7 +318,7 @@
VLOG("APP_BREADCRUMB_REPORTED does not have valid state %ld", appHookState);
return false;
}
- } else if (event.GetTagId() == android::util::DAVEY_OCCURRED) {
+ } else if (event.GetTagId() == util::DAVEY_OCCURRED) {
// Daveys can be logged from any app since they are logged in libs/hwui/JankTracker.cpp.
// Check that the davey duration is reasonable. Max length check is for privacy.
status_t err = NO_ERROR;
diff --git a/cmds/statsd/src/packages/UidMap.h b/cmds/statsd/src/packages/UidMap.h
index 4e3c506..02fe7b1 100644
--- a/cmds/statsd/src/packages/UidMap.h
+++ b/cmds/statsd/src/packages/UidMap.h
@@ -139,7 +139,7 @@
// record is deleted.
void appendUidMap(const int64_t& timestamp, const ConfigKey& key, std::set<string>* str_set,
bool includeVersionStrings, bool includeInstaller,
- util::ProtoOutputStream* proto);
+ ProtoOutputStream* proto);
// Forces the output to be cleared. We still generate a snapshot based on the current state.
// This results in extra data uploaded but helps us reconstruct the uid mapping on the server
diff --git a/cmds/statsd/src/subscriber/SubscriberReporter.cpp b/cmds/statsd/src/subscriber/SubscriberReporter.cpp
index 93af5e9..c915ef3 100644
--- a/cmds/statsd/src/subscriber/SubscriberReporter.cpp
+++ b/cmds/statsd/src/subscriber/SubscriberReporter.cpp
@@ -39,33 +39,47 @@
shared_ptr<IPendingIntentRef> mPir;
};
-static void broadcastSubscriberDied(void* cookie) {
- BroadcastSubscriberDeathCookie* cookie_ = (BroadcastSubscriberDeathCookie*)cookie;
- ConfigKey configKey = cookie_->mConfigKey;
+void SubscriberReporter::broadcastSubscriberDied(void* cookie) {
+ auto cookie_ = static_cast<BroadcastSubscriberDeathCookie*>(cookie);
+ ConfigKey& configKey = cookie_->mConfigKey;
int64_t subscriberId = cookie_->mSubscriberId;
- shared_ptr<IPendingIntentRef> pir = cookie_->mPir;
+ shared_ptr<IPendingIntentRef>& pir = cookie_->mPir;
- // TODO(b/149254662): Fix threading. This currently fails if a new pir gets
- // set between the get and the unset.
- if (SubscriberReporter::getInstance().getBroadcastSubscriber(configKey, subscriberId) == pir) {
- SubscriberReporter::getInstance().unsetBroadcastSubscriber(configKey, subscriberId);
+ SubscriberReporter& thiz = getInstance();
+
+ // Erase the mapping from a (config_key, subscriberId) to a pir if the
+ // mapping exists.
+ lock_guard<mutex> lock(thiz.mLock);
+ auto subscriberMapIt = thiz.mIntentMap.find(configKey);
+ if (subscriberMapIt != thiz.mIntentMap.end()) {
+ auto subscriberMap = subscriberMapIt->second;
+ auto pirIt = subscriberMap.find(subscriberId);
+ if (pirIt != subscriberMap.end() && pirIt->second == pir) {
+ subscriberMap.erase(subscriberId);
+ if (subscriberMap.empty()) {
+ thiz.mIntentMap.erase(configKey);
+ }
+ }
}
+
// The death recipient corresponding to this specific pir can never be
// triggered again, so free up resources.
delete cookie_;
}
-static ::ndk::ScopedAIBinder_DeathRecipient sBroadcastSubscriberDeathRecipient(
- AIBinder_DeathRecipient_new(broadcastSubscriberDied));
+SubscriberReporter::SubscriberReporter() :
+ mBroadcastSubscriberDeathRecipient(AIBinder_DeathRecipient_new(broadcastSubscriberDied)) {
+}
void SubscriberReporter::setBroadcastSubscriber(const ConfigKey& configKey,
int64_t subscriberId,
const shared_ptr<IPendingIntentRef>& pir) {
VLOG("SubscriberReporter::setBroadcastSubscriber called.");
- lock_guard<mutex> lock(mLock);
- mIntentMap[configKey][subscriberId] = pir;
- // TODO(b/149254662): Is it ok to call linkToDeath while holding a lock?
- AIBinder_linkToDeath(pir->asBinder().get(), sBroadcastSubscriberDeathRecipient.get(),
+ {
+ lock_guard<mutex> lock(mLock);
+ mIntentMap[configKey][subscriberId] = pir;
+ }
+ AIBinder_linkToDeath(pir->asBinder().get(), mBroadcastSubscriberDeathRecipient.get(),
new BroadcastSubscriberDeathCookie(configKey, subscriberId, pir));
}
@@ -103,8 +117,6 @@
}
int64_t subscriberId = subscription.broadcast_subscriber_details().subscriber_id();
- // TODO(b/149254662): Is there a way to convert a RepeatedPtrField into a
- // vector without copying?
vector<string> cookies;
cookies.reserve(subscription.broadcast_subscriber_details().cookie_size());
for (auto& cookie : subscription.broadcast_subscriber_details().cookie()) {
diff --git a/cmds/statsd/src/subscriber/SubscriberReporter.h b/cmds/statsd/src/subscriber/SubscriberReporter.h
index 0f97d39..4fe4281 100644
--- a/cmds/statsd/src/subscriber/SubscriberReporter.h
+++ b/cmds/statsd/src/subscriber/SubscriberReporter.h
@@ -78,7 +78,7 @@
int64_t subscriberId);
private:
- SubscriberReporter() {};
+ SubscriberReporter();
mutable mutex mLock;
@@ -94,6 +94,14 @@
const Subscription& subscription,
const vector<string>& cookies,
const MetricDimensionKey& dimKey) const;
+
+ ::ndk::ScopedAIBinder_DeathRecipient mBroadcastSubscriberDeathRecipient;
+
+ /**
+ * Death recipient callback that is called when a broadcast subscriber dies.
+ * The cookie is a pointer to a BroadcastSubscriberDeathCookie.
+ */
+ static void broadcastSubscriberDied(void* cookie);
};
} // namespace statsd
diff --git a/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp b/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
index 4b78e30..7febb35 100644
--- a/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
+++ b/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
@@ -137,7 +137,9 @@
simplePredicate, trackerNameIndexMap);
EXPECT_FALSE(conditionTracker.isSliced());
- LogEvent event(1 /*tagId*/, 0 /*timestamp*/);
+ // This event is not accessed in this test besides dimensions which is why this is okay.
+ // This is technically an invalid LogEvent because we do not call parseBuffer.
+ LogEvent event(/*uid=*/0, /*pid=*/0);
vector<MatchingState> matcherState;
matcherState.push_back(MatchingState::kNotMatched);
@@ -222,7 +224,9 @@
trackerNameIndexMap);
EXPECT_FALSE(conditionTracker.isSliced());
- LogEvent event(1 /*tagId*/, 0 /*timestamp*/);
+ // This event is not accessed in this test besides dimensions which is why this is okay.
+ // This is technically an invalid LogEvent because we do not call parseBuffer.
+ LogEvent event(/*uid=*/0, /*pid=*/0);
// one matched start
vector<MatchingState> matcherState;
@@ -296,8 +300,8 @@
std::vector<int> uids = {111, 222, 333};
- LogEvent event(/*uid=*/-1, /*pid=*/-1);
- makeWakeLockEvent(&event, /*atomId=*/1, /*timestamp=*/0, uids, "wl1", /*acquire=*/1);
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event1, /*atomId=*/1, /*timestamp=*/0, uids, "wl1", /*acquire=*/1);
// one matched start
vector<MatchingState> matcherState;
@@ -308,7 +312,7 @@
vector<ConditionState> conditionCache(1, ConditionState::kNotEvaluated);
vector<bool> changedCache(1, false);
- conditionTracker.evaluateCondition(event, matcherState, allPredicates, conditionCache,
+ conditionTracker.evaluateCondition(event1, matcherState, allPredicates, conditionCache,
changedCache);
if (position == Position::FIRST || position == Position::LAST) {
@@ -333,7 +337,7 @@
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by this uid
- LogEvent event2(/*uid=*/-1, /*pid=*/-1);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
makeWakeLockEvent(&event2, /*atomId=*/1, /*timestamp=*/0, uids, "wl2", /*acquire=*/1);
matcherState.clear();
matcherState.push_back(MatchingState::kMatched);
@@ -353,7 +357,7 @@
// wake lock 1 release
- LogEvent event3(/*uid=*/-1, /*pid=*/-1);
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
makeWakeLockEvent(&event3, /*atomId=*/1, /*timestamp=*/0, uids, "wl1", /*acquire=*/0);
matcherState.clear();
matcherState.push_back(MatchingState::kNotMatched);
@@ -372,7 +376,7 @@
EXPECT_TRUE(conditionTracker.getChangedToTrueDimensions(allConditions)->empty());
EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
- LogEvent event4(/*uid=*/-1, /*pid=*/-1);
+ LogEvent event4(/*uid=*/0, /*pid=*/0);
makeWakeLockEvent(&event4, /*atomId=*/1, /*timestamp=*/0, uids, "wl2", /*acquire=*/0);
matcherState.clear();
matcherState.push_back(MatchingState::kNotMatched);
@@ -399,246 +403,235 @@
}
-//TEST(SimpleConditionTrackerTest, TestSlicedWithNoOutputDim) {
-// std::vector<sp<ConditionTracker>> allConditions;
-//
-// SimplePredicate simplePredicate = getWakeLockHeldCondition(
-// true /*nesting*/, true /*default to false*/, false /*slice output by uid*/,
-// Position::ANY /* position */);
-// string conditionName = "WL_HELD";
-//
-// unordered_map<int64_t, int> trackerNameIndexMap;
-// trackerNameIndexMap[StringToId("WAKE_LOCK_ACQUIRE")] = 0;
-// trackerNameIndexMap[StringToId("WAKE_LOCK_RELEASE")] = 1;
-// trackerNameIndexMap[StringToId("RELEASE_ALL")] = 2;
-//
-// SimpleConditionTracker conditionTracker(kConfigKey, StringToId(conditionName),
-// 0 /*condition tracker index*/, simplePredicate,
-// trackerNameIndexMap);
-//
-// EXPECT_FALSE(conditionTracker.isSliced());
-//
-// std::vector<int> uid_list1 = {111, 1111, 11111};
-// string uid1_wl1 = "wl1_1";
-// std::vector<int> uid_list2 = {222, 2222, 22222};
-// string uid2_wl1 = "wl2_1";
-//
-// LogEvent event(1 /*tagId*/, 0 /*timestamp*/);
-// makeWakeLockEvent(&event, uid_list1, uid1_wl1, 1);
-//
-// // one matched start for uid1
-// vector<MatchingState> matcherState;
-// matcherState.push_back(MatchingState::kMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// vector<sp<ConditionTracker>> allPredicates;
-// vector<ConditionState> conditionCache(1, ConditionState::kNotEvaluated);
-// vector<bool> changedCache(1, false);
-//
-// conditionTracker.evaluateCondition(event, matcherState, allPredicates, conditionCache,
-// changedCache);
-//
-// EXPECT_EQ(1UL, conditionTracker.mSlicedConditionState.size());
-// EXPECT_TRUE(changedCache[0]);
-//
-// // Now test query
-// ConditionKey queryKey;
-// conditionCache[0] = ConditionState::kNotEvaluated;
-//
-// conditionTracker.isConditionMet(queryKey, allPredicates,
-// true,
-// conditionCache);
-// EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
-//
-// // another wake lock acquired by this uid
-// LogEvent event2(1 /*tagId*/, 0 /*timestamp*/);
-// makeWakeLockEvent(&event2, uid_list2, uid2_wl1, 1);
-// matcherState.clear();
-// matcherState.push_back(MatchingState::kMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// changedCache[0] = false;
-// conditionTracker.evaluateCondition(event2, matcherState, allPredicates, conditionCache,
-// changedCache);
-// EXPECT_FALSE(changedCache[0]);
-//
-// // uid1 wake lock 1 release
-// LogEvent event3(1 /*tagId*/, 0 /*timestamp*/);
-// makeWakeLockEvent(&event3, uid_list1, uid1_wl1, 0); // now release it.
-// matcherState.clear();
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kMatched);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// changedCache[0] = false;
-// conditionTracker.evaluateCondition(event3, matcherState, allPredicates, conditionCache,
-// changedCache);
-// // nothing changes, because uid2 is still holding wl.
-// EXPECT_FALSE(changedCache[0]);
-//
-// LogEvent event4(1 /*tagId*/, 0 /*timestamp*/);
-// makeWakeLockEvent(&event4, uid_list2, uid2_wl1, 0); // now release it.
-// matcherState.clear();
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kMatched);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// changedCache[0] = false;
-// conditionTracker.evaluateCondition(event4, matcherState, allPredicates, conditionCache,
-// changedCache);
-// EXPECT_EQ(0UL, conditionTracker.mSlicedConditionState.size());
-// EXPECT_TRUE(changedCache[0]);
-//
-// // query again
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// conditionTracker.isConditionMet(queryKey, allPredicates,
-// true,
-// conditionCache);
-// EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
-//}
-//
-//TEST(SimpleConditionTrackerTest, TestStopAll) {
-// std::vector<sp<ConditionTracker>> allConditions;
-// for (Position position :
-// { Position::FIRST, Position::LAST }) {
-// SimplePredicate simplePredicate = getWakeLockHeldCondition(
-// true /*nesting*/, true /*default to false*/, true /*output slice by uid*/,
-// position);
-// string conditionName = "WL_HELD_BY_UID3";
-//
-// unordered_map<int64_t, int> trackerNameIndexMap;
-// trackerNameIndexMap[StringToId("WAKE_LOCK_ACQUIRE")] = 0;
-// trackerNameIndexMap[StringToId("WAKE_LOCK_RELEASE")] = 1;
-// trackerNameIndexMap[StringToId("RELEASE_ALL")] = 2;
-//
-// SimpleConditionTracker conditionTracker(kConfigKey, StringToId(conditionName),
-// 0 /*condition tracker index*/, simplePredicate,
-// trackerNameIndexMap);
-//
-// std::vector<int> uid_list1 = {111, 1111, 11111};
-// std::vector<int> uid_list2 = {222, 2222, 22222};
-//
-// LogEvent event(1 /*tagId*/, 0 /*timestamp*/);
-// makeWakeLockEvent(&event, uid_list1, "wl1", 1);
-//
-// // one matched start
-// vector<MatchingState> matcherState;
-// matcherState.push_back(MatchingState::kMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// vector<sp<ConditionTracker>> allPredicates;
-// vector<ConditionState> conditionCache(1, ConditionState::kNotEvaluated);
-// vector<bool> changedCache(1, false);
-//
-// conditionTracker.evaluateCondition(event, matcherState, allPredicates, conditionCache,
-// changedCache);
-// if (position == Position::FIRST ||
-// position == Position::LAST) {
-// EXPECT_EQ(1UL, conditionTracker.mSlicedConditionState.size());
-// } else {
-// EXPECT_EQ(uid_list1.size(), conditionTracker.mSlicedConditionState.size());
-// }
-// EXPECT_TRUE(changedCache[0]);
-// {
-// if (position == Position::FIRST ||
-// position == Position::LAST) {
-// EXPECT_EQ(1UL, conditionTracker.getChangedToTrueDimensions(allConditions)->size());
-// EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
-// } else {
-// EXPECT_EQ(uid_list1.size(), conditionTracker.getChangedToTrueDimensions(allConditions)->size());
-// EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
-// }
-// }
-//
-// // Now test query
-// const auto queryKey = getWakeLockQueryKey(position, uid_list1, conditionName);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-//
-// conditionTracker.isConditionMet(queryKey, allPredicates,
-// false,
-// conditionCache);
-// EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
-//
-// // another wake lock acquired by uid2
-// LogEvent event2(1 /*tagId*/, 0 /*timestamp*/);
-// makeWakeLockEvent(&event2, uid_list2, "wl2", 1);
-// matcherState.clear();
-// matcherState.push_back(MatchingState::kMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// changedCache[0] = false;
-// conditionTracker.evaluateCondition(event2, matcherState, allPredicates, conditionCache,
-// changedCache);
-// if (position == Position::FIRST ||
-// position == Position::LAST) {
-// EXPECT_EQ(2UL, conditionTracker.mSlicedConditionState.size());
-// } else {
-// EXPECT_EQ(uid_list1.size() + uid_list2.size(),
-// conditionTracker.mSlicedConditionState.size());
-// }
-// EXPECT_TRUE(changedCache[0]);
-// {
-// if (position == Position::FIRST ||
-// position == Position::LAST) {
-// EXPECT_EQ(1UL, conditionTracker.getChangedToTrueDimensions(allConditions)->size());
-// EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
-// } else {
-// EXPECT_EQ(uid_list2.size(), conditionTracker.getChangedToTrueDimensions(allConditions)->size());
-// EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
-// }
-// }
-//
-//
-// // TEST QUERY
-// const auto queryKey2 = getWakeLockQueryKey(position, uid_list2, conditionName);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// conditionTracker.isConditionMet(queryKey, allPredicates,
-// false,
-// conditionCache);
-//
-// EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
-//
-//
-// // stop all event
-// LogEvent event3(2 /*tagId*/, 0 /*timestamp*/);
-// matcherState.clear();
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kNotMatched);
-// matcherState.push_back(MatchingState::kMatched);
-//
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// changedCache[0] = false;
-// conditionTracker.evaluateCondition(event3, matcherState, allPredicates, conditionCache,
-// changedCache);
-// EXPECT_TRUE(changedCache[0]);
-// EXPECT_EQ(0UL, conditionTracker.mSlicedConditionState.size());
-// {
-// if (position == Position::FIRST || position == Position::LAST) {
-// EXPECT_EQ(2UL, conditionTracker.getChangedToFalseDimensions(allConditions)->size());
-// EXPECT_TRUE(conditionTracker.getChangedToTrueDimensions(allConditions)->empty());
-// } else {
-// EXPECT_EQ(uid_list1.size() + uid_list2.size(),
-// conditionTracker.getChangedToFalseDimensions(allConditions)->size());
-// EXPECT_TRUE(conditionTracker.getChangedToTrueDimensions(allConditions)->empty());
-// }
-// }
-//
-// // TEST QUERY
-// const auto queryKey3 = getWakeLockQueryKey(position, uid_list1, conditionName);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// conditionTracker.isConditionMet(queryKey, allPredicates,
-// false,
-// conditionCache);
-// EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
-//
-// // TEST QUERY
-// const auto queryKey4 = getWakeLockQueryKey(position, uid_list2, conditionName);
-// conditionCache[0] = ConditionState::kNotEvaluated;
-// conditionTracker.isConditionMet(queryKey, allPredicates,
-// false,
-// conditionCache);
-// EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
-// }
-//}
+TEST(SimpleConditionTrackerTest, TestSlicedWithNoOutputDim) {
+ std::vector<sp<ConditionTracker>> allConditions;
+
+ SimplePredicate simplePredicate =
+ getWakeLockHeldCondition(true /*nesting*/, true /*default to false*/,
+ false /*slice output by uid*/, Position::ANY /* position */);
+ string conditionName = "WL_HELD";
+
+ unordered_map<int64_t, int> trackerNameIndexMap;
+ trackerNameIndexMap[StringToId("WAKE_LOCK_ACQUIRE")] = 0;
+ trackerNameIndexMap[StringToId("WAKE_LOCK_RELEASE")] = 1;
+ trackerNameIndexMap[StringToId("RELEASE_ALL")] = 2;
+
+ SimpleConditionTracker conditionTracker(kConfigKey, StringToId(conditionName),
+ 0 /*condition tracker index*/, simplePredicate,
+ trackerNameIndexMap);
+
+ EXPECT_FALSE(conditionTracker.isSliced());
+
+ std::vector<int> uids1 = {111, 1111, 11111};
+ string uid1_wl1 = "wl1_1";
+ std::vector<int> uids2 = {222, 2222, 22222};
+ string uid2_wl1 = "wl2_1";
+
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event1, /*atomId=*/1, /*timestamp=*/0, uids1, uid1_wl1, /*acquire=*/1);
+
+ // one matched start for uid1
+ vector<MatchingState> matcherState;
+ matcherState.push_back(MatchingState::kMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ vector<sp<ConditionTracker>> allPredicates;
+ vector<ConditionState> conditionCache(1, ConditionState::kNotEvaluated);
+ vector<bool> changedCache(1, false);
+
+ conditionTracker.evaluateCondition(event1, matcherState, allPredicates, conditionCache,
+ changedCache);
+
+ EXPECT_EQ(1UL, conditionTracker.mSlicedConditionState.size());
+ EXPECT_TRUE(changedCache[0]);
+
+ // Now test query
+ ConditionKey queryKey;
+ conditionCache[0] = ConditionState::kNotEvaluated;
+
+ conditionTracker.isConditionMet(queryKey, allPredicates, true, conditionCache);
+ EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
+
+ // another wake lock acquired by this uid
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event2, /*atomId=*/1, /*timestamp=*/0, uids2, uid2_wl1, /*acquire=*/1);
+
+ matcherState.clear();
+ matcherState.push_back(MatchingState::kMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ changedCache[0] = false;
+ conditionTracker.evaluateCondition(event2, matcherState, allPredicates, conditionCache,
+ changedCache);
+ EXPECT_FALSE(changedCache[0]);
+
+ // uid1 wake lock 1 release
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event3, /*atomId=*/1, /*timestamp=*/0, uids1, uid1_wl1,
+ /*release=*/0); // now release it.
+
+ matcherState.clear();
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kMatched);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ changedCache[0] = false;
+ conditionTracker.evaluateCondition(event3, matcherState, allPredicates, conditionCache,
+ changedCache);
+ // nothing changes, because uid2 is still holding wl.
+ EXPECT_FALSE(changedCache[0]);
+
+ LogEvent event4(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event4, /*atomId=*/1, /*timestamp=*/0, uids2, uid2_wl1,
+ /*acquire=*/0); // now release it.
+ matcherState.clear();
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kMatched);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ changedCache[0] = false;
+ conditionTracker.evaluateCondition(event4, matcherState, allPredicates, conditionCache,
+ changedCache);
+ EXPECT_EQ(0UL, conditionTracker.mSlicedConditionState.size());
+ EXPECT_TRUE(changedCache[0]);
+
+ // query again
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ conditionTracker.isConditionMet(queryKey, allPredicates, true, conditionCache);
+ EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
+}
+
+TEST(SimpleConditionTrackerTest, TestStopAll) {
+ std::vector<sp<ConditionTracker>> allConditions;
+ for (Position position : {Position::FIRST, Position::LAST}) {
+ SimplePredicate simplePredicate =
+ getWakeLockHeldCondition(true /*nesting*/, true /*default to false*/,
+ true /*output slice by uid*/, position);
+ string conditionName = "WL_HELD_BY_UID3";
+
+ unordered_map<int64_t, int> trackerNameIndexMap;
+ trackerNameIndexMap[StringToId("WAKE_LOCK_ACQUIRE")] = 0;
+ trackerNameIndexMap[StringToId("WAKE_LOCK_RELEASE")] = 1;
+ trackerNameIndexMap[StringToId("RELEASE_ALL")] = 2;
+
+ SimpleConditionTracker conditionTracker(kConfigKey, StringToId(conditionName),
+ 0 /*condition tracker index*/, simplePredicate,
+ trackerNameIndexMap);
+
+ std::vector<int> uids1 = {111, 1111, 11111};
+ std::vector<int> uids2 = {222, 2222, 22222};
+
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event1, /*atomId=*/1, /*timestamp=*/0, uids1, "wl1", /*acquire=*/1);
+
+ // one matched start
+ vector<MatchingState> matcherState;
+ matcherState.push_back(MatchingState::kMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ vector<sp<ConditionTracker>> allPredicates;
+ vector<ConditionState> conditionCache(1, ConditionState::kNotEvaluated);
+ vector<bool> changedCache(1, false);
+
+ conditionTracker.evaluateCondition(event1, matcherState, allPredicates, conditionCache,
+ changedCache);
+ if (position == Position::FIRST || position == Position::LAST) {
+ EXPECT_EQ(1UL, conditionTracker.mSlicedConditionState.size());
+ } else {
+ EXPECT_EQ(uids1.size(), conditionTracker.mSlicedConditionState.size());
+ }
+ EXPECT_TRUE(changedCache[0]);
+ {
+ if (position == Position::FIRST || position == Position::LAST) {
+ EXPECT_EQ(1UL, conditionTracker.getChangedToTrueDimensions(allConditions)->size());
+ EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
+ } else {
+ EXPECT_EQ(uids1.size(),
+ conditionTracker.getChangedToTrueDimensions(allConditions)->size());
+ EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
+ }
+ }
+
+ // Now test query
+ const auto queryKey = getWakeLockQueryKey(position, uids1, conditionName);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+
+ conditionTracker.isConditionMet(queryKey, allPredicates, false, conditionCache);
+ EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
+
+ // another wake lock acquired by uid2
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event2, /*atomId=*/1, /*timestamp=*/0, uids2, "wl2", /*acquire=*/1);
+
+ matcherState.clear();
+ matcherState.push_back(MatchingState::kMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ changedCache[0] = false;
+ conditionTracker.evaluateCondition(event2, matcherState, allPredicates, conditionCache,
+ changedCache);
+ if (position == Position::FIRST || position == Position::LAST) {
+ EXPECT_EQ(2UL, conditionTracker.mSlicedConditionState.size());
+ } else {
+ EXPECT_EQ(uids1.size() + uids2.size(), conditionTracker.mSlicedConditionState.size());
+ }
+ EXPECT_TRUE(changedCache[0]);
+ {
+ if (position == Position::FIRST || position == Position::LAST) {
+ EXPECT_EQ(1UL, conditionTracker.getChangedToTrueDimensions(allConditions)->size());
+ EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
+ } else {
+ EXPECT_EQ(uids2.size(),
+ conditionTracker.getChangedToTrueDimensions(allConditions)->size());
+ EXPECT_TRUE(conditionTracker.getChangedToFalseDimensions(allConditions)->empty());
+ }
+ }
+
+ // TEST QUERY
+ const auto queryKey2 = getWakeLockQueryKey(position, uids2, conditionName);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ conditionTracker.isConditionMet(queryKey, allPredicates, false, conditionCache);
+
+ EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
+
+ // stop all event
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeWakeLockEvent(&event3, /*atomId=*/1, /*timestamp=*/0, uids2, "wl2", /*acquire=*/1);
+
+ matcherState.clear();
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kNotMatched);
+ matcherState.push_back(MatchingState::kMatched);
+
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ changedCache[0] = false;
+ conditionTracker.evaluateCondition(event3, matcherState, allPredicates, conditionCache,
+ changedCache);
+ EXPECT_TRUE(changedCache[0]);
+ EXPECT_EQ(0UL, conditionTracker.mSlicedConditionState.size());
+ {
+ if (position == Position::FIRST || position == Position::LAST) {
+ EXPECT_EQ(2UL, conditionTracker.getChangedToFalseDimensions(allConditions)->size());
+ EXPECT_TRUE(conditionTracker.getChangedToTrueDimensions(allConditions)->empty());
+ } else {
+ EXPECT_EQ(uids1.size() + uids2.size(),
+ conditionTracker.getChangedToFalseDimensions(allConditions)->size());
+ EXPECT_TRUE(conditionTracker.getChangedToTrueDimensions(allConditions)->empty());
+ }
+ }
+
+ // TEST QUERY
+ const auto queryKey3 = getWakeLockQueryKey(position, uids1, conditionName);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ conditionTracker.isConditionMet(queryKey, allPredicates, false, conditionCache);
+ EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
+
+ // TEST QUERY
+ const auto queryKey4 = getWakeLockQueryKey(position, uids2, conditionName);
+ conditionCache[0] = ConditionState::kNotEvaluated;
+ conditionTracker.isConditionMet(queryKey, allPredicates, false, conditionCache);
+ EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
+ }
+}
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/tests/e2e/Anomaly_count_e2e_test.cpp b/cmds/statsd/tests/e2e/Anomaly_count_e2e_test.cpp
index 1eaaf08..e0eebef 100644
--- a/cmds/statsd/tests/e2e/Anomaly_count_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/Anomaly_count_e2e_test.cpp
@@ -53,185 +53,192 @@
} // namespace
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_single_bucket) {
-// const int num_buckets = 1;
-// const int threshold = 3;
-// auto config = CreateStatsdConfig(num_buckets, threshold);
-// const uint64_t alert_id = config.alert(0).id();
-// const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
-//
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
-//
-// sp<AnomalyTracker> anomalyTracker =
-// processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
-//
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1")};
-// std::vector<AttributionNodeInternal> attributions2 = {
-// CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1")};
-// std::vector<AttributionNodeInternal> attributions3 = {
-// CreateAttribution(111, "App1"), CreateAttribution(333, "App3")};
-// std::vector<AttributionNodeInternal> attributions4 = {
-// CreateAttribution(222, "GMSCoreModule1"), CreateAttribution(333, "App3")};
-// std::vector<AttributionNodeInternal> attributions5 = {
-// CreateAttribution(222, "GMSCoreModule1") };
-//
-// FieldValue fieldValue1(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
-// Value((int32_t)111));
-// HashableDimensionKey whatKey1({fieldValue1});
-// MetricDimensionKey dimensionKey1(whatKey1, DEFAULT_DIMENSION_KEY);
-//
-// FieldValue fieldValue2(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
-// Value((int32_t)222));
-// HashableDimensionKey whatKey2({fieldValue2});
-// MetricDimensionKey dimensionKey2(whatKey2, DEFAULT_DIMENSION_KEY);
-//
-// auto event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 2);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions4, "wl2", bucketStartTimeNs + 2);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// event = CreateAcquireWakelockEvent(attributions2, "wl1", bucketStartTimeNs + 3);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions5, "wl2", bucketStartTimeNs + 3);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// event = CreateAcquireWakelockEvent(attributions3, "wl1", bucketStartTimeNs + 4);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions5, "wl2", bucketStartTimeNs + 4);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// // Fired alarm and refractory period end timestamp updated.
-// event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 5);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + bucketStartTimeNs / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 100);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + bucketStartTimeNs / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + bucketSizeNs - 1);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs - 1) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + 1);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs - 1) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions4, "wl2", bucketStartTimeNs + bucketSizeNs + 1);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// event = CreateAcquireWakelockEvent(attributions5, "wl2", bucketStartTimeNs + bucketSizeNs + 2);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// event = CreateAcquireWakelockEvent(attributions5, "wl2", bucketStartTimeNs + bucketSizeNs + 3);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// event = CreateAcquireWakelockEvent(attributions5, "wl2", bucketStartTimeNs + bucketSizeNs + 4);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 4) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//}
-//
-//TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_multiple_buckets) {
-// const int num_buckets = 3;
-// const int threshold = 3;
-// auto config = CreateStatsdConfig(num_buckets, threshold);
-// const uint64_t alert_id = config.alert(0).id();
-// const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
-//
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
-//
-// sp<AnomalyTracker> anomalyTracker =
-// processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
-//
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1")};
-// std::vector<AttributionNodeInternal> attributions2 = {
-// CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1")};
-// std::vector<AttributionNodeInternal> attributions3 = {
-// CreateAttribution(111, "App1"), CreateAttribution(333, "App3")};
-// std::vector<AttributionNodeInternal> attributions4 = {
-// CreateAttribution(222, "GMSCoreModule1"), CreateAttribution(333, "App3")};
-// std::vector<AttributionNodeInternal> attributions5 = {
-// CreateAttribution(222, "GMSCoreModule1") };
-//
-// FieldValue fieldValue1(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
-// Value((int32_t)111));
-// HashableDimensionKey whatKey1({fieldValue1});
-// MetricDimensionKey dimensionKey1(whatKey1, DEFAULT_DIMENSION_KEY);
-//
-// FieldValue fieldValue2(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
-// Value((int32_t)222));
-// HashableDimensionKey whatKey2({fieldValue2});
-// MetricDimensionKey dimensionKey2(whatKey2, DEFAULT_DIMENSION_KEY);
-//
-// auto event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 2);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions2, "wl1", bucketStartTimeNs + 3);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// // Fired alarm and refractory period end timestamp updated.
-// event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 4);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + 1);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 1) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(attributions2, "wl1", bucketStartTimeNs + bucketSizeNs + 2);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 1) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 3 * bucketSizeNs + 1);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 1) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//
-// event = CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 3 * bucketSizeNs + 2);
-// processor->OnLogEvent(event.get());
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + 3 * bucketSizeNs + 2) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
-//}
+TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_single_bucket) {
+ const int num_buckets = 1;
+ const int threshold = 3;
+ auto config = CreateStatsdConfig(num_buckets, threshold);
+ const uint64_t alert_id = config.alert(0).id();
+ const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
+
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
+
+ sp<AnomalyTracker> anomalyTracker =
+ processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
+
+ std::vector<int> attributionUids1 = {111};
+ std::vector<string> attributionTags1 = {"App1"};
+ std::vector<int> attributionUids2 = {111, 222};
+ std::vector<string> attributionTags2 = {"App1", "GMSCoreModule1"};
+ std::vector<int> attributionUids3 = {111, 333};
+ std::vector<string> attributionTags3 = {"App1", "App3"};
+ std::vector<int> attributionUids4 = {222, 333};
+ std::vector<string> attributionTags4 = {"GMSCoreModule1", "App3"};
+ std::vector<int> attributionUids5 = {222};
+ std::vector<string> attributionTags5 = {"GMSCoreModule1"};
+
+ FieldValue fieldValue1(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
+ Value((int32_t)111));
+ HashableDimensionKey whatKey1({fieldValue1});
+ MetricDimensionKey dimensionKey1(whatKey1, DEFAULT_DIMENSION_KEY);
+
+ FieldValue fieldValue2(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
+ Value((int32_t)222));
+ HashableDimensionKey whatKey2({fieldValue2});
+ MetricDimensionKey dimensionKey2(whatKey2, DEFAULT_DIMENSION_KEY);
+
+ auto event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids4, attributionTags4,
+ "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 3, attributionUids2, attributionTags2,
+ "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 3, attributionUids5, attributionTags5,
+ "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 4, attributionUids3, attributionTags3,
+ "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 4, attributionUids5, attributionTags5,
+ "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ // Fired alarm and refractory period end timestamp updated.
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 5, attributionUids1, attributionTags1,
+ "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + bucketStartTimeNs / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 100, attributionUids1, attributionTags1,
+ "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + bucketStartTimeNs / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 1, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs - 1) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 1, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs - 1) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 1, attributionUids4,
+ attributionTags4, "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 2, attributionUids5,
+ attributionTags5, "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 3, attributionUids5,
+ attributionTags5, "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 4, attributionUids5,
+ attributionTags5, "wl2");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 4) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+}
+
+TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_multiple_buckets) {
+ const int num_buckets = 3;
+ const int threshold = 3;
+ auto config = CreateStatsdConfig(num_buckets, threshold);
+ const uint64_t alert_id = config.alert(0).id();
+ const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
+
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
+
+ sp<AnomalyTracker> anomalyTracker =
+ processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
+
+ std::vector<int> attributionUids1 = {111};
+ std::vector<string> attributionTags1 = {"App1"};
+ std::vector<int> attributionUids2 = {111, 222};
+ std::vector<string> attributionTags2 = {"App1", "GMSCoreModule1"};
+
+ FieldValue fieldValue1(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
+ Value((int32_t)111));
+ HashableDimensionKey whatKey1({fieldValue1});
+ MetricDimensionKey dimensionKey1(whatKey1, DEFAULT_DIMENSION_KEY);
+
+ auto event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 3, attributionUids2, attributionTags2,
+ "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Fired alarm and refractory period end timestamp updated.
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 4, attributionUids1, attributionTags1,
+ "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 1, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 1) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 2, attributionUids2,
+ attributionTags2, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 1) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs + 1, attributionUids2,
+ attributionTags2, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + 1) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs + 2, attributionUids2,
+ attributionTags2, "wl1");
+ processor->OnLogEvent(event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + 3 * bucketSizeNs + 2) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/Anomaly_duration_sum_e2e_test.cpp b/cmds/statsd/tests/e2e/Anomaly_duration_sum_e2e_test.cpp
index 03a209a..fe45b55 100644
--- a/cmds/statsd/tests/e2e/Anomaly_duration_sum_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/Anomaly_duration_sum_e2e_test.cpp
@@ -69,414 +69,432 @@
return config;
}
-} // namespace
+std::vector<int> attributionUids1 = {111, 222};
+std::vector<string> attributionTags1 = {"App1", "GMSCoreModule1"};
-std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1"),
- CreateAttribution(222, "GMSCoreModule1")};
+std::vector<int> attributionUids2 = {111, 222};
+std::vector<string> attributionTags2 = {"App2", "GMSCoreModule1"};
-std::vector<AttributionNodeInternal> attributions2 = {CreateAttribution(111, "App2"),
- CreateAttribution(222, "GMSCoreModule1")};
+std::vector<int> attributionUids3 = {222};
+std::vector<string> attributionTags3 = {"GMSCoreModule1"};
-std::vector<AttributionNodeInternal> attributions3 = {CreateAttribution(222, "GMSCoreModule1")};
-
-MetricDimensionKey dimensionKey(
- HashableDimensionKey({FieldValue(Field(android::util::WAKELOCK_STATE_CHANGED,
- (int32_t)0x02010101), Value((int32_t)111))}),
- DEFAULT_DIMENSION_KEY);
+MetricDimensionKey dimensionKey1(
+ HashableDimensionKey({FieldValue(Field(android::util::WAKELOCK_STATE_CHANGED,
+ (int32_t)0x02010101),
+ Value((int32_t)111))}),
+ DEFAULT_DIMENSION_KEY);
MetricDimensionKey dimensionKey2(
HashableDimensionKey({FieldValue(Field(android::util::WAKELOCK_STATE_CHANGED,
(int32_t)0x02010101), Value((int32_t)222))}),
DEFAULT_DIMENSION_KEY);
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_single_bucket) {
-// const int num_buckets = 1;
-// const uint64_t threshold_ns = NS_PER_SEC;
-// auto config = CreateStatsdConfig(num_buckets, threshold_ns, DurationMetric::SUM, true);
-// const uint64_t alert_id = config.alert(0).id();
-// const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
-//
-// int64_t bucketStartTimeNs = 10 * NS_PER_SEC;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
-//
-// sp<AnomalyTracker> anomalyTracker =
-// processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
-//
-// auto screen_on_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_ON, bucketStartTimeNs + 1);
-// auto screen_off_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF, bucketStartTimeNs + 10);
-// processor->OnLogEvent(screen_on_event.get());
-// processor->OnLogEvent(screen_off_event.get());
-//
-// // Acquire wakelock wl1.
-// auto acquire_event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 11);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 11 + threshold_ns) / NS_PER_SEC + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Release wakelock wl1. No anomaly detected. Alarm cancelled at the "release" event.
-// auto release_event = CreateReleaseWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 101);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Acquire wakelock wl1 within bucket #0.
-// acquire_event = CreateAcquireWakelockEvent(attributions2, "wl1", bucketStartTimeNs + 110);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 110 + threshold_ns - 90) / NS_PER_SEC + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Release wakelock wl1. One anomaly detected.
-// release_event = CreateReleaseWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + NS_PER_SEC + 109);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + NS_PER_SEC + 109) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Acquire wakelock wl1.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + NS_PER_SEC + 112);
-// processor->OnLogEvent(acquire_event.get());
-// // Wakelock has been hold longer than the threshold in bucket #0. The alarm is set at the
-// // end of the refractory period.
-// const int64_t alarmFiredTimestampSec0 = anomalyTracker->getAlarmTimestampSec(dimensionKey);
-// EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + NS_PER_SEC + 109) / NS_PER_SEC + 1,
-// (uint32_t)alarmFiredTimestampSec0);
-//
-// // Anomaly alarm fired.
-// auto alarmSet = processor->getAnomalyAlarmMonitor()->popSoonerThan(
-// static_cast<uint32_t>(alarmFiredTimestampSec0));
-// EXPECT_EQ(1u, alarmSet.size());
-// processor->onAnomalyAlarmFired(alarmFiredTimestampSec0 * NS_PER_SEC, alarmSet);
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec + alarmFiredTimestampSec0,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Release wakelock wl1.
-// release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", alarmFiredTimestampSec0 * NS_PER_SEC + NS_PER_SEC + 1);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// // Within refractory period. No more anomaly detected.
-// EXPECT_EQ(refractory_period_sec + alarmFiredTimestampSec0,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Acquire wakelock wl1.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + bucketSizeNs - 5 * NS_PER_SEC - 11);
-// processor->OnLogEvent(acquire_event.get());
-// const int64_t alarmFiredTimestampSec1 = anomalyTracker->getAlarmTimestampSec(dimensionKey);
-// EXPECT_EQ((bucketStartTimeNs + bucketSizeNs - 5 * NS_PER_SEC) / NS_PER_SEC,
-// (uint64_t)alarmFiredTimestampSec1);
-//
-// // Release wakelock wl1.
-// release_event = CreateReleaseWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + bucketSizeNs - 4 * NS_PER_SEC - 10);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + bucketSizeNs - 4 * NS_PER_SEC - 10) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// alarmSet = processor->getAnomalyAlarmMonitor()->popSoonerThan(
-// static_cast<uint32_t>(alarmFiredTimestampSec1));
-// EXPECT_EQ(0u, alarmSet.size());
-//
-// // Acquire wakelock wl1 near the end of bucket #0.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + bucketSizeNs - 2);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// // Release the event at early bucket #1.
-// release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + NS_PER_SEC - 1);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// // Anomaly detected when stopping the alarm. The refractory period does not change.
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + bucketSizeNs + NS_PER_SEC) / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Condition changes to false.
-// screen_on_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 2 * bucketSizeNs + 20);
-// processor->OnLogEvent(screen_on_event.get());
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + bucketSizeNs + NS_PER_SEC) / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 2 * bucketSizeNs + 30);
-// processor->OnLogEvent(acquire_event.get());
-// // The condition is false. Do not start the alarm.
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + bucketSizeNs + NS_PER_SEC) / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Condition turns true.
-// screen_off_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 2 * bucketSizeNs + NS_PER_SEC);
-// processor->OnLogEvent(screen_off_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs + NS_PER_SEC + threshold_ns) / NS_PER_SEC,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// // Condition turns to false.
-// screen_on_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC + 1);
-// processor->OnLogEvent(screen_on_event.get());
-// // Condition turns to false. Cancelled the alarm.
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// // Detected one anomaly.
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC + 1) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Condition turns to true again.
-// screen_off_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC + 2);
-// processor->OnLogEvent(screen_off_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs) / NS_PER_SEC + 2 + 2 + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// release_event = CreateReleaseWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 2 * bucketSizeNs + 5 * NS_PER_SEC);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + 2 * bucketSizeNs + 5 * NS_PER_SEC) / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//}
-//
-//TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_multiple_buckets) {
-// const int num_buckets = 3;
-// const uint64_t threshold_ns = NS_PER_SEC;
-// auto config = CreateStatsdConfig(num_buckets, threshold_ns, DurationMetric::SUM, true);
-// const uint64_t alert_id = config.alert(0).id();
-// const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
-//
-// int64_t bucketStartTimeNs = 10 * NS_PER_SEC;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
-//
-// sp<AnomalyTracker> anomalyTracker =
-// processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
-//
-// auto screen_off_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF, bucketStartTimeNs + 1);
-// processor->OnLogEvent(screen_off_event.get());
-//
-// // Acquire wakelock "wc1" in bucket #0.
-// auto acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + bucketSizeNs - NS_PER_SEC / 2 - 1);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Release wakelock "wc1" in bucket #0.
-// auto release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + bucketSizeNs - 1);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Acquire wakelock "wc1" in bucket #1.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + bucketSizeNs + 1);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// release_event = CreateReleaseWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + bucketSizeNs + 100);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Acquire wakelock "wc2" in bucket #2.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions3, "wl2", bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs) / NS_PER_SEC + 2,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey2));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// // Release wakelock "wc2" in bucket #2.
-// release_event = CreateReleaseWakelockEvent(
-// attributions3, "wl2", bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey2));
-// EXPECT_EQ(refractory_period_sec +
-// (bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC) / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
-//
-// // Acquire wakelock "wc1" in bucket #2.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs) / NS_PER_SEC + 2 + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Release wakelock "wc1" in bucket #2.
-// release_event = CreateReleaseWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 2 * bucketSizeNs + 2.5 * NS_PER_SEC);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec +
-// (int64_t)(bucketStartTimeNs + 2 * bucketSizeNs + 2.5 * NS_PER_SEC) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions3, "wl2", bucketStartTimeNs + 6 * bucketSizeNs - NS_PER_SEC + 4);
-// processor->OnLogEvent(acquire_event.get());
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 6 * bucketSizeNs - NS_PER_SEC + 5);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 6 * bucketSizeNs) / NS_PER_SEC + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ((bucketStartTimeNs + 6 * bucketSizeNs) / NS_PER_SEC + 1,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey2));
-//
-// release_event = CreateReleaseWakelockEvent(
-// attributions3, "wl2", bucketStartTimeNs + 6 * bucketSizeNs + 2);
-// processor->OnLogEvent(release_event.get());
-// release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 6 * bucketSizeNs + 6);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey2));
-// // The buckets are not messed up across dimensions. Only one dimension has anomaly triggered.
-// EXPECT_EQ(refractory_period_sec +
-// (int64_t)(bucketStartTimeNs + 6 * bucketSizeNs) / NS_PER_SEC + 1,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//}
-//
-//TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_long_refractory_period) {
-// const int num_buckets = 2;
-// const uint64_t threshold_ns = 3 * NS_PER_SEC;
-// auto config = CreateStatsdConfig(num_buckets, threshold_ns, DurationMetric::SUM, false);
-// int64_t bucketStartTimeNs = 10 * NS_PER_SEC;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000;
-//
-// const uint64_t alert_id = config.alert(0).id();
-// const uint32_t refractory_period_sec = 3 * bucketSizeNs / NS_PER_SEC;
-// config.mutable_alert(0)->set_refractory_period_secs(refractory_period_sec);
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
-//
-// sp<AnomalyTracker> anomalyTracker =
-// processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
-//
-// auto screen_off_event = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF, bucketStartTimeNs + 1);
-// processor->OnLogEvent(screen_off_event.get());
-//
-// // Acquire wakelock "wc1" in bucket #0.
-// auto acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + bucketSizeNs - 100);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 3,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Acquire the wakelock "wc1" again.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + 2 * NS_PER_SEC + 1);
-// processor->OnLogEvent(acquire_event.get());
-// // The alarm does not change.
-// EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 3,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // Anomaly alarm fired late.
-// const int64_t firedAlarmTimestampNs = bucketStartTimeNs + 2 * bucketSizeNs - NS_PER_SEC;
-// auto alarmSet = processor->getAnomalyAlarmMonitor()->popSoonerThan(
-// static_cast<uint32_t>(firedAlarmTimestampNs / NS_PER_SEC));
-// EXPECT_EQ(1u, alarmSet.size());
-// processor->onAnomalyAlarmFired(firedAlarmTimestampNs, alarmSet);
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 2 * bucketSizeNs - 100);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// auto release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-// // Within the refractory period. No anomaly.
-// EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// // A new wakelock, but still within refractory period.
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 2 * bucketSizeNs + 10 * NS_PER_SEC);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 3 * bucketSizeNs - NS_PER_SEC);
-// // Still in the refractory period. No anomaly.
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
-// anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey));
-//
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 5 * bucketSizeNs - 3 * NS_PER_SEC - 5);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 5 * bucketSizeNs) / NS_PER_SEC,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// release_event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 5 * bucketSizeNs - 3 * NS_PER_SEC - 4);
-// processor->OnLogEvent(release_event.get());
-// EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//
-// acquire_event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 5 * bucketSizeNs - 3 * NS_PER_SEC - 3);
-// processor->OnLogEvent(acquire_event.get());
-// EXPECT_EQ((bucketStartTimeNs + 5 * bucketSizeNs) / NS_PER_SEC,
-// anomalyTracker->getAlarmTimestampSec(dimensionKey));
-//}
+} // namespace
+
+TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_single_bucket) {
+ const int num_buckets = 1;
+ const uint64_t threshold_ns = NS_PER_SEC;
+ auto config = CreateStatsdConfig(num_buckets, threshold_ns, DurationMetric::SUM, true);
+ const uint64_t alert_id = config.alert(0).id();
+ const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
+
+ int64_t bucketStartTimeNs = 10 * NS_PER_SEC;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
+
+ sp<AnomalyTracker> anomalyTracker =
+ processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
+
+ auto screen_on_event = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 1, android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+ auto screen_off_event = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 10, android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screen_on_event.get());
+ processor->OnLogEvent(screen_off_event.get());
+
+ // Acquire wakelock wl1.
+ auto acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + 11, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 11 + threshold_ns) / NS_PER_SEC + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Release wakelock wl1. No anomaly detected. Alarm cancelled at the "release" event.
+ auto release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + 101, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Acquire wakelock wl1 within bucket #0.
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + 110, attributionUids2,
+ attributionTags2, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 110 + threshold_ns - 90) / NS_PER_SEC + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Release wakelock wl1. One anomaly detected.
+ release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + NS_PER_SEC + 109,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + NS_PER_SEC + 109) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Acquire wakelock wl1.
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + NS_PER_SEC + 112,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ // Wakelock has been hold longer than the threshold in bucket #0. The alarm is set at the
+ // end of the refractory period.
+ const int64_t alarmFiredTimestampSec0 = anomalyTracker->getAlarmTimestampSec(dimensionKey1);
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + NS_PER_SEC + 109) / NS_PER_SEC + 1,
+ (uint32_t)alarmFiredTimestampSec0);
+
+ // Anomaly alarm fired.
+ auto alarmSet = processor->getAnomalyAlarmMonitor()->popSoonerThan(
+ static_cast<uint32_t>(alarmFiredTimestampSec0));
+ EXPECT_EQ(1u, alarmSet.size());
+ processor->onAnomalyAlarmFired(alarmFiredTimestampSec0 * NS_PER_SEC, alarmSet);
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec + alarmFiredTimestampSec0,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Release wakelock wl1.
+ release_event =
+ CreateReleaseWakelockEvent(alarmFiredTimestampSec0 * NS_PER_SEC + NS_PER_SEC + 1,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ // Within refractory period. No more anomaly detected.
+ EXPECT_EQ(refractory_period_sec + alarmFiredTimestampSec0,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Acquire wakelock wl1.
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 5 * NS_PER_SEC - 11,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ const int64_t alarmFiredTimestampSec1 = anomalyTracker->getAlarmTimestampSec(dimensionKey1);
+ EXPECT_EQ((bucketStartTimeNs + bucketSizeNs - 5 * NS_PER_SEC) / NS_PER_SEC,
+ (uint64_t)alarmFiredTimestampSec1);
+
+ // Release wakelock wl1.
+ release_event =
+ CreateReleaseWakelockEvent(bucketStartTimeNs + bucketSizeNs - 4 * NS_PER_SEC - 10,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec +
+ (bucketStartTimeNs + bucketSizeNs - 4 * NS_PER_SEC - 10) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ alarmSet = processor->getAnomalyAlarmMonitor()->popSoonerThan(
+ static_cast<uint32_t>(alarmFiredTimestampSec1));
+ EXPECT_EQ(0u, alarmSet.size());
+
+ // Acquire wakelock wl1 near the end of bucket #0.
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 2,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ // Release the event at early bucket #1.
+ release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + bucketSizeNs + NS_PER_SEC - 1,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ // Anomaly detected when stopping the alarm. The refractory period does not change.
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + NS_PER_SEC) / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Condition changes to false.
+ screen_on_event =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs + 20,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screen_on_event.get());
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + NS_PER_SEC) / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 30,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ // The condition is false. Do not start the alarm.
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec + (bucketStartTimeNs + bucketSizeNs + NS_PER_SEC) / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Condition turns true.
+ screen_off_event =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs + NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screen_off_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs + NS_PER_SEC + threshold_ns) / NS_PER_SEC,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ // Condition turns to false.
+ screen_on_event =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC + 1,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screen_on_event.get());
+ // Condition turns to false. Cancelled the alarm.
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ // Detected one anomaly.
+ EXPECT_EQ(refractory_period_sec +
+ (bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC + 1) / NS_PER_SEC + 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Condition turns to true again.
+ screen_off_event =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC + 2,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screen_off_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs) / NS_PER_SEC + 2 + 2 + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ release_event =
+ CreateReleaseWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 5 * NS_PER_SEC,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(refractory_period_sec +
+ (bucketStartTimeNs + 2 * bucketSizeNs + 5 * NS_PER_SEC) / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+}
+
+TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_multiple_buckets) {
+ const int num_buckets = 3;
+ const uint64_t threshold_ns = NS_PER_SEC;
+ auto config = CreateStatsdConfig(num_buckets, threshold_ns, DurationMetric::SUM, true);
+ const uint64_t alert_id = config.alert(0).id();
+ const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
+
+ int64_t bucketStartTimeNs = 10 * NS_PER_SEC;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
+
+ sp<AnomalyTracker> anomalyTracker =
+ processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
+
+ auto screen_off_event = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 1, android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screen_off_event.get());
+
+ // Acquire wakelock "wc1" in bucket #0.
+ auto acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - NS_PER_SEC / 2 - 1,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Release wakelock "wc1" in bucket #0.
+ auto release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + bucketSizeNs - 1,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Acquire wakelock "wc1" in bucket #1.
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 1,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + bucketSizeNs + 100,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Acquire wakelock "wc2" in bucket #2.
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 1,
+ attributionUids3, attributionTags3, "wl2");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs) / NS_PER_SEC + 2,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey2));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ // Release wakelock "wc2" in bucket #2.
+ release_event =
+ CreateReleaseWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC,
+ attributionUids3, attributionTags3, "wl2");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey2));
+ EXPECT_EQ(refractory_period_sec +
+ (bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC) / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey2));
+
+ // Acquire wakelock "wc1" in bucket #2.
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 2 * NS_PER_SEC,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 2 * bucketSizeNs) / NS_PER_SEC + 2 + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Release wakelock "wc1" in bucket #2.
+ release_event =
+ CreateReleaseWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 2.5 * NS_PER_SEC,
+ attributionUids2, attributionTags2, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec +
+ (int64_t)(bucketStartTimeNs + 2 * bucketSizeNs + 2.5 * NS_PER_SEC) /
+ NS_PER_SEC +
+ 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + 6 * bucketSizeNs - NS_PER_SEC + 4,
+ attributionUids3, attributionTags3, "wl2");
+ processor->OnLogEvent(acquire_event.get());
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + 6 * bucketSizeNs - NS_PER_SEC + 5,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 6 * bucketSizeNs) / NS_PER_SEC + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ((bucketStartTimeNs + 6 * bucketSizeNs) / NS_PER_SEC + 1,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey2));
+
+ release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + 6 * bucketSizeNs + 2,
+ attributionUids3, attributionTags3, "wl2");
+ processor->OnLogEvent(release_event.get());
+ release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + 6 * bucketSizeNs + 6,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey2));
+ // The buckets are not messed up across dimensions. Only one dimension has anomaly triggered.
+ EXPECT_EQ(refractory_period_sec + (int64_t)(bucketStartTimeNs + 6 * bucketSizeNs) / NS_PER_SEC +
+ 1,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+}
+
+TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_long_refractory_period) {
+ const int num_buckets = 2;
+ const uint64_t threshold_ns = 3 * NS_PER_SEC;
+ auto config = CreateStatsdConfig(num_buckets, threshold_ns, DurationMetric::SUM, false);
+ int64_t bucketStartTimeNs = 10 * NS_PER_SEC;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000;
+
+ const uint64_t alert_id = config.alert(0).id();
+ const uint32_t refractory_period_sec = 3 * bucketSizeNs / NS_PER_SEC;
+ config.mutable_alert(0)->set_refractory_period_secs(refractory_period_sec);
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ EXPECT_EQ(1u, processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers.size());
+
+ sp<AnomalyTracker> anomalyTracker =
+ processor->mMetricsManagers.begin()->second->mAllAnomalyTrackers[0];
+
+ auto screen_off_event = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 1, android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screen_off_event.get());
+
+ // Acquire wakelock "wc1" in bucket #0.
+ auto acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 100,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 3,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Acquire the wakelock "wc1" again.
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 2 * NS_PER_SEC + 1,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ // The alarm does not change.
+ EXPECT_EQ((bucketStartTimeNs + bucketSizeNs) / NS_PER_SEC + 3,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(0u, anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // Anomaly alarm fired late.
+ const int64_t firedAlarmTimestampNs = bucketStartTimeNs + 2 * bucketSizeNs - NS_PER_SEC;
+ auto alarmSet = processor->getAnomalyAlarmMonitor()->popSoonerThan(
+ static_cast<uint32_t>(firedAlarmTimestampNs / NS_PER_SEC));
+ EXPECT_EQ(1u, alarmSet.size());
+ processor->onAnomalyAlarmFired(firedAlarmTimestampNs, alarmSet);
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ acquire_event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs - 100,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ auto release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 1,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+ // Within the refractory period. No anomaly.
+ EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ // A new wakelock, but still within refractory period.
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 10 * NS_PER_SEC,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ release_event = CreateReleaseWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs - NS_PER_SEC,
+ attributionUids1, attributionTags1, "wl1");
+ // Still in the refractory period. No anomaly.
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(refractory_period_sec + firedAlarmTimestampNs / NS_PER_SEC,
+ anomalyTracker->getRefractoryPeriodEndsSec(dimensionKey1));
+
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + 5 * bucketSizeNs - 3 * NS_PER_SEC - 5,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 5 * bucketSizeNs) / NS_PER_SEC,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ release_event =
+ CreateReleaseWakelockEvent(bucketStartTimeNs + 5 * bucketSizeNs - 3 * NS_PER_SEC - 4,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(release_event.get());
+ EXPECT_EQ(0u, anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+
+ acquire_event =
+ CreateAcquireWakelockEvent(bucketStartTimeNs + 5 * bucketSizeNs - 3 * NS_PER_SEC - 3,
+ attributionUids1, attributionTags1, "wl1");
+ processor->OnLogEvent(acquire_event.get());
+ EXPECT_EQ((bucketStartTimeNs + 5 * bucketSizeNs) / NS_PER_SEC,
+ anomalyTracker->getAlarmTimestampSec(dimensionKey1));
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/Attribution_e2e_test.cpp b/cmds/statsd/tests/e2e/Attribution_e2e_test.cpp
index 6051174..9e743f7 100644
--- a/cmds/statsd/tests/e2e/Attribution_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/Attribution_e2e_test.cpp
@@ -53,367 +53,318 @@
return config;
}
+// GMS core node is in the middle.
+std::vector<int> attributionUids1 = {111, 222, 333};
+std::vector<string> attributionTags1 = {"App1", "GMSCoreModule1", "App3"};
+
+// GMS core node is the last one.
+std::vector<int> attributionUids2 = {111, 333, 222};
+std::vector<string> attributionTags2 = {"App1", "App3", "GMSCoreModule1"};
+
+// GMS core node is the first one.
+std::vector<int> attributionUids3 = {222, 333};
+std::vector<string> attributionTags3 = {"GMSCoreModule1", "App3"};
+
+// Single GMS core node.
+std::vector<int> attributionUids4 = {222};
+std::vector<string> attributionTags4 = {"GMSCoreModule1"};
+
+// GMS core has another uid.
+std::vector<int> attributionUids5 = {111, 444, 333};
+std::vector<string> attributionTags5 = {"App1", "GMSCoreModule2", "App3"};
+
+// Multiple GMS core nodes.
+std::vector<int> attributionUids6 = {444, 222};
+std::vector<string> attributionTags6 = {"GMSCoreModule2", "GMSCoreModule1"};
+
+// No GMS core nodes
+std::vector<int> attributionUids7 = {111, 333};
+std::vector<string> attributionTags7 = {"App1", "App3"};
+
+std::vector<int> attributionUids8 = {111};
+std::vector<string> attributionTags8 = {"App1"};
+
+// GMS core node with isolated uid.
+const int isolatedUid = 666;
+std::vector<int> attributionUids9 = {isolatedUid};
+std::vector<string> attributionTags9 = {"GMSCoreModule3"};
+
+std::vector<int> attributionUids10 = {isolatedUid};
+std::vector<string> attributionTags10 = {"GMSCoreModule1"};
+
} // namespace
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(AttributionE2eTest, TestAttributionMatchAndSliceByFirstUid) {
-// auto config = CreateStatsdConfig(Position::FIRST);
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-//
-// // Here it assumes that GMS core has two uids.
-// processor->getUidMap()->updateMap(
-// 1, {222, 444, 111, 333}, {1, 1, 2, 2},
-// {String16("v1"), String16("v1"), String16("v2"), String16("v2")},
-// {String16("com.android.gmscore"), String16("com.android.gmscore"), String16("app1"),
-// String16("APP3")},
-// {String16(""), String16(""), String16(""), String16("")});
-//
-// // GMS core node is in the middle.
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1"),
-// CreateAttribution(222, "GMSCoreModule1"),
-// CreateAttribution(333, "App3")};
-//
-// // GMS core node is the last one.
-// std::vector<AttributionNodeInternal> attributions2 = {CreateAttribution(111, "App1"),
-// CreateAttribution(333, "App3"),
-// CreateAttribution(222, "GMSCoreModule1")};
-//
-// // GMS core node is the first one.
-// std::vector<AttributionNodeInternal> attributions3 = {CreateAttribution(222, "GMSCoreModule1"),
-// CreateAttribution(333, "App3")};
-//
-// // Single GMS core node.
-// std::vector<AttributionNodeInternal> attributions4 = {CreateAttribution(222, "GMSCoreModule1")};
-//
-// // GMS core has another uid.
-// std::vector<AttributionNodeInternal> attributions5 = {CreateAttribution(111, "App1"),
-// CreateAttribution(444, "GMSCoreModule2"),
-// CreateAttribution(333, "App3")};
-//
-// // Multiple GMS core nodes.
-// std::vector<AttributionNodeInternal> attributions6 = {CreateAttribution(444, "GMSCoreModule2"),
-// CreateAttribution(222, "GMSCoreModule1")};
-//
-// // No GMS core nodes.
-// std::vector<AttributionNodeInternal> attributions7 = {CreateAttribution(111, "App1"),
-// CreateAttribution(333, "App3")};
-// std::vector<AttributionNodeInternal> attributions8 = {CreateAttribution(111, "App1")};
-//
-// // GMS core node with isolated uid.
-// const int isolatedUid = 666;
-// std::vector<AttributionNodeInternal> attributions9 = {
-// CreateAttribution(isolatedUid, "GMSCoreModule3")};
-//
-// std::vector<std::unique_ptr<LogEvent>> events;
-// // Events 1~4 are in the 1st bucket.
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 2));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 200));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions3, "wl1", bucketStartTimeNs + bucketSizeNs - 1));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions4, "wl1", bucketStartTimeNs + bucketSizeNs));
-//
-// // Events 5~8 are in the 3rd bucket.
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions5, "wl2", bucketStartTimeNs + 2 * bucketSizeNs + 1));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions6, "wl2", bucketStartTimeNs + 2 * bucketSizeNs + 100));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions7, "wl2", bucketStartTimeNs + 3 * bucketSizeNs - 2));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions8, "wl2", bucketStartTimeNs + 3 * bucketSizeNs));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions9, "wl2", bucketStartTimeNs + 3 * bucketSizeNs + 1));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions9, "wl2", bucketStartTimeNs + 3 * bucketSizeNs + 100));
-// events.push_back(CreateIsolatedUidChangedEvent(
-// isolatedUid, 222, true/* is_create*/, bucketStartTimeNs + 3 * bucketSizeNs - 1));
-// events.push_back(CreateIsolatedUidChangedEvent(
-// isolatedUid, 222, false/* is_create*/, bucketStartTimeNs + 3 * bucketSizeNs + 10));
-//
-// sortLogEventsByTimestamp(&events);
-//
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 4 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-// sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(countMetrics.data_size(), 4);
-//
-// auto data = countMetrics.data(0);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), android::util::WAKELOCK_STATE_CHANGED, 111,
-// "App1");
-// EXPECT_EQ(data.bucket_info_size(), 2);
-// EXPECT_EQ(data.bucket_info(0).count(), 2);
-// EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
-// EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-// EXPECT_EQ(data.bucket_info(1).count(), 1);
-// EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
-// EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(), bucketStartTimeNs + 3 * bucketSizeNs);
-//
-// data = countMetrics.data(1);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), android::util::WAKELOCK_STATE_CHANGED, 222,
-// "GMSCoreModule1");
-// EXPECT_EQ(data.bucket_info_size(), 2);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
-// EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-// EXPECT_EQ(data.bucket_info(1).count(), 1);
-// EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-// EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
-//
-// data = countMetrics.data(2);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), android::util::WAKELOCK_STATE_CHANGED, 222,
-// "GMSCoreModule3");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs + 3 * bucketSizeNs);
-// EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + 4 * bucketSizeNs);
-//
-// data = countMetrics.data(3);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), android::util::WAKELOCK_STATE_CHANGED, 444,
-// "GMSCoreModule2");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
-// EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + 3 * bucketSizeNs);
-//}
-//
-//TEST(AttributionE2eTest, TestAttributionMatchAndSliceByChain) {
-// auto config = CreateStatsdConfig(Position::ALL);
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-//
-// // Here it assumes that GMS core has two uids.
-// processor->getUidMap()->updateMap(
-// 1, {222, 444, 111, 333}, {1, 1, 2, 2},
-// {String16("v1"), String16("v1"), String16("v2"), String16("v2")},
-// {String16("com.android.gmscore"), String16("com.android.gmscore"), String16("app1"),
-// String16("APP3")},
-// {String16(""), String16(""), String16(""), String16("")});
-//
-// // GMS core node is in the middle.
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1"),
-// CreateAttribution(222, "GMSCoreModule1"),
-// CreateAttribution(333, "App3")};
-//
-// // GMS core node is the last one.
-// std::vector<AttributionNodeInternal> attributions2 = {CreateAttribution(111, "App1"),
-// CreateAttribution(333, "App3"),
-// CreateAttribution(222, "GMSCoreModule1")};
-//
-// // GMS core node is the first one.
-// std::vector<AttributionNodeInternal> attributions3 = {CreateAttribution(222, "GMSCoreModule1"),
-// CreateAttribution(333, "App3")};
-//
-// // Single GMS core node.
-// std::vector<AttributionNodeInternal> attributions4 = {CreateAttribution(222, "GMSCoreModule1")};
-//
-// // GMS core has another uid.
-// std::vector<AttributionNodeInternal> attributions5 = {CreateAttribution(111, "App1"),
-// CreateAttribution(444, "GMSCoreModule2"),
-// CreateAttribution(333, "App3")};
-//
-// // Multiple GMS core nodes.
-// std::vector<AttributionNodeInternal> attributions6 = {CreateAttribution(444, "GMSCoreModule2"),
-// CreateAttribution(222, "GMSCoreModule1")};
-//
-// // No GMS core nodes.
-// std::vector<AttributionNodeInternal> attributions7 = {CreateAttribution(111, "App1"),
-// CreateAttribution(333, "App3")};
-// std::vector<AttributionNodeInternal> attributions8 = {CreateAttribution(111, "App1")};
-//
-// // GMS core node with isolated uid.
-// const int isolatedUid = 666;
-// std::vector<AttributionNodeInternal> attributions9 = {
-// CreateAttribution(isolatedUid, "GMSCoreModule1")};
-//
-// std::vector<std::unique_ptr<LogEvent>> events;
-// // Events 1~4 are in the 1st bucket.
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 2));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions2, "wl1", bucketStartTimeNs + 200));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions3, "wl1", bucketStartTimeNs + bucketSizeNs - 1));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions4, "wl1", bucketStartTimeNs + bucketSizeNs));
-//
-// // Events 5~8 are in the 3rd bucket.
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions5, "wl2", bucketStartTimeNs + 2 * bucketSizeNs + 1));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions6, "wl2", bucketStartTimeNs + 2 * bucketSizeNs + 100));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions7, "wl2", bucketStartTimeNs + 3 * bucketSizeNs - 2));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions8, "wl2", bucketStartTimeNs + 3 * bucketSizeNs));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions9, "wl2", bucketStartTimeNs + 3 * bucketSizeNs + 1));
-// events.push_back(CreateAcquireWakelockEvent(
-// attributions9, "wl2", bucketStartTimeNs + 3 * bucketSizeNs + 100));
-// events.push_back(CreateIsolatedUidChangedEvent(
-// isolatedUid, 222, true/* is_create*/, bucketStartTimeNs + 3 * bucketSizeNs - 1));
-// events.push_back(CreateIsolatedUidChangedEvent(
-// isolatedUid, 222, false/* is_create*/, bucketStartTimeNs + 3 * bucketSizeNs + 10));
-//
-// sortLogEventsByTimestamp(&events);
-//
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 4 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-// sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(countMetrics.data_size(), 6);
-//
-// auto data = countMetrics.data(0);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), android::util::WAKELOCK_STATE_CHANGED, 222, "GMSCoreModule1");
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(1).count());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 4 * bucketSizeNs,
-// data.bucket_info(1).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// ValidateUidDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 222);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 222, "GMSCoreModule1");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 333);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
-// EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-//
-// data = countMetrics.data(2);
-// ValidateUidDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 444);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 444, "GMSCoreModule2");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 222);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 222, "GMSCoreModule1");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(3);
-// ValidateUidDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 222);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 222, "GMSCoreModule1");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 333);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(bucketStartTimeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(4);
-// ValidateUidDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 333);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 222);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 222, "GMSCoreModule1");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(bucketStartTimeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(5);
-// ValidateUidDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 444);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 444, "GMSCoreModule2");
-// ValidateUidDimension(
-// data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 333);
-// ValidateAttributionUidAndTagDimension(
-// data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
-// EXPECT_EQ(data.bucket_info_size(), 1);
-// EXPECT_EQ(data.bucket_info(0).count(), 1);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
+TEST(AttributionE2eTest, TestAttributionMatchAndSliceByFirstUid) {
+ auto config = CreateStatsdConfig(Position::FIRST);
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ // Here it assumes that GMS core has two uids.
+ processor->getUidMap()->updateMap(
+ 1, {222, 444, 111, 333}, {1, 1, 2, 2},
+ {String16("v1"), String16("v1"), String16("v2"), String16("v2")},
+ {String16("com.android.gmscore"), String16("com.android.gmscore"), String16("app1"),
+ String16("APP3")},
+ {String16(""), String16(""), String16(""), String16("")});
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ // Events 1~4 are in the 1st bucket.
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids1,
+ attributionTags1, "wl1"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 200, attributionUids2,
+ attributionTags2, "wl1"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 1,
+ attributionUids3, attributionTags3, "wl1"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs, attributionUids4,
+ attributionTags4, "wl1"));
+
+ // Events 5~8 are in the 3rd bucket.
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 1,
+ attributionUids5, attributionTags5, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 100,
+ attributionUids6, attributionTags6, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs - 2,
+ attributionUids7, attributionTags7, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs,
+ attributionUids8, attributionTags8, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs + 1,
+ attributionUids9, attributionTags9, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs + 100,
+ attributionUids9, attributionTags9, "wl2"));
+ events.push_back(CreateIsolatedUidChangedEvent(bucketStartTimeNs + 3 * bucketSizeNs - 1, 222,
+ isolatedUid, true /*is_create*/));
+ events.push_back(CreateIsolatedUidChangedEvent(bucketStartTimeNs + 3 * bucketSizeNs + 10, 222,
+ isolatedUid, false /*is_create*/));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 4 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(countMetrics.data_size(), 4);
+
+ auto data = countMetrics.data(0);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).count(), 2);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).count(), 1);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
+ bucketStartTimeNs + 2 * bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(), bucketStartTimeNs + 3 * bucketSizeNs);
+
+ data = countMetrics.data(1);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule1");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).count(), 1);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+
+ data = countMetrics.data(2);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule3");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
+ bucketStartTimeNs + 3 * bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + 4 * bucketSizeNs);
+
+ data = countMetrics.data(3);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 444,
+ "GMSCoreModule2");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
+ bucketStartTimeNs + 2 * bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + 3 * bucketSizeNs);
+}
+
+TEST(AttributionE2eTest, TestAttributionMatchAndSliceByChain) {
+ auto config = CreateStatsdConfig(Position::ALL);
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ // Here it assumes that GMS core has two uids.
+ processor->getUidMap()->updateMap(
+ 1, {222, 444, 111, 333}, {1, 1, 2, 2},
+ {String16("v1"), String16("v1"), String16("v2"), String16("v2")},
+ {String16("com.android.gmscore"), String16("com.android.gmscore"), String16("app1"),
+ String16("APP3")},
+ {String16(""), String16(""), String16(""), String16("")});
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ // Events 1~4 are in the 1st bucket.
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids1,
+ attributionTags1, "wl1"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 200, attributionUids2,
+ attributionTags2, "wl1"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 1,
+ attributionUids3, attributionTags3, "wl1"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs, attributionUids4,
+ attributionTags4, "wl1"));
+
+ // Events 5~8 are in the 3rd bucket.
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 1,
+ attributionUids5, attributionTags5, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 100,
+ attributionUids6, attributionTags6, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs - 2,
+ attributionUids7, attributionTags7, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs,
+ attributionUids8, attributionTags8, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs + 1,
+ attributionUids10, attributionTags10, "wl2"));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 3 * bucketSizeNs + 100,
+ attributionUids10, attributionTags10, "wl2"));
+ events.push_back(CreateIsolatedUidChangedEvent(bucketStartTimeNs + 3 * bucketSizeNs - 1, 222,
+ isolatedUid, true /*is_create*/));
+ events.push_back(CreateIsolatedUidChangedEvent(bucketStartTimeNs + 3 * bucketSizeNs + 10, 222,
+ isolatedUid, false /*is_create*/));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 4 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(countMetrics.data_size(), 6);
+
+ auto data = countMetrics.data(0);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule1");
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(1).count());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
+ data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ ValidateUidDimension(data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 222);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 0,
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule1");
+ ValidateUidDimension(data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 333);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 1,
+ android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
+
+ data = countMetrics.data(2);
+ ValidateUidDimension(data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 444);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 0,
+ android::util::WAKELOCK_STATE_CHANGED, 444,
+ "GMSCoreModule2");
+ ValidateUidDimension(data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 222);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 1,
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule1");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(3);
+ ValidateUidDimension(data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 0,
+ android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
+ ValidateUidDimension(data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 222);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 1,
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule1");
+ ValidateUidDimension(data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 333);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 2,
+ android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(4);
+ ValidateUidDimension(data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 0,
+ android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
+ ValidateUidDimension(data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 333);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 1,
+ android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
+ ValidateUidDimension(data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 222);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 2,
+ android::util::WAKELOCK_STATE_CHANGED, 222,
+ "GMSCoreModule1");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(5);
+ ValidateUidDimension(data.dimensions_in_what(), 0, android::util::WAKELOCK_STATE_CHANGED, 111);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 0,
+ android::util::WAKELOCK_STATE_CHANGED, 111, "App1");
+ ValidateUidDimension(data.dimensions_in_what(), 1, android::util::WAKELOCK_STATE_CHANGED, 444);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 1,
+ android::util::WAKELOCK_STATE_CHANGED, 444,
+ "GMSCoreModule2");
+ ValidateUidDimension(data.dimensions_in_what(), 2, android::util::WAKELOCK_STATE_CHANGED, 333);
+ ValidateAttributionUidAndTagDimension(data.dimensions_in_what(), 2,
+ android::util::WAKELOCK_STATE_CHANGED, 333, "App3");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp b/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp
index f8edee5..102bb1e 100644
--- a/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/ConfigTtl_e2e_test.cpp
@@ -56,54 +56,54 @@
} // namespace
-// TODO(b/149590301): Update this test to use new socket schema.
-//TEST(ConfigTtlE2eTest, TestCountMetric) {
-// const int num_buckets = 1;
-// const int threshold = 3;
-// auto config = CreateStatsdConfig(num_buckets, threshold);
-// const uint64_t alert_id = config.alert(0).id();
-// const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
-//
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-//
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1")};
-//
-// FieldValue fieldValue1(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
-// Value((int32_t)111));
-// HashableDimensionKey whatKey1({fieldValue1});
-// MetricDimensionKey dimensionKey1(whatKey1, DEFAULT_DIMENSION_KEY);
-//
-// FieldValue fieldValue2(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
-// Value((int32_t)222));
-// HashableDimensionKey whatKey2({fieldValue2});
-// MetricDimensionKey dimensionKey2(whatKey2, DEFAULT_DIMENSION_KEY);
-//
-// auto event = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 2);
-// processor->OnLogEvent(event.get());
-//
-// event = CreateAcquireWakelockEvent(attributions1, "wl2", bucketStartTimeNs + bucketSizeNs + 2);
-// processor->OnLogEvent(event.get());
-//
-// event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 25 * bucketSizeNs + 2);
-// processor->OnLogEvent(event.get());
-//
-// EXPECT_EQ((int64_t)(bucketStartTimeNs + 25 * bucketSizeNs + 2 + 2 * 3600 * NS_PER_SEC),
-// processor->mMetricsManagers.begin()->second->getTtlEndNs());
-//
-// // Clear the data stored on disk as a result of the ttl.
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 25 * bucketSizeNs + 3, false, true,
-// ADB_DUMP, FAST, &buffer);
-//}
+TEST(ConfigTtlE2eTest, TestCountMetric) {
+ const int num_buckets = 1;
+ const int threshold = 3;
+ auto config = CreateStatsdConfig(num_buckets, threshold);
+ const uint64_t alert_id = config.alert(0).id();
+ const uint32_t refractory_period_sec = config.alert(0).refractory_period_secs();
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ std::vector<int> attributionUids1 = {111};
+ std::vector<string> attributionTags1 = {"App1"};
+
+ FieldValue fieldValue1(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
+ Value((int32_t)111));
+ HashableDimensionKey whatKey1({fieldValue1});
+ MetricDimensionKey dimensionKey1(whatKey1, DEFAULT_DIMENSION_KEY);
+
+ FieldValue fieldValue2(Field(android::util::WAKELOCK_STATE_CHANGED, (int32_t)0x02010101),
+ Value((int32_t)222));
+ HashableDimensionKey whatKey2({fieldValue2});
+ MetricDimensionKey dimensionKey2(whatKey2, DEFAULT_DIMENSION_KEY);
+
+ auto event = CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs + 2, attributionUids1,
+ attributionTags1, "wl2");
+ processor->OnLogEvent(event.get());
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + 25 * bucketSizeNs + 2, attributionUids1,
+ attributionTags1, "wl1");
+ processor->OnLogEvent(event.get());
+
+ EXPECT_EQ((int64_t)(bucketStartTimeNs + 25 * bucketSizeNs + 2 + 2 * 3600 * NS_PER_SEC),
+ processor->mMetricsManagers.begin()->second->getTtlEndNs());
+
+ // Clear the data stored on disk as a result of the ttl.
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 25 * bucketSizeNs + 3, false, true,
+ ADB_DUMP, FAST, &buffer);
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/CountMetric_e2e_test.cpp b/cmds/statsd/tests/e2e/CountMetric_e2e_test.cpp
index a1f74a6..2cd7854 100644
--- a/cmds/statsd/tests/e2e/CountMetric_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/CountMetric_e2e_test.cpp
@@ -27,773 +27,775 @@
#ifdef __ANDROID__
-// TODO(b/149590301): Update these tests to use new socket schema.
-///**
-// * Test a count metric that has one slice_by_state with no primary fields.
-// *
-// * Once the CountMetricProducer is initialized, it has one atom id in
-// * mSlicedStateAtoms and no entries in mStateGroupMap.
-//
-// * One StateTracker tracks the state atom, and it has one listener which is the
-// * CountMetricProducer that was initialized.
-// */
-//TEST(CountMetricE2eTest, TestSlicedState) {
-// // Initialize config.
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto syncStartMatcher = CreateSyncStartAtomMatcher();
-// *config.add_atom_matcher() = syncStartMatcher;
-//
-// auto state = CreateScreenState();
-// *config.add_state() = state;
-//
-// // Create count metric that slices by screen state.
-// int64_t metricId = 123456;
-// auto countMetric = config.add_count_metric();
-// countMetric->set_id(metricId);
-// countMetric->set_what(syncStartMatcher.id());
-// countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
-// countMetric->add_slice_by_state(state.id());
-//
-// // Initialize StatsLogProcessor.
-// const uint64_t bucketStartTimeNs = 10000000000; // 0:10
-// const uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-//
-// // Check that CountMetricProducer was initialized correctly.
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 1);
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), SCREEN_STATE_ATOM_ID);
-// EXPECT_EQ(metricProducer->mStateGroupMap.size(), 0);
-//
-// // Check that StateTrackers were initialized correctly.
-// EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
-// EXPECT_EQ(1, StateManager::getInstance().getListenersCount(SCREEN_STATE_ATOM_ID));
-//
-// /*
-// bucket #1 bucket #2
-// | 1 2 3 4 5 6 7 8 9 10 (minutes)
-// |-----------------------------|-----------------------------|--
-// x x x x x x (syncStartEvents)
-// | | (ScreenIsOnEvent)
-// | | (ScreenIsOffEvent)
-// | (ScreenUnknownEvent)
-// */
-// // Initialize log events - first bucket.
-// int appUid = 123;
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(appUid, "App1")};
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 50 * NS_PER_SEC)); // 1:00
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 75 * NS_PER_SEC)); // 1:25
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 150 * NS_PER_SEC)); // 2:40
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 200 * NS_PER_SEC)); // 3:30
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 250 * NS_PER_SEC)); // 4:20
-//
-// // Initialize log events - second bucket.
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 350 * NS_PER_SEC)); // 6:00
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 400 * NS_PER_SEC)); // 6:50
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 450 * NS_PER_SEC)); // 7:40
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 475 * NS_PER_SEC)); // 8:05
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN,
-// bucketStartTimeNs + 500 * NS_PER_SEC)); // 8:30
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 520 * NS_PER_SEC)); // 8:50
-//
-// // Send log events to StatsLogProcessor.
-// for (auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//
-// // Check dump report.
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
-// FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
-// EXPECT_EQ(3, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// // For each CountMetricData, check StateValue info is correct and buckets
-// // have correct counts.
-// auto data = reports.reports(0).metrics(0).count_metrics().data(0);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::view::DisplayStateEnum::DISPLAY_STATE_ON, data.slice_by_state(0).value());
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(1, data.bucket_info(1).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(1);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN, data.slice_by_state(0).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(2);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::view::DisplayStateEnum::DISPLAY_STATE_OFF, data.slice_by_state(0).value());
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(2, data.bucket_info(1).count());
-//}
-//
-///**
-// * Test a count metric that has one slice_by_state with a mapping and no
-// * primary fields.
-// *
-// * Once the CountMetricProducer is initialized, it has one atom id in
-// * mSlicedStateAtoms and has one entry per state value in mStateGroupMap.
-// *
-// * One StateTracker tracks the state atom, and it has one listener which is the
-// * CountMetricProducer that was initialized.
-// */
-//TEST(CountMetricE2eTest, TestSlicedStateWithMap) {
-// // Initialize config.
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto syncStartMatcher = CreateSyncStartAtomMatcher();
-// *config.add_atom_matcher() = syncStartMatcher;
-//
-// auto state = CreateScreenStateWithOnOffMap();
-// *config.add_state() = state;
-//
-// // Create count metric that slices by screen state with on/off map.
-// int64_t metricId = 123456;
-// auto countMetric = config.add_count_metric();
-// countMetric->set_id(metricId);
-// countMetric->set_what(syncStartMatcher.id());
-// countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
-// countMetric->add_slice_by_state(state.id());
-//
-// // Initialize StatsLogProcessor.
-// const uint64_t bucketStartTimeNs = 10000000000; // 0:10
-// const uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-//
-// // Check that StateTrackers were initialized correctly.
-// EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
-// EXPECT_EQ(1, StateManager::getInstance().getListenersCount(SCREEN_STATE_ATOM_ID));
-//
-// // Check that CountMetricProducer was initialized correctly.
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 1);
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), SCREEN_STATE_ATOM_ID);
-// EXPECT_EQ(metricProducer->mStateGroupMap.size(), 1);
-//
-// StateMap map = state.map();
-// for (auto group : map.group()) {
-// for (auto value : group.value()) {
-// EXPECT_EQ(metricProducer->mStateGroupMap[SCREEN_STATE_ATOM_ID][value],
-// group.group_id());
-// }
-// }
-//
-// /*
-// bucket #1 bucket #2
-// | 1 2 3 4 5 6 7 8 9 10 (minutes)
-// |-----------------------------|-----------------------------|--
-// x x x x x x x x x (syncStartEvents)
-// -----------------------------------------------------------SCREEN_OFF events
-// | (ScreenStateUnknownEvent = 0)
-// | | (ScreenStateOffEvent = 1)
-// | (ScreenStateDozeEvent = 3)
-// | (ScreenStateDozeSuspendEvent = 4)
-// -----------------------------------------------------------SCREEN_ON events
-// | | (ScreenStateOnEvent = 2)
-// | (ScreenStateVrEvent = 5)
-// | (ScreenStateOnSuspendEvent = 6)
-// */
-// // Initialize log events - first bucket.
-// int appUid = 123;
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(appUid, "App1")};
-//
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 20 * NS_PER_SEC)); // 0:30
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN,
-// bucketStartTimeNs + 30 * NS_PER_SEC)); // 0:40
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 60 * NS_PER_SEC)); // 1:10
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 90 * NS_PER_SEC)); // 1:40
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 120 * NS_PER_SEC)); // 2:10
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 150 * NS_PER_SEC)); // 2:40
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_VR,
-// bucketStartTimeNs + 180 * NS_PER_SEC)); // 3:10
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 200 * NS_PER_SEC)); // 3:30
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_DOZE,
-// bucketStartTimeNs + 210 * NS_PER_SEC)); // 3:40
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 250 * NS_PER_SEC)); // 4:20
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 280 * NS_PER_SEC)); // 4:50
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 285 * NS_PER_SEC)); // 4:55
-//
-// // Initialize log events - second bucket.
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 360 * NS_PER_SEC)); // 6:10
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON_SUSPEND,
-// bucketStartTimeNs + 390 * NS_PER_SEC)); // 6:40
-// events.push_back(CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_DOZE_SUSPEND,
-// bucketStartTimeNs + 430 * NS_PER_SEC)); // 7:20
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 440 * NS_PER_SEC)); // 7:30
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 540 * NS_PER_SEC)); // 9:10
-// events.push_back(CreateSyncStartEvent(attributions1, "sync_name",
-// bucketStartTimeNs + 570 * NS_PER_SEC)); // 9:40
-//
-// // Send log events to StatsLogProcessor.
-// for (auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//
-// // Check dump report.
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
-// FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
-// EXPECT_EQ(3, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// // For each CountMetricData, check StateValue info is correct and buckets
-// // have correct counts.
-// auto data = reports.reports(0).metrics(0).count_metrics().data(0);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(-1 /* StateTracker::kStateUnknown */, data.slice_by_state(0).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(1);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(4, data.bucket_info(0).count());
-// EXPECT_EQ(2, data.bucket_info(1).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(2);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_ON"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(1, data.bucket_info(1).count());
-//}
-//
-///**
-// * Test a count metric that has one slice_by_state with a primary field.
-//
-// * Once the CountMetricProducer is initialized, it should have one
-// * MetricStateLink stored. State querying using a non-empty primary key
-// * should also work as intended.
-// */
-//TEST(CountMetricE2eTest, TestSlicedStateWithPrimaryFields) {
-// // Initialize config.
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto appCrashMatcher =
-// CreateSimpleAtomMatcher("APP_CRASH_OCCURRED", android::util::APP_CRASH_OCCURRED);
-// *config.add_atom_matcher() = appCrashMatcher;
-//
-// auto state = CreateUidProcessState();
-// *config.add_state() = state;
-//
-// // Create count metric that slices by uid process state.
-// int64_t metricId = 123456;
-// auto countMetric = config.add_count_metric();
-// countMetric->set_id(metricId);
-// countMetric->set_what(appCrashMatcher.id());
-// countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
-// countMetric->add_slice_by_state(state.id());
-// MetricStateLink* stateLink = countMetric->add_state_link();
-// stateLink->set_state_atom_id(UID_PROCESS_STATE_ATOM_ID);
-// auto fieldsInWhat = stateLink->mutable_fields_in_what();
-// *fieldsInWhat = CreateDimensions(android::util::APP_CRASH_OCCURRED, {1 /* uid */});
-// auto fieldsInState = stateLink->mutable_fields_in_state();
-// *fieldsInState = CreateDimensions(UID_PROCESS_STATE_ATOM_ID, {1 /* uid */});
-//
-// // Initialize StatsLogProcessor.
-// const uint64_t bucketStartTimeNs = 10000000000; // 0:10
-// const uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-//
-// // Check that StateTrackers were initialized correctly.
-// EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
-// EXPECT_EQ(1, StateManager::getInstance().getListenersCount(UID_PROCESS_STATE_ATOM_ID));
-//
-// // Check that CountMetricProducer was initialized correctly.
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 1);
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), UID_PROCESS_STATE_ATOM_ID);
-// EXPECT_EQ(metricProducer->mStateGroupMap.size(), 0);
-// EXPECT_EQ(metricProducer->mMetric2StateLinks.size(), 1);
-//
-// /*
-// NOTE: "1" or "2" represents the uid associated with the state/app crash event
-// bucket #1 bucket #2
-// | 1 2 3 4 5 6 7 8 9 10
-// |-----------------------------|-----------------------------|--
-// 1 1 1 1 1 2 1 1 2 (AppCrashEvents)
-// -----------------------------------------------------------PROCESS STATE events
-// 1 2 (ProcessStateTopEvent = 1002)
-// 1 1 (ProcessStateForegroundServiceEvent = 1003)
-// 2 (ProcessStateImportantBackgroundEvent = 1006)
-// 1 1 1 (ProcessStateImportantForegroundEvent = 1005)
-//
-// Based on the diagram above, an AppCrashEvent querying for process state value would return:
-// - StateTracker::kStateUnknown
-// - Important foreground
-// - Top
-// - Important foreground
-// - Foreground service
-// - Top (both the app crash and state still have matching uid = 2)
-//
-// - Foreground service
-// - Foreground service
-// - Important background
-// */
-// // Initialize log events - first bucket.
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(
-// CreateAppCrashOccurredEvent(1 /* uid */, bucketStartTimeNs + 20 * NS_PER_SEC)); // 0:30
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND,
-// bucketStartTimeNs + 30 * NS_PER_SEC)); // 0:40
-// events.push_back(
-// CreateAppCrashOccurredEvent(1 /* uid */, bucketStartTimeNs + 60 * NS_PER_SEC)); // 1:10
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_TOP,
-// bucketStartTimeNs + 90 * NS_PER_SEC)); // 1:40
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 120 * NS_PER_SEC)); // 2:10
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND,
-// bucketStartTimeNs + 150 * NS_PER_SEC)); // 2:40
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 200 * NS_PER_SEC)); // 3:30
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE,
-// bucketStartTimeNs + 210 * NS_PER_SEC)); // 3:40
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 250 * NS_PER_SEC)); // 4:20
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 2 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_TOP,
-// bucketStartTimeNs + 280 * NS_PER_SEC)); // 4:50
-// events.push_back(CreateAppCrashOccurredEvent(2 /* uid */,
-// bucketStartTimeNs + 285 * NS_PER_SEC)); // 4:55
-//
-// // Initialize log events - second bucket.
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 360 * NS_PER_SEC)); // 6:10
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE,
-// bucketStartTimeNs + 390 * NS_PER_SEC)); // 6:40
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 2 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_BACKGROUND,
-// bucketStartTimeNs + 430 * NS_PER_SEC)); // 7:20
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 440 * NS_PER_SEC)); // 7:30
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND,
-// bucketStartTimeNs + 540 * NS_PER_SEC)); // 9:10
-// events.push_back(CreateAppCrashOccurredEvent(2 /* uid */,
-// bucketStartTimeNs + 570 * NS_PER_SEC)); // 9:40
-//
-// // Send log events to StatsLogProcessor.
-// for (auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//
-// // Check dump report.
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
-// FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
-// EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// // For each CountMetricData, check StateValue info is correct and buckets
-// // have correct counts.
-// auto data = reports.reports(0).metrics(0).count_metrics().data(0);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_BACKGROUND, data.slice_by_state(0).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(1);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(-1 /* StateTracker::kStateUnknown */, data.slice_by_state(0).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(2);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(0).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(2, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(3);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_TOP, data.slice_by_state(0).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(2, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(4);
-// EXPECT_EQ(1, data.slice_by_state_size());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_FOREGROUND_SERVICE, data.slice_by_state(0).value());
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(2, data.bucket_info(1).count());
-//}
-//
-//TEST(CountMetricE2eTest, TestMultipleSlicedStates) {
-// // Initialize config.
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto appCrashMatcher =
-// CreateSimpleAtomMatcher("APP_CRASH_OCCURRED", android::util::APP_CRASH_OCCURRED);
-// *config.add_atom_matcher() = appCrashMatcher;
-//
-// auto state1 = CreateScreenStateWithOnOffMap();
-// *config.add_state() = state1;
-// auto state2 = CreateUidProcessState();
-// *config.add_state() = state2;
-//
-// // Create count metric that slices by screen state with on/off map and
-// // slices by uid process state.
-// int64_t metricId = 123456;
-// auto countMetric = config.add_count_metric();
-// countMetric->set_id(metricId);
-// countMetric->set_what(appCrashMatcher.id());
-// countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
-// countMetric->add_slice_by_state(state1.id());
-// countMetric->add_slice_by_state(state2.id());
-// MetricStateLink* stateLink = countMetric->add_state_link();
-// stateLink->set_state_atom_id(UID_PROCESS_STATE_ATOM_ID);
-// auto fieldsInWhat = stateLink->mutable_fields_in_what();
-// *fieldsInWhat = CreateDimensions(android::util::APP_CRASH_OCCURRED, {1 /* uid */});
-// auto fieldsInState = stateLink->mutable_fields_in_state();
-// *fieldsInState = CreateDimensions(UID_PROCESS_STATE_ATOM_ID, {1 /* uid */});
-//
-// // Initialize StatsLogProcessor.
-// const uint64_t bucketStartTimeNs = 10000000000; // 0:10
-// const uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-//
-// // Check that StateTrackers were properly initialized.
-// EXPECT_EQ(2, StateManager::getInstance().getStateTrackersCount());
-// EXPECT_EQ(1, StateManager::getInstance().getListenersCount(SCREEN_STATE_ATOM_ID));
-// EXPECT_EQ(1, StateManager::getInstance().getListenersCount(UID_PROCESS_STATE_ATOM_ID));
-//
-// // Check that CountMetricProducer was initialized correctly.
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 2);
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), SCREEN_STATE_ATOM_ID);
-// EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(1), UID_PROCESS_STATE_ATOM_ID);
-// EXPECT_EQ(metricProducer->mStateGroupMap.size(), 1);
-// EXPECT_EQ(metricProducer->mMetric2StateLinks.size(), 1);
-//
-// StateMap map = state1.map();
-// for (auto group : map.group()) {
-// for (auto value : group.value()) {
-// EXPECT_EQ(metricProducer->mStateGroupMap[SCREEN_STATE_ATOM_ID][value],
-// group.group_id());
-// }
-// }
-//
-// /*
-// bucket #1 bucket #2
-// | 1 2 3 4 5 6 7 8 9 10 (minutes)
-// |-----------------------------|-----------------------------|--
-// 1 1 1 1 1 2 1 1 2 (AppCrashEvents)
-// -----------------------------------------------------------SCREEN_OFF events
-// | (ScreenStateUnknownEvent = 0)
-// | | (ScreenStateOffEvent = 1)
-// | (ScreenStateDozeEvent = 3)
-// -----------------------------------------------------------SCREEN_ON events
-// | | (ScreenStateOnEvent = 2)
-// | (ScreenStateOnSuspendEvent = 6)
-// -----------------------------------------------------------PROCESS STATE events
-// 1 2 (ProcessStateTopEvent = 1002)
-// 1 (ProcessStateForegroundServiceEvent = 1003)
-// 2 (ProcessStateImportantBackgroundEvent = 1006)
-// 1 1 1 (ProcessStateImportantForegroundEvent = 1005)
-//
-// Based on the diagram above, Screen State / Process State pairs for each
-// AppCrashEvent are:
-// - StateTracker::kStateUnknown / important foreground
-// - off / important foreground
-// - off / Top
-// - on / important foreground
-// - off / important foreground
-// - off / top
-//
-// - off / important foreground
-// - off / foreground service
-// - on / important background
-//
-// */
-// // Initialize log events - first bucket.
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND,
-// bucketStartTimeNs + 5 * NS_PER_SEC)); // 0:15
-// events.push_back(
-// CreateAppCrashOccurredEvent(1 /* uid */, bucketStartTimeNs + 20 * NS_PER_SEC)); // 0:30
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN,
-// bucketStartTimeNs + 30 * NS_PER_SEC)); // 0:40
-// events.push_back(
-// CreateAppCrashOccurredEvent(1 /* uid */, bucketStartTimeNs + 60 * NS_PER_SEC)); // 1:10
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_TOP,
-// bucketStartTimeNs + 90 * NS_PER_SEC)); // 1:40
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 90 * NS_PER_SEC)); // 1:40
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 120 * NS_PER_SEC)); // 2:10
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND,
-// bucketStartTimeNs + 150 * NS_PER_SEC)); // 2:40
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 160 * NS_PER_SEC)); // 2:50
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 200 * NS_PER_SEC)); // 3:30
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_DOZE,
-// bucketStartTimeNs + 210 * NS_PER_SEC)); // 3:40
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 250 * NS_PER_SEC)); // 4:20
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 2 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_TOP,
-// bucketStartTimeNs + 280 * NS_PER_SEC)); // 4:50
-// events.push_back(CreateAppCrashOccurredEvent(2 /* uid */,
-// bucketStartTimeNs + 285 * NS_PER_SEC)); // 4:55
-//
-// // Initialize log events - second bucket.
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 360 * NS_PER_SEC)); // 6:10
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE,
-// bucketStartTimeNs + 380 * NS_PER_SEC)); // 6:30
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON_SUSPEND,
-// bucketStartTimeNs + 390 * NS_PER_SEC)); // 6:40
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 2 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_BACKGROUND,
-// bucketStartTimeNs + 420 * NS_PER_SEC)); // 7:10
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 440 * NS_PER_SEC)); // 7:30
-// events.push_back(CreateAppCrashOccurredEvent(1 /* uid */,
-// bucketStartTimeNs + 450 * NS_PER_SEC)); // 7:40
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 520 * NS_PER_SEC)); // 8:50
-// events.push_back(CreateUidProcessStateChangedEvent(
-// 1 /* uid */, android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND,
-// bucketStartTimeNs + 540 * NS_PER_SEC)); // 9:10
-// events.push_back(CreateAppCrashOccurredEvent(2 /* uid */,
-// bucketStartTimeNs + 570 * NS_PER_SEC)); // 9:40
-//
-// // Send log events to StatsLogProcessor.
-// for (auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//
-// // Check dump report.
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
-// FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
-// EXPECT_EQ(6, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// // For each CountMetricData, check StateValue info is correct and buckets
-// // have correct counts.
-// auto data = reports.reports(0).metrics(0).count_metrics().data(0);
-// EXPECT_EQ(2, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
-// EXPECT_TRUE(data.slice_by_state(1).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_FOREGROUND_SERVICE, data.slice_by_state(1).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(1);
-// EXPECT_EQ(2, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_value());
-// EXPECT_EQ(-1, data.slice_by_state(0).value());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
-// EXPECT_TRUE(data.slice_by_state(1).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(1).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(2);
-// EXPECT_EQ(2, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
-// EXPECT_TRUE(data.slice_by_state(1).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(1).value());
-// EXPECT_EQ(2, data.bucket_info_size());
-// EXPECT_EQ(2, data.bucket_info(0).count());
-// EXPECT_EQ(1, data.bucket_info(1).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(3);
-// EXPECT_EQ(2, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_ON"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
-// EXPECT_TRUE(data.slice_by_state(1).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(1).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(4);
-// EXPECT_EQ(2, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_ON"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
-// EXPECT_TRUE(data.slice_by_state(1).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_BACKGROUND, data.slice_by_state(1).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-//
-// data = reports.reports(0).metrics(0).count_metrics().data(5);
-// EXPECT_EQ(2, data.slice_by_state_size());
-// EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
-// EXPECT_TRUE(data.slice_by_state(0).has_group_id());
-// EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
-// EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
-// EXPECT_TRUE(data.slice_by_state(1).has_value());
-// EXPECT_EQ(android::app::PROCESS_STATE_TOP, data.slice_by_state(1).value());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(2, data.bucket_info(0).count());
-//}
+/**
+* Test a count metric that has one slice_by_state with no primary fields.
+*
+* Once the CountMetricProducer is initialized, it has one atom id in
+* mSlicedStateAtoms and no entries in mStateGroupMap.
+
+* One StateTracker tracks the state atom, and it has one listener which is the
+* CountMetricProducer that was initialized.
+*/
+TEST(CountMetricE2eTest, TestSlicedState) {
+ // Initialize config.
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto syncStartMatcher = CreateSyncStartAtomMatcher();
+ *config.add_atom_matcher() = syncStartMatcher;
+
+ auto state = CreateScreenState();
+ *config.add_state() = state;
+
+ // Create count metric that slices by screen state.
+ int64_t metricId = 123456;
+ auto countMetric = config.add_count_metric();
+ countMetric->set_id(metricId);
+ countMetric->set_what(syncStartMatcher.id());
+ countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
+ countMetric->add_slice_by_state(state.id());
+
+ // Initialize StatsLogProcessor.
+ const uint64_t bucketStartTimeNs = 10000000000; // 0:10
+ const uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+
+ // Check that CountMetricProducer was initialized correctly.
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 1);
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), SCREEN_STATE_ATOM_ID);
+ EXPECT_EQ(metricProducer->mStateGroupMap.size(), 0);
+
+ // Check that StateTrackers were initialized correctly.
+ EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
+ EXPECT_EQ(1, StateManager::getInstance().getListenersCount(SCREEN_STATE_ATOM_ID));
+
+ /*
+ bucket #1 bucket #2
+ | 1 2 3 4 5 6 7 8 9 10 (minutes)
+ |-----------------------------|-----------------------------|--
+ x x x x x x (syncStartEvents)
+ | | (ScreenIsOnEvent)
+ | | (ScreenIsOffEvent)
+ | (ScreenUnknownEvent)
+ */
+ // Initialize log events - first bucket.
+ std::vector<int> attributionUids1 = {123};
+ std::vector<string> attributionTags1 = {"App1"};
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 50 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON)); // 1:00
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 75 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 1:25
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 150 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF)); // 2:40
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 200 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF)); // 3:30
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 250 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 4:20
+
+ // Initialize log events - second bucket.
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 350 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 6:00
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 400 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 6:50
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 450 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON)); // 7:40
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 475 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 8:05
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 500 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN)); // 8:30
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 520 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 8:50
+
+ // Send log events to StatsLogProcessor.
+ for (auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ // Check dump report.
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
+ EXPECT_EQ(3, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ // For each CountMetricData, check StateValue info is correct and buckets
+ // have correct counts.
+ auto data = reports.reports(0).metrics(0).count_metrics().data(0);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::view::DisplayStateEnum::DISPLAY_STATE_ON, data.slice_by_state(0).value());
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(1, data.bucket_info(1).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(1);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN,
+ data.slice_by_state(0).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(2);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::view::DisplayStateEnum::DISPLAY_STATE_OFF, data.slice_by_state(0).value());
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(2, data.bucket_info(1).count());
+}
+
+/**
+ * Test a count metric that has one slice_by_state with a mapping and no
+ * primary fields.
+ *
+ * Once the CountMetricProducer is initialized, it has one atom id in
+ * mSlicedStateAtoms and has one entry per state value in mStateGroupMap.
+ *
+ * One StateTracker tracks the state atom, and it has one listener which is the
+ * CountMetricProducer that was initialized.
+ */
+TEST(CountMetricE2eTest, TestSlicedStateWithMap) {
+ // Initialize config.
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto syncStartMatcher = CreateSyncStartAtomMatcher();
+ *config.add_atom_matcher() = syncStartMatcher;
+
+ auto state = CreateScreenStateWithOnOffMap();
+ *config.add_state() = state;
+
+ // Create count metric that slices by screen state with on/off map.
+ int64_t metricId = 123456;
+ auto countMetric = config.add_count_metric();
+ countMetric->set_id(metricId);
+ countMetric->set_what(syncStartMatcher.id());
+ countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
+ countMetric->add_slice_by_state(state.id());
+
+ // Initialize StatsLogProcessor.
+ const uint64_t bucketStartTimeNs = 10000000000; // 0:10
+ const uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+
+ // Check that StateTrackers were initialized correctly.
+ EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
+ EXPECT_EQ(1, StateManager::getInstance().getListenersCount(SCREEN_STATE_ATOM_ID));
+
+ // Check that CountMetricProducer was initialized correctly.
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 1);
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), SCREEN_STATE_ATOM_ID);
+ EXPECT_EQ(metricProducer->mStateGroupMap.size(), 1);
+
+ StateMap map = state.map();
+ for (auto group : map.group()) {
+ for (auto value : group.value()) {
+ EXPECT_EQ(metricProducer->mStateGroupMap[SCREEN_STATE_ATOM_ID][value],
+ group.group_id());
+ }
+ }
+
+ /*
+ bucket #1 bucket #2
+ | 1 2 3 4 5 6 7 8 9 10 (minutes)
+ |-----------------------------|-----------------------------|--
+ x x x x x x x x x (syncStartEvents)
+ -----------------------------------------------------------SCREEN_OFF events
+ | (ScreenStateUnknownEvent = 0)
+ | | (ScreenStateOffEvent = 1)
+ | (ScreenStateDozeEvent = 3)
+ | (ScreenStateDozeSuspendEvent =
+ 4)
+ -----------------------------------------------------------SCREEN_ON events
+ | | (ScreenStateOnEvent = 2)
+ | (ScreenStateVrEvent = 5)
+ | (ScreenStateOnSuspendEvent = 6)
+ */
+ // Initialize log events - first bucket.
+ std::vector<int> attributionUids1 = {123};
+ std::vector<string> attributionTags1 = {"App1"};
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 20 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 0:30
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 30 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN)); // 0:40
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 60 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 1:10
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 90 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF)); // 1:40
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 120 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 2:10
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 150 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON)); // 2:40
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 180 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_VR)); // 3:10
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 200 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 3:30
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 210 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_DOZE)); // 3:40
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 250 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 4:20
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 280 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF)); // 4:50
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 285 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 4:55
+
+ // Initialize log events - second bucket.
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 360 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 6:10
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 390 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON_SUSPEND)); // 6:40
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 430 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_DOZE_SUSPEND)); // 7:20
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 440 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 7:30
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 540 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON)); // 9:10
+ events.push_back(CreateSyncStartEvent(bucketStartTimeNs + 570 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "sync_name")); // 9:40
+
+ // Send log events to StatsLogProcessor.
+ for (auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ // Check dump report.
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
+ EXPECT_EQ(3, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ // For each CountMetricData, check StateValue info is correct and buckets
+ // have correct counts.
+ auto data = reports.reports(0).metrics(0).count_metrics().data(0);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(-1 /* StateTracker::kStateUnknown */, data.slice_by_state(0).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(1);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(4, data.bucket_info(0).count());
+ EXPECT_EQ(2, data.bucket_info(1).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(2);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_ON"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(1, data.bucket_info(1).count());
+}
+
+/**
+* Test a count metric that has one slice_by_state with a primary field.
+
+* Once the CountMetricProducer is initialized, it should have one
+* MetricStateLink stored. State querying using a non-empty primary key
+* should also work as intended.
+*/
+TEST(CountMetricE2eTest, TestSlicedStateWithPrimaryFields) {
+ // Initialize config.
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto appCrashMatcher =
+ CreateSimpleAtomMatcher("APP_CRASH_OCCURRED", android::util::APP_CRASH_OCCURRED);
+ *config.add_atom_matcher() = appCrashMatcher;
+
+ auto state = CreateUidProcessState();
+ *config.add_state() = state;
+
+ // Create count metric that slices by uid process state.
+ int64_t metricId = 123456;
+ auto countMetric = config.add_count_metric();
+ countMetric->set_id(metricId);
+ countMetric->set_what(appCrashMatcher.id());
+ countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
+ countMetric->add_slice_by_state(state.id());
+ MetricStateLink* stateLink = countMetric->add_state_link();
+ stateLink->set_state_atom_id(UID_PROCESS_STATE_ATOM_ID);
+ auto fieldsInWhat = stateLink->mutable_fields_in_what();
+ *fieldsInWhat = CreateDimensions(android::util::APP_CRASH_OCCURRED, {1 /*uid*/});
+ auto fieldsInState = stateLink->mutable_fields_in_state();
+ *fieldsInState = CreateDimensions(UID_PROCESS_STATE_ATOM_ID, {1 /*uid*/});
+
+ // Initialize StatsLogProcessor.
+ const uint64_t bucketStartTimeNs = 10000000000; // 0:10
+ const uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+
+ // Check that StateTrackers were initialized correctly.
+ EXPECT_EQ(1, StateManager::getInstance().getStateTrackersCount());
+ EXPECT_EQ(1, StateManager::getInstance().getListenersCount(UID_PROCESS_STATE_ATOM_ID));
+
+ // Check that CountMetricProducer was initialized correctly.
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 1);
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), UID_PROCESS_STATE_ATOM_ID);
+ EXPECT_EQ(metricProducer->mStateGroupMap.size(), 0);
+ EXPECT_EQ(metricProducer->mMetric2StateLinks.size(), 1);
+
+ /*
+ NOTE: "1" or "2" represents the uid associated with the state/app crash event
+ bucket #1 bucket #2
+ | 1 2 3 4 5 6 7 8 9 10
+ |------------------------|-------------------------|--
+ 1 1 1 1 1 2 1 1 2 (AppCrashEvents)
+ -----------------------------------------------------PROCESS STATE events
+ 1 2 (TopEvent = 1002)
+ 1 1 (ForegroundServiceEvent = 1003)
+ 2 (ImportantBackgroundEvent = 1006)
+ 1 1 1 (ImportantForegroundEvent = 1005)
+
+ Based on the diagram above, an AppCrashEvent querying for process state value would return:
+ - StateTracker::kStateUnknown
+ - Important foreground
+ - Top
+ - Important foreground
+ - Foreground service
+ - Top (both the app crash and state still have matching uid = 2)
+
+ - Foreground service
+ - Foreground service
+ - Important background
+ */
+ // Initialize log events - first bucket.
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 20 * NS_PER_SEC, 1 /*uid*/)); // 0:30
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 30 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND)); // 0:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 60 * NS_PER_SEC, 1 /*uid*/)); // 1:10
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 90 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_TOP)); // 1:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 120 * NS_PER_SEC, 1 /*uid*/)); // 2:10
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 150 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND)); // 2:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 200 * NS_PER_SEC, 1 /*uid*/)); // 3:30
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 210 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE)); // 3:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 250 * NS_PER_SEC, 1 /*uid*/)); // 4:20
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 280 * NS_PER_SEC, 2 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_TOP)); // 4:50
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 285 * NS_PER_SEC, 2 /*uid*/)); // 4:55
+
+ // Initialize log events - second bucket.
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 360 * NS_PER_SEC, 1 /*uid*/)); // 6:10
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 390 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE)); // 6:40
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 430 * NS_PER_SEC, 2 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_BACKGROUND)); // 7:20
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 440 * NS_PER_SEC, 1 /*uid*/)); // 7:30
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 540 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND)); // 9:10
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 570 * NS_PER_SEC, 2 /*uid*/)); // 9:40
+
+ // Send log events to StatsLogProcessor.
+ for (auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ // Check dump report.
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
+ EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ // For each CountMetricData, check StateValue info is correct and buckets
+ // have correct counts.
+ auto data = reports.reports(0).metrics(0).count_metrics().data(0);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_BACKGROUND, data.slice_by_state(0).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(1);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(-1 /* StateTracker::kStateUnknown */, data.slice_by_state(0).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(2);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(0).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(2, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(3);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_TOP, data.slice_by_state(0).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(2, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(4);
+ EXPECT_EQ(1, data.slice_by_state_size());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_FOREGROUND_SERVICE, data.slice_by_state(0).value());
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(2, data.bucket_info(1).count());
+}
+
+TEST(CountMetricE2eTest, TestMultipleSlicedStates) {
+ // Initialize config.
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto appCrashMatcher =
+ CreateSimpleAtomMatcher("APP_CRASH_OCCURRED", android::util::APP_CRASH_OCCURRED);
+ *config.add_atom_matcher() = appCrashMatcher;
+
+ auto state1 = CreateScreenStateWithOnOffMap();
+ *config.add_state() = state1;
+ auto state2 = CreateUidProcessState();
+ *config.add_state() = state2;
+
+ // Create count metric that slices by screen state with on/off map and
+ // slices by uid process state.
+ int64_t metricId = 123456;
+ auto countMetric = config.add_count_metric();
+ countMetric->set_id(metricId);
+ countMetric->set_what(appCrashMatcher.id());
+ countMetric->set_bucket(TimeUnit::FIVE_MINUTES);
+ countMetric->add_slice_by_state(state1.id());
+ countMetric->add_slice_by_state(state2.id());
+ MetricStateLink* stateLink = countMetric->add_state_link();
+ stateLink->set_state_atom_id(UID_PROCESS_STATE_ATOM_ID);
+ auto fieldsInWhat = stateLink->mutable_fields_in_what();
+ *fieldsInWhat = CreateDimensions(android::util::APP_CRASH_OCCURRED, {1 /*uid*/});
+ auto fieldsInState = stateLink->mutable_fields_in_state();
+ *fieldsInState = CreateDimensions(UID_PROCESS_STATE_ATOM_ID, {1 /*uid*/});
+
+ // Initialize StatsLogProcessor.
+ const uint64_t bucketStartTimeNs = 10000000000; // 0:10
+ const uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+
+ // Check that StateTrackers were properly initialized.
+ EXPECT_EQ(2, StateManager::getInstance().getStateTrackersCount());
+ EXPECT_EQ(1, StateManager::getInstance().getListenersCount(SCREEN_STATE_ATOM_ID));
+ EXPECT_EQ(1, StateManager::getInstance().getListenersCount(UID_PROCESS_STATE_ATOM_ID));
+
+ // Check that CountMetricProducer was initialized correctly.
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.size(), 2);
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(0), SCREEN_STATE_ATOM_ID);
+ EXPECT_EQ(metricProducer->mSlicedStateAtoms.at(1), UID_PROCESS_STATE_ATOM_ID);
+ EXPECT_EQ(metricProducer->mStateGroupMap.size(), 1);
+ EXPECT_EQ(metricProducer->mMetric2StateLinks.size(), 1);
+
+ StateMap map = state1.map();
+ for (auto group : map.group()) {
+ for (auto value : group.value()) {
+ EXPECT_EQ(metricProducer->mStateGroupMap[SCREEN_STATE_ATOM_ID][value],
+ group.group_id());
+ }
+ }
+
+ /*
+ bucket #1 bucket #2
+ | 1 2 3 4 5 6 7 8 9 10 (minutes)
+ |------------------------|------------------------|--
+ 1 1 1 1 1 2 1 1 2 (AppCrashEvents)
+ ---------------------------------------------------SCREEN_OFF events
+ | (ScreenUnknownEvent = 0)
+ | | (ScreenOffEvent = 1)
+ | (ScreenDozeEvent = 3)
+ ---------------------------------------------------SCREEN_ON events
+ | | (ScreenOnEvent = 2)
+ | (ScreenOnSuspendEvent = 6)
+ ---------------------------------------------------PROCESS STATE events
+ 1 2 (TopEvent = 1002)
+ 1 (ForegroundServiceEvent = 1003)
+ 2 (ImportantBackgroundEvent = 1006)
+ 1 1 1 (ImportantForegroundEvent = 1005)
+
+ Based on the diagram above, Screen State / Process State pairs for each
+ AppCrashEvent are:
+ - StateTracker::kStateUnknown / important foreground
+ - off / important foreground
+ - off / Top
+ - on / important foreground
+ - off / important foreground
+ - off / top
+
+ - off / important foreground
+ - off / foreground service
+ - on / important background
+
+ */
+ // Initialize log events - first bucket.
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 5 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND)); // 0:15
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 20 * NS_PER_SEC, 1 /*uid*/)); // 0:30
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 30 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_UNKNOWN)); // 0:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 60 * NS_PER_SEC, 1 /*uid*/)); // 1:10
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 90 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_TOP)); // 1:40
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 90 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF)); // 1:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 120 * NS_PER_SEC, 1 /*uid*/)); // 2:10
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 150 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND)); // 2:40
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 160 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON)); // 2:50
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 200 * NS_PER_SEC, 1 /*uid*/)); // 3:30
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 210 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_DOZE)); // 3:40
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 250 * NS_PER_SEC, 1 /*uid*/)); // 4:20
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 280 * NS_PER_SEC, 2 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_TOP)); // 4:50
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 285 * NS_PER_SEC, 2 /*uid*/)); // 4:55
+
+ // Initialize log events - second bucket.
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 360 * NS_PER_SEC, 1 /*uid*/)); // 6:10
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 380 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_FOREGROUND_SERVICE)); // 6:30
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 390 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON_SUSPEND)); // 6:40
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 420 * NS_PER_SEC, 2 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_BACKGROUND)); // 7:10
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 440 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF)); // 7:30
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 450 * NS_PER_SEC, 1 /*uid*/)); // 7:40
+ events.push_back(CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 520 * NS_PER_SEC,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON)); // 8:50
+ events.push_back(CreateUidProcessStateChangedEvent(
+ bucketStartTimeNs + 540 * NS_PER_SEC, 1 /*uid*/,
+ android::app::ProcessStateEnum::PROCESS_STATE_IMPORTANT_FOREGROUND)); // 9:10
+ events.push_back(
+ CreateAppCrashOccurredEvent(bucketStartTimeNs + 570 * NS_PER_SEC, 2 /*uid*/)); // 9:40
+
+ // Send log events to StatsLogProcessor.
+ for (auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ // Check dump report.
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs * 2 + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_count_metrics());
+ EXPECT_EQ(6, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ // For each CountMetricData, check StateValue info is correct and buckets
+ // have correct counts.
+ auto data = reports.reports(0).metrics(0).count_metrics().data(0);
+ EXPECT_EQ(2, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
+ EXPECT_TRUE(data.slice_by_state(1).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_FOREGROUND_SERVICE, data.slice_by_state(1).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(1);
+ EXPECT_EQ(2, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_value());
+ EXPECT_EQ(-1, data.slice_by_state(0).value());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
+ EXPECT_TRUE(data.slice_by_state(1).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(1).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(2);
+ EXPECT_EQ(2, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
+ EXPECT_TRUE(data.slice_by_state(1).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(1).value());
+ EXPECT_EQ(2, data.bucket_info_size());
+ EXPECT_EQ(2, data.bucket_info(0).count());
+ EXPECT_EQ(1, data.bucket_info(1).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(3);
+ EXPECT_EQ(2, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_ON"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
+ EXPECT_TRUE(data.slice_by_state(1).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_FOREGROUND, data.slice_by_state(1).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(4);
+ EXPECT_EQ(2, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_ON"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
+ EXPECT_TRUE(data.slice_by_state(1).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_IMPORTANT_BACKGROUND, data.slice_by_state(1).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+
+ data = reports.reports(0).metrics(0).count_metrics().data(5);
+ EXPECT_EQ(2, data.slice_by_state_size());
+ EXPECT_EQ(SCREEN_STATE_ATOM_ID, data.slice_by_state(0).atom_id());
+ EXPECT_TRUE(data.slice_by_state(0).has_group_id());
+ EXPECT_EQ(StringToId("SCREEN_OFF"), data.slice_by_state(0).group_id());
+ EXPECT_EQ(UID_PROCESS_STATE_ATOM_ID, data.slice_by_state(1).atom_id());
+ EXPECT_TRUE(data.slice_by_state(1).has_value());
+ EXPECT_EQ(android::app::PROCESS_STATE_TOP, data.slice_by_state(1).value());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(2, data.bucket_info(0).count());
+}
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/tests/e2e/DurationMetric_e2e_test.cpp b/cmds/statsd/tests/e2e/DurationMetric_e2e_test.cpp
index 8eb5f69..b586b06 100644
--- a/cmds/statsd/tests/e2e/DurationMetric_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/DurationMetric_e2e_test.cpp
@@ -26,688 +26,688 @@
#ifdef __ANDROID__
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(DurationMetricE2eTest, TestOneBucket) {
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
-// auto screenOffMatcher = CreateScreenTurnedOffAtomMatcher();
-// *config.add_atom_matcher() = screenOnMatcher;
-// *config.add_atom_matcher() = screenOffMatcher;
-//
-// auto durationPredicate = CreateScreenIsOnPredicate();
-// *config.add_predicate() = durationPredicate;
-//
-// int64_t metricId = 123456;
-// auto durationMetric = config.add_duration_metric();
-// durationMetric->set_id(metricId);
-// durationMetric->set_what(durationPredicate.id());
-// durationMetric->set_bucket(FIVE_MINUTES);
-// durationMetric->set_aggregation_type(DurationMetric_AggregationType_SUM);
-//
-//
-// const int64_t baseTimeNs = 0; // 0:00
-// const int64_t configAddedTimeNs = baseTimeNs + 1 * NS_PER_SEC; // 0:01
-// const int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey);
-//
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// // Screen is off at start of bucket.
-// event = CreateScreenStateChangedEvent(
-// android::view::DISPLAY_STATE_OFF, configAddedTimeNs); // 0:01
-// processor->OnLogEvent(event.get());
-//
-// // Turn screen on.
-// const int64_t durationStartNs = configAddedTimeNs + 10 * NS_PER_SEC; // 0:11
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, durationStartNs);
-// processor->OnLogEvent(event.get());
-//
-// // Turn off screen 30 seconds after turning on.
-// const int64_t durationEndNs = durationStartNs + 30 * NS_PER_SEC; // 0:41
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF, durationEndNs);
-// processor->OnLogEvent(event.get());
-//
-// event = CreateScreenBrightnessChangedEvent(64, durationEndNs + 1 * NS_PER_SEC); // 0:42
-// processor->OnLogEvent(event.get());
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + bucketSizeNs + 1 * NS_PER_SEC, false, true,
-// ADB_DUMP, FAST, &buffer); // 5:01
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(metricId, reports.reports(0).metrics(0).metric_id());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_duration_metrics());
-//
-// const StatsLogReport::DurationMetricDataWrapper& durationMetrics =
-// reports.reports(0).metrics(0).duration_metrics();
-// EXPECT_EQ(1, durationMetrics.data_size());
-//
-// auto data = durationMetrics.data(0);
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(durationEndNs - durationStartNs, data.bucket_info(0).duration_nanos());
-// EXPECT_EQ(configAddedTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
-//
-//TEST(DurationMetricE2eTest, TestTwoBuckets) {
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
-// auto screenOffMatcher = CreateScreenTurnedOffAtomMatcher();
-// *config.add_atom_matcher() = screenOnMatcher;
-// *config.add_atom_matcher() = screenOffMatcher;
-//
-// auto durationPredicate = CreateScreenIsOnPredicate();
-// *config.add_predicate() = durationPredicate;
-//
-// int64_t metricId = 123456;
-// auto durationMetric = config.add_duration_metric();
-// durationMetric->set_id(metricId);
-// durationMetric->set_what(durationPredicate.id());
-// durationMetric->set_bucket(FIVE_MINUTES);
-// durationMetric->set_aggregation_type(DurationMetric_AggregationType_SUM);
-//
-//
-// const int64_t baseTimeNs = 0; // 0:00
-// const int64_t configAddedTimeNs = baseTimeNs + 1 * NS_PER_SEC; // 0:01
-// const int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey);
-//
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// // Screen is off at start of bucket.
-// event = CreateScreenStateChangedEvent(
-// android::view::DISPLAY_STATE_OFF, configAddedTimeNs); // 0:01
-// processor->OnLogEvent(event.get());
-//
-// // Turn screen on.
-// const int64_t durationStartNs = configAddedTimeNs + 10 * NS_PER_SEC; // 0:11
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, durationStartNs);
-// processor->OnLogEvent(event.get());
-//
-// // Turn off screen 30 seconds after turning on.
-// const int64_t durationEndNs = durationStartNs + 30 * NS_PER_SEC; // 0:41
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF, durationEndNs);
-// processor->OnLogEvent(event.get());
-//
-// event = CreateScreenBrightnessChangedEvent(64, durationEndNs + 1 * NS_PER_SEC); // 0:42
-// processor->OnLogEvent(event.get());
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 2 * bucketSizeNs + 1 * NS_PER_SEC, false, true,
-// ADB_DUMP, FAST, &buffer); // 10:01
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(metricId, reports.reports(0).metrics(0).metric_id());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_duration_metrics());
-//
-// const StatsLogReport::DurationMetricDataWrapper& durationMetrics =
-// reports.reports(0).metrics(0).duration_metrics();
-// EXPECT_EQ(1, durationMetrics.data_size());
-//
-// auto data = durationMetrics.data(0);
-// EXPECT_EQ(1, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(0, bucketInfo.bucket_num());
-// EXPECT_EQ(durationEndNs - durationStartNs, bucketInfo.duration_nanos());
-// EXPECT_EQ(configAddedTimeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-//}
-//
-//TEST(DurationMetricE2eTest, TestWithActivation) {
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-//
-// auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
-// auto screenOffMatcher = CreateScreenTurnedOffAtomMatcher();
-// auto crashMatcher = CreateProcessCrashAtomMatcher();
-// *config.add_atom_matcher() = screenOnMatcher;
-// *config.add_atom_matcher() = screenOffMatcher;
-// *config.add_atom_matcher() = crashMatcher;
-//
-// auto durationPredicate = CreateScreenIsOnPredicate();
-// *config.add_predicate() = durationPredicate;
-//
-// int64_t metricId = 123456;
-// auto durationMetric = config.add_duration_metric();
-// durationMetric->set_id(metricId);
-// durationMetric->set_what(durationPredicate.id());
-// durationMetric->set_bucket(FIVE_MINUTES);
-// durationMetric->set_aggregation_type(DurationMetric_AggregationType_SUM);
-//
-// auto metric_activation1 = config.add_metric_activation();
-// metric_activation1->set_metric_id(metricId);
-// auto event_activation1 = metric_activation1->add_event_activation();
-// event_activation1->set_atom_matcher_id(crashMatcher.id());
-// event_activation1->set_ttl_seconds(30); // 30 secs.
-//
-// const int64_t bucketStartTimeNs = 10000000000;
-// const int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// sp<UidMap> m = new UidMap();
-// sp<StatsPullerManager> pullerManager = new StatsPullerManager();
-// sp<AlarmMonitor> anomalyAlarmMonitor;
-// sp<AlarmMonitor> subscriberAlarmMonitor;
-// vector<int64_t> activeConfigsBroadcast;
-//
-// int broadcastCount = 0;
-// StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
-// bucketStartTimeNs, [](const ConfigKey& key) { return true; },
-// [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
-// const vector<int64_t>& activeConfigs) {
-// broadcastCount++;
-// EXPECT_EQ(broadcastUid, uid);
-// activeConfigsBroadcast.clear();
-// activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
-// activeConfigs.begin(), activeConfigs.end());
-// return true;
-// });
-//
-// processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config); // 0:00
-//
-// EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-//
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap.size(), 1u);
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// // Turn screen off.
-// event = CreateScreenStateChangedEvent(
-// android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + 2 * NS_PER_SEC); // 0:02
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 2 * NS_PER_SEC);
-//
-// // Turn screen on.
-// const int64_t durationStartNs = bucketStartTimeNs + 5 * NS_PER_SEC; // 0:05
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, durationStartNs);
-// processor.OnLogEvent(event.get(), durationStartNs);
-//
-// // Activate metric.
-// const int64_t activationStartNs = bucketStartTimeNs + 5 * NS_PER_SEC; // 0:10
-// const int64_t activationEndNs =
-// activationStartNs + event_activation1->ttl_seconds() * NS_PER_SEC; // 0:40
-// event = CreateAppCrashEvent(111, activationStartNs);
-// processor.OnLogEvent(event.get(), activationStartNs);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, activationStartNs);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// // Expire activation.
-// const int64_t expirationNs = activationEndNs + 7 * NS_PER_SEC;
-// event = CreateScreenBrightnessChangedEvent(64, expirationNs); // 0:47
-// processor.OnLogEvent(event.get(), expirationNs);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 2);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap.size(), 1u);
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, activationStartNs);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// // Turn off screen 10 seconds after activation expiration.
-// const int64_t durationEndNs = activationEndNs + 10 * NS_PER_SEC; // 0:50
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF, durationEndNs);
-// processor.OnLogEvent(event.get(),durationEndNs);
-//
-// // Turn screen on.
-// const int64_t duration2StartNs = durationEndNs + 5 * NS_PER_SEC; // 0:55
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, duration2StartNs);
-// processor.OnLogEvent(event.get(), duration2StartNs);
-//
-// // Turn off screen.
-// const int64_t duration2EndNs = duration2StartNs + 10 * NS_PER_SEC; // 1:05
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF, duration2EndNs);
-// processor.OnLogEvent(event.get(), duration2EndNs);
-//
-// // Activate metric.
-// const int64_t activation2StartNs = duration2EndNs + 5 * NS_PER_SEC; // 1:10
-// const int64_t activation2EndNs =
-// activation2StartNs + event_activation1->ttl_seconds() * NS_PER_SEC; // 1:40
-// event = CreateAppCrashEvent(211, activation2StartNs);
-// processor.OnLogEvent(event.get(), activation2StartNs);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, activation2StartNs);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor.onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1 * NS_PER_SEC, false, true,
-// ADB_DUMP, FAST, &buffer); // 5:01
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(metricId, reports.reports(0).metrics(0).metric_id());
-// EXPECT_TRUE(reports.reports(0).metrics(0).has_duration_metrics());
-//
-// const StatsLogReport::DurationMetricDataWrapper& durationMetrics =
-// reports.reports(0).metrics(0).duration_metrics();
-// EXPECT_EQ(1, durationMetrics.data_size());
-//
-// auto data = durationMetrics.data(0);
-// EXPECT_EQ(1, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(0, bucketInfo.bucket_num());
-// EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(expirationNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ(expirationNs - durationStartNs, bucketInfo.duration_nanos());
-//}
-//
-//TEST(DurationMetricE2eTest, TestWithCondition) {
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-// *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
-// *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
-// *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
-// *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
-//
-// auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
-// *config.add_predicate() = holdingWakelockPredicate;
-//
-// auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
-// *config.add_predicate() = isInBackgroundPredicate;
-//
-// auto durationMetric = config.add_duration_metric();
-// durationMetric->set_id(StringToId("WakelockDuration"));
-// durationMetric->set_what(holdingWakelockPredicate.id());
-// durationMetric->set_condition(isInBackgroundPredicate.id());
-// durationMetric->set_aggregation_type(DurationMetric::SUM);
-// durationMetric->set_bucket(FIVE_MINUTES);
-//
-// ConfigKey cfgKey;
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_TRUE(eventActivationMap.empty());
-//
-// int appUid = 123;
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(appUid, "App1")};
-//
-// auto event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 10 * NS_PER_SEC); // 0:10
-// processor->OnLogEvent(event.get());
-//
-// event = CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + 22 * NS_PER_SEC); // 0:22
-// processor->OnLogEvent(event.get());
-//
-// event = CreateMoveToForegroundEvent(
-// appUid, bucketStartTimeNs + (3 * 60 + 15) * NS_PER_SEC); // 3:15
-// processor->OnLogEvent(event.get());
-//
-// event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 4 * 60 * NS_PER_SEC); // 4:00
-// processor->OnLogEvent(event.get());
-//
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(1, reports.reports(0).metrics(0).duration_metrics().data_size());
-//
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-//
-// // Validate bucket info.
-// EXPECT_EQ(1, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ((2 * 60 + 53) * NS_PER_SEC, bucketInfo.duration_nanos());
-//}
-//
-//TEST(DurationMetricE2eTest, TestWithSlicedCondition) {
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-// auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
-// *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
-// *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
-// *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
-// *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
-//
-// auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
-// // The predicate is dimensioning by first attribution node by uid.
-// FieldMatcher dimensions = CreateAttributionUidDimensions(
-// android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
-// *holdingWakelockPredicate.mutable_simple_predicate()->mutable_dimensions() = dimensions;
-// *config.add_predicate() = holdingWakelockPredicate;
-//
-// auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
-// *isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
-// CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {Position::FIRST});
-// *config.add_predicate() = isInBackgroundPredicate;
-//
-// auto durationMetric = config.add_duration_metric();
-// durationMetric->set_id(StringToId("WakelockDuration"));
-// durationMetric->set_what(holdingWakelockPredicate.id());
-// durationMetric->set_condition(isInBackgroundPredicate.id());
-// durationMetric->set_aggregation_type(DurationMetric::SUM);
-// // The metric is dimensioning by first attribution node and only by uid.
-// *durationMetric->mutable_dimensions_in_what() =
-// CreateAttributionUidDimensions(
-// android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
-// durationMetric->set_bucket(FIVE_MINUTES);
-//
-// // Links between wakelock state atom and condition of app is in background.
-// auto links = durationMetric->add_links();
-// links->set_condition(isInBackgroundPredicate.id());
-// auto dimensionWhat = links->mutable_fields_in_what();
-// dimensionWhat->set_field(android::util::WAKELOCK_STATE_CHANGED);
-// dimensionWhat->add_child()->set_field(1); // uid field.
-// *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
-// android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, { Position::FIRST });
-//
-// ConfigKey cfgKey;
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_TRUE(eventActivationMap.empty());
-//
-// int appUid = 123;
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(appUid, "App1")};
-//
-// auto event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 10 * NS_PER_SEC); // 0:10
-// processor->OnLogEvent(event.get());
-//
-// event = CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + 22 * NS_PER_SEC); // 0:22
-// processor->OnLogEvent(event.get());
-//
-// event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 60 * NS_PER_SEC); // 1:00
-// processor->OnLogEvent(event.get());
-//
-//
-// event = CreateMoveToForegroundEvent(
-// appUid, bucketStartTimeNs + (3 * 60 + 15) * NS_PER_SEC); // 3:15
-// processor->OnLogEvent(event.get());
-//
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(1, reports.reports(0).metrics(0).duration_metrics().data_size());
-//
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// // Validate dimension value.
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, appUid);
-// // Validate bucket info.
-// EXPECT_EQ(1, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ(38 * NS_PER_SEC, bucketInfo.duration_nanos());
-//}
-//
-//TEST(DurationMetricE2eTest, TestWithActivationAndSlicedCondition) {
-// StatsdConfig config;
-// config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
-// auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
-// *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
-// *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
-// *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
-// *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
-// *config.add_atom_matcher() = screenOnMatcher;
-//
-// auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
-// // The predicate is dimensioning by first attribution node by uid.
-// FieldMatcher dimensions = CreateAttributionUidDimensions(
-// android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
-// *holdingWakelockPredicate.mutable_simple_predicate()->mutable_dimensions() = dimensions;
-// *config.add_predicate() = holdingWakelockPredicate;
-//
-// auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
-// *isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
-// CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {Position::FIRST});
-// *config.add_predicate() = isInBackgroundPredicate;
-//
-// auto durationMetric = config.add_duration_metric();
-// durationMetric->set_id(StringToId("WakelockDuration"));
-// durationMetric->set_what(holdingWakelockPredicate.id());
-// durationMetric->set_condition(isInBackgroundPredicate.id());
-// durationMetric->set_aggregation_type(DurationMetric::SUM);
-// // The metric is dimensioning by first attribution node and only by uid.
-// *durationMetric->mutable_dimensions_in_what() =
-// CreateAttributionUidDimensions(
-// android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
-// durationMetric->set_bucket(FIVE_MINUTES);
-//
-// // Links between wakelock state atom and condition of app is in background.
-// auto links = durationMetric->add_links();
-// links->set_condition(isInBackgroundPredicate.id());
-// auto dimensionWhat = links->mutable_fields_in_what();
-// dimensionWhat->set_field(android::util::WAKELOCK_STATE_CHANGED);
-// dimensionWhat->add_child()->set_field(1); // uid field.
-// *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
-// android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, { Position::FIRST });
-//
-// auto metric_activation1 = config.add_metric_activation();
-// metric_activation1->set_metric_id(durationMetric->id());
-// auto event_activation1 = metric_activation1->add_event_activation();
-// event_activation1->set_atom_matcher_id(screenOnMatcher.id());
-// event_activation1->set_ttl_seconds(60 * 2); // 2 minutes.
-//
-// ConfigKey cfgKey;
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap.size(), 1u);
-// EXPECT_TRUE(eventActivationMap.find(4) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[4]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// int appUid = 123;
-// std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(appUid, "App1")};
-//
-// auto event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + 10 * NS_PER_SEC); // 0:10
-// processor->OnLogEvent(event.get());
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[4]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// event = CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + 22 * NS_PER_SEC); // 0:22
-// processor->OnLogEvent(event.get());
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[4]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// const int64_t durationStartNs = bucketStartTimeNs + 30 * NS_PER_SEC; // 0:30
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, durationStartNs);
-// processor->OnLogEvent(event.get());
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[4]->start_ns, durationStartNs);
-// EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// const int64_t durationEndNs =
-// durationStartNs + (event_activation1->ttl_seconds() + 30) * NS_PER_SEC; // 3:00
-// event = CreateAppCrashEvent(333, durationEndNs);
-// processor->OnLogEvent(event.get());
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[4]->start_ns, durationStartNs);
-// EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// event = CreateMoveToForegroundEvent(
-// appUid, bucketStartTimeNs + (3 * 60 + 15) * NS_PER_SEC); // 3:15
-// processor->OnLogEvent(event.get());
-//
-// event = CreateReleaseWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + (4 * 60 + 17) * NS_PER_SEC); // 4:17
-// processor->OnLogEvent(event.get());
-//
-// event = CreateMoveToBackgroundEvent(
-// appUid, bucketStartTimeNs + (4 * 60 + 20) * NS_PER_SEC); // 4:20
-// processor->OnLogEvent(event.get());
-//
-// event = CreateAcquireWakelockEvent(
-// attributions1, "wl1", bucketStartTimeNs + (4 * 60 + 25) * NS_PER_SEC); // 4:25
-// processor->OnLogEvent(event.get());
-//
-// const int64_t duration2StartNs = bucketStartTimeNs + (4 * 60 + 30) * NS_PER_SEC; // 4:30
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, duration2StartNs);
-// processor->OnLogEvent(event.get());
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[4]->start_ns, duration2StartNs);
-// EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
-//
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_GT(buffer.size(), 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(1, reports.reports(0).metrics(0).duration_metrics().data_size());
-//
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// // Validate dimension value.
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, appUid);
-// // Validate bucket info.
-// EXPECT_EQ(2, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(durationEndNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ(durationEndNs - durationStartNs, bucketInfo.duration_nanos());
-//
-// bucketInfo = data.bucket_info(1);
-// EXPECT_EQ(durationEndNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - duration2StartNs, bucketInfo.duration_nanos());
-//}
+TEST(DurationMetricE2eTest, TestOneBucket) {
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+ auto screenOffMatcher = CreateScreenTurnedOffAtomMatcher();
+ *config.add_atom_matcher() = screenOnMatcher;
+ *config.add_atom_matcher() = screenOffMatcher;
+
+ auto durationPredicate = CreateScreenIsOnPredicate();
+ *config.add_predicate() = durationPredicate;
+
+ int64_t metricId = 123456;
+ auto durationMetric = config.add_duration_metric();
+ durationMetric->set_id(metricId);
+ durationMetric->set_what(durationPredicate.id());
+ durationMetric->set_bucket(FIVE_MINUTES);
+ durationMetric->set_aggregation_type(DurationMetric_AggregationType_SUM);
+
+ const int64_t baseTimeNs = 0; // 0:00
+ const int64_t configAddedTimeNs = baseTimeNs + 1 * NS_PER_SEC; // 0:01
+ const int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey);
+
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+
+ std::unique_ptr<LogEvent> event;
+
+ // Screen is off at start of bucket.
+ event = CreateScreenStateChangedEvent(configAddedTimeNs,
+ android::view::DISPLAY_STATE_OFF); // 0:01
+ processor->OnLogEvent(event.get());
+
+ // Turn screen on.
+ const int64_t durationStartNs = configAddedTimeNs + 10 * NS_PER_SEC; // 0:11
+ event = CreateScreenStateChangedEvent(durationStartNs, android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(event.get());
+
+ // Turn off screen 30 seconds after turning on.
+ const int64_t durationEndNs = durationStartNs + 30 * NS_PER_SEC; // 0:41
+ event = CreateScreenStateChangedEvent(durationEndNs, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(event.get());
+
+ event = CreateScreenBrightnessChangedEvent(durationEndNs + 1 * NS_PER_SEC, 64); // 0:42
+ processor->OnLogEvent(event.get());
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + bucketSizeNs + 1 * NS_PER_SEC, false, true,
+ ADB_DUMP, FAST, &buffer); // 5:01
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(metricId, reports.reports(0).metrics(0).metric_id());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_duration_metrics());
+
+ const StatsLogReport::DurationMetricDataWrapper& durationMetrics =
+ reports.reports(0).metrics(0).duration_metrics();
+ EXPECT_EQ(1, durationMetrics.data_size());
+
+ auto data = durationMetrics.data(0);
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(durationEndNs - durationStartNs, data.bucket_info(0).duration_nanos());
+ EXPECT_EQ(configAddedTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(DurationMetricE2eTest, TestTwoBuckets) {
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+ auto screenOffMatcher = CreateScreenTurnedOffAtomMatcher();
+ *config.add_atom_matcher() = screenOnMatcher;
+ *config.add_atom_matcher() = screenOffMatcher;
+
+ auto durationPredicate = CreateScreenIsOnPredicate();
+ *config.add_predicate() = durationPredicate;
+
+ int64_t metricId = 123456;
+ auto durationMetric = config.add_duration_metric();
+ durationMetric->set_id(metricId);
+ durationMetric->set_what(durationPredicate.id());
+ durationMetric->set_bucket(FIVE_MINUTES);
+ durationMetric->set_aggregation_type(DurationMetric_AggregationType_SUM);
+
+ const int64_t baseTimeNs = 0; // 0:00
+ const int64_t configAddedTimeNs = baseTimeNs + 1 * NS_PER_SEC; // 0:01
+ const int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey);
+
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+
+ std::unique_ptr<LogEvent> event;
+
+ // Screen is off at start of bucket.
+ event = CreateScreenStateChangedEvent(configAddedTimeNs,
+ android::view::DISPLAY_STATE_OFF); // 0:01
+ processor->OnLogEvent(event.get());
+
+ // Turn screen on.
+ const int64_t durationStartNs = configAddedTimeNs + 10 * NS_PER_SEC; // 0:11
+ event = CreateScreenStateChangedEvent(durationStartNs, android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(event.get());
+
+ // Turn off screen 30 seconds after turning on.
+ const int64_t durationEndNs = durationStartNs + 30 * NS_PER_SEC; // 0:41
+ event = CreateScreenStateChangedEvent(durationEndNs, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(event.get());
+
+ event = CreateScreenBrightnessChangedEvent(durationEndNs + 1 * NS_PER_SEC, 64); // 0:42
+ processor->OnLogEvent(event.get());
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 2 * bucketSizeNs + 1 * NS_PER_SEC, false,
+ true, ADB_DUMP, FAST, &buffer); // 10:01
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(metricId, reports.reports(0).metrics(0).metric_id());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_duration_metrics());
+
+ const StatsLogReport::DurationMetricDataWrapper& durationMetrics =
+ reports.reports(0).metrics(0).duration_metrics();
+ EXPECT_EQ(1, durationMetrics.data_size());
+
+ auto data = durationMetrics.data(0);
+ EXPECT_EQ(1, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(0, bucketInfo.bucket_num());
+ EXPECT_EQ(durationEndNs - durationStartNs, bucketInfo.duration_nanos());
+ EXPECT_EQ(configAddedTimeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+}
+
+TEST(DurationMetricE2eTest, TestWithActivation) {
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+
+ auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+ auto screenOffMatcher = CreateScreenTurnedOffAtomMatcher();
+ auto crashMatcher = CreateProcessCrashAtomMatcher();
+ *config.add_atom_matcher() = screenOnMatcher;
+ *config.add_atom_matcher() = screenOffMatcher;
+ *config.add_atom_matcher() = crashMatcher;
+
+ auto durationPredicate = CreateScreenIsOnPredicate();
+ *config.add_predicate() = durationPredicate;
+
+ int64_t metricId = 123456;
+ auto durationMetric = config.add_duration_metric();
+ durationMetric->set_id(metricId);
+ durationMetric->set_what(durationPredicate.id());
+ durationMetric->set_bucket(FIVE_MINUTES);
+ durationMetric->set_aggregation_type(DurationMetric_AggregationType_SUM);
+
+ auto metric_activation1 = config.add_metric_activation();
+ metric_activation1->set_metric_id(metricId);
+ auto event_activation1 = metric_activation1->add_event_activation();
+ event_activation1->set_atom_matcher_id(crashMatcher.id());
+ event_activation1->set_ttl_seconds(30); // 30 secs.
+
+ const int64_t bucketStartTimeNs = 10000000000;
+ const int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ sp<UidMap> m = new UidMap();
+ sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+ sp<AlarmMonitor> anomalyAlarmMonitor;
+ sp<AlarmMonitor> subscriberAlarmMonitor;
+ vector<int64_t> activeConfigsBroadcast;
+
+ int broadcastCount = 0;
+ StatsLogProcessor processor(
+ m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, bucketStartTimeNs,
+ [](const ConfigKey& key) { return true; },
+ [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+ const vector<int64_t>& activeConfigs) {
+ broadcastCount++;
+ EXPECT_EQ(broadcastUid, uid);
+ activeConfigsBroadcast.clear();
+ activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
+ activeConfigs.end());
+ return true;
+ });
+
+ processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config); // 0:00
+
+ EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap.size(), 1u);
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ std::unique_ptr<LogEvent> event;
+
+ // Turn screen off.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * NS_PER_SEC,
+ android::view::DISPLAY_STATE_OFF); // 0:02
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 2 * NS_PER_SEC);
+
+ // Turn screen on.
+ const int64_t durationStartNs = bucketStartTimeNs + 5 * NS_PER_SEC; // 0:05
+ event = CreateScreenStateChangedEvent(durationStartNs, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), durationStartNs);
+
+ // Activate metric.
+ const int64_t activationStartNs = bucketStartTimeNs + 5 * NS_PER_SEC; // 0:10
+ const int64_t activationEndNs =
+ activationStartNs + event_activation1->ttl_seconds() * NS_PER_SEC; // 0:40
+ event = CreateAppCrashEvent(activationStartNs, 111);
+ processor.OnLogEvent(event.get(), activationStartNs);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, activationStartNs);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ // Expire activation.
+ const int64_t expirationNs = activationEndNs + 7 * NS_PER_SEC;
+ event = CreateScreenBrightnessChangedEvent(expirationNs, 64); // 0:47
+ processor.OnLogEvent(event.get(), expirationNs);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 2);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap.size(), 1u);
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, activationStartNs);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ // Turn off screen 10 seconds after activation expiration.
+ const int64_t durationEndNs = activationEndNs + 10 * NS_PER_SEC; // 0:50
+ event = CreateScreenStateChangedEvent(durationEndNs, android::view::DISPLAY_STATE_OFF);
+ processor.OnLogEvent(event.get(), durationEndNs);
+
+ // Turn screen on.
+ const int64_t duration2StartNs = durationEndNs + 5 * NS_PER_SEC; // 0:55
+ event = CreateScreenStateChangedEvent(duration2StartNs, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), duration2StartNs);
+
+ // Turn off screen.
+ const int64_t duration2EndNs = duration2StartNs + 10 * NS_PER_SEC; // 1:05
+ event = CreateScreenStateChangedEvent(duration2EndNs, android::view::DISPLAY_STATE_OFF);
+ processor.OnLogEvent(event.get(), duration2EndNs);
+
+ // Activate metric.
+ const int64_t activation2StartNs = duration2EndNs + 5 * NS_PER_SEC; // 1:10
+ const int64_t activation2EndNs =
+ activation2StartNs + event_activation1->ttl_seconds() * NS_PER_SEC; // 1:40
+ event = CreateAppCrashEvent(activation2StartNs, 211);
+ processor.OnLogEvent(event.get(), activation2StartNs);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, activation2StartNs);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor.onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1 * NS_PER_SEC, false, true,
+ ADB_DUMP, FAST, &buffer); // 5:01
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(metricId, reports.reports(0).metrics(0).metric_id());
+ EXPECT_TRUE(reports.reports(0).metrics(0).has_duration_metrics());
+
+ const StatsLogReport::DurationMetricDataWrapper& durationMetrics =
+ reports.reports(0).metrics(0).duration_metrics();
+ EXPECT_EQ(1, durationMetrics.data_size());
+
+ auto data = durationMetrics.data(0);
+ EXPECT_EQ(1, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(0, bucketInfo.bucket_num());
+ EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(expirationNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ(expirationNs - durationStartNs, bucketInfo.duration_nanos());
+}
+
+TEST(DurationMetricE2eTest, TestWithCondition) {
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+ *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
+
+ auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
+ *config.add_predicate() = holdingWakelockPredicate;
+
+ auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
+ *config.add_predicate() = isInBackgroundPredicate;
+
+ auto durationMetric = config.add_duration_metric();
+ durationMetric->set_id(StringToId("WakelockDuration"));
+ durationMetric->set_what(holdingWakelockPredicate.id());
+ durationMetric->set_condition(isInBackgroundPredicate.id());
+ durationMetric->set_aggregation_type(DurationMetric::SUM);
+ durationMetric->set_bucket(FIVE_MINUTES);
+
+ ConfigKey cfgKey;
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_TRUE(eventActivationMap.empty());
+
+ int appUid = 123;
+ vector<int> attributionUids1 = {appUid};
+ vector<string> attributionTags1 = {"App1"};
+
+ auto event = CreateAcquireWakelockEvent(bucketStartTimeNs + 10 * NS_PER_SEC, attributionUids1,
+ attributionTags1,
+ "wl1"); // 0:10
+ processor->OnLogEvent(event.get());
+
+ event = CreateMoveToBackgroundEvent(bucketStartTimeNs + 22 * NS_PER_SEC, appUid); // 0:22
+ processor->OnLogEvent(event.get());
+
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + (3 * 60 + 15) * NS_PER_SEC,
+ appUid); // 3:15
+ processor->OnLogEvent(event.get());
+
+ event = CreateReleaseWakelockEvent(bucketStartTimeNs + 4 * 60 * NS_PER_SEC, attributionUids1,
+ attributionTags1,
+ "wl1"); // 4:00
+ processor->OnLogEvent(event.get());
+
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(1, reports.reports(0).metrics(0).duration_metrics().data_size());
+
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+
+ // Validate bucket info.
+ EXPECT_EQ(1, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ((2 * 60 + 53) * NS_PER_SEC, bucketInfo.duration_nanos());
+}
+
+TEST(DurationMetricE2eTest, TestWithSlicedCondition) {
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+ auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+ *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
+
+ auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
+ // The predicate is dimensioning by first attribution node by uid.
+ FieldMatcher dimensions = CreateAttributionUidDimensions(android::util::WAKELOCK_STATE_CHANGED,
+ {Position::FIRST});
+ *holdingWakelockPredicate.mutable_simple_predicate()->mutable_dimensions() = dimensions;
+ *config.add_predicate() = holdingWakelockPredicate;
+
+ auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
+ *isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
+ CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {Position::FIRST});
+ *config.add_predicate() = isInBackgroundPredicate;
+
+ auto durationMetric = config.add_duration_metric();
+ durationMetric->set_id(StringToId("WakelockDuration"));
+ durationMetric->set_what(holdingWakelockPredicate.id());
+ durationMetric->set_condition(isInBackgroundPredicate.id());
+ durationMetric->set_aggregation_type(DurationMetric::SUM);
+ // The metric is dimensioning by first attribution node and only by uid.
+ *durationMetric->mutable_dimensions_in_what() = CreateAttributionUidDimensions(
+ android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
+ durationMetric->set_bucket(FIVE_MINUTES);
+
+ // Links between wakelock state atom and condition of app is in background.
+ auto links = durationMetric->add_links();
+ links->set_condition(isInBackgroundPredicate.id());
+ auto dimensionWhat = links->mutable_fields_in_what();
+ dimensionWhat->set_field(android::util::WAKELOCK_STATE_CHANGED);
+ dimensionWhat->add_child()->set_field(1); // uid field.
+ *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
+ android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {Position::FIRST});
+
+ ConfigKey cfgKey;
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_TRUE(eventActivationMap.empty());
+
+ int appUid = 123;
+ std::vector<int> attributionUids1 = {appUid};
+ std::vector<string> attributionTags1 = {"App1"};
+
+ auto event = CreateAcquireWakelockEvent(bucketStartTimeNs + 10 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "wl1"); // 0:10
+ processor->OnLogEvent(event.get());
+
+ event = CreateMoveToBackgroundEvent(bucketStartTimeNs + 22 * NS_PER_SEC, appUid); // 0:22
+ processor->OnLogEvent(event.get());
+
+ event = CreateReleaseWakelockEvent(bucketStartTimeNs + 60 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "wl1"); // 1:00
+ processor->OnLogEvent(event.get());
+
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + (3 * 60 + 15) * NS_PER_SEC,
+ appUid); // 3:15
+ processor->OnLogEvent(event.get());
+
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(1, reports.reports(0).metrics(0).duration_metrics().data_size());
+
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ // Validate dimension value.
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, appUid);
+ // Validate bucket info.
+ EXPECT_EQ(1, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ(38 * NS_PER_SEC, bucketInfo.duration_nanos());
+}
+
+TEST(DurationMetricE2eTest, TestWithActivationAndSlicedCondition) {
+ StatsdConfig config;
+ config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+ auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+ *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
+ *config.add_atom_matcher() = screenOnMatcher;
+
+ auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
+ // The predicate is dimensioning by first attribution node by uid.
+ FieldMatcher dimensions = CreateAttributionUidDimensions(android::util::WAKELOCK_STATE_CHANGED,
+ {Position::FIRST});
+ *holdingWakelockPredicate.mutable_simple_predicate()->mutable_dimensions() = dimensions;
+ *config.add_predicate() = holdingWakelockPredicate;
+
+ auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
+ *isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
+ CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {Position::FIRST});
+ *config.add_predicate() = isInBackgroundPredicate;
+
+ auto durationMetric = config.add_duration_metric();
+ durationMetric->set_id(StringToId("WakelockDuration"));
+ durationMetric->set_what(holdingWakelockPredicate.id());
+ durationMetric->set_condition(isInBackgroundPredicate.id());
+ durationMetric->set_aggregation_type(DurationMetric::SUM);
+ // The metric is dimensioning by first attribution node and only by uid.
+ *durationMetric->mutable_dimensions_in_what() = CreateAttributionUidDimensions(
+ android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
+ durationMetric->set_bucket(FIVE_MINUTES);
+
+ // Links between wakelock state atom and condition of app is in background.
+ auto links = durationMetric->add_links();
+ links->set_condition(isInBackgroundPredicate.id());
+ auto dimensionWhat = links->mutable_fields_in_what();
+ dimensionWhat->set_field(android::util::WAKELOCK_STATE_CHANGED);
+ dimensionWhat->add_child()->set_field(1); // uid field.
+ *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
+ android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {Position::FIRST});
+
+ auto metric_activation1 = config.add_metric_activation();
+ metric_activation1->set_metric_id(durationMetric->id());
+ auto event_activation1 = metric_activation1->add_event_activation();
+ event_activation1->set_atom_matcher_id(screenOnMatcher.id());
+ event_activation1->set_ttl_seconds(60 * 2); // 2 minutes.
+
+ ConfigKey cfgKey;
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor->mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap.size(), 1u);
+ EXPECT_TRUE(eventActivationMap.find(4) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[4]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ int appUid = 123;
+ std::vector<int> attributionUids1 = {appUid};
+ std::vector<string> attributionTags1 = {"App1"};
+
+ auto event = CreateAcquireWakelockEvent(bucketStartTimeNs + 10 * NS_PER_SEC, attributionUids1,
+ attributionTags1, "wl1"); // 0:10
+ processor->OnLogEvent(event.get());
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[4]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ event = CreateMoveToBackgroundEvent(bucketStartTimeNs + 22 * NS_PER_SEC, appUid); // 0:22
+ processor->OnLogEvent(event.get());
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[4]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ const int64_t durationStartNs = bucketStartTimeNs + 30 * NS_PER_SEC; // 0:30
+ event = CreateScreenStateChangedEvent(durationStartNs, android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(event.get());
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[4]->start_ns, durationStartNs);
+ EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ const int64_t durationEndNs =
+ durationStartNs + (event_activation1->ttl_seconds() + 30) * NS_PER_SEC; // 3:00
+ event = CreateAppCrashEvent(durationEndNs, 333);
+ processor->OnLogEvent(event.get());
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[4]->start_ns, durationStartNs);
+ EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + (3 * 60 + 15) * NS_PER_SEC,
+ appUid); // 3:15
+ processor->OnLogEvent(event.get());
+
+ event = CreateReleaseWakelockEvent(bucketStartTimeNs + (4 * 60 + 17) * NS_PER_SEC,
+ attributionUids1, attributionTags1, "wl1"); // 4:17
+ processor->OnLogEvent(event.get());
+
+ event = CreateMoveToBackgroundEvent(bucketStartTimeNs + (4 * 60 + 20) * NS_PER_SEC,
+ appUid); // 4:20
+ processor->OnLogEvent(event.get());
+
+ event = CreateAcquireWakelockEvent(bucketStartTimeNs + (4 * 60 + 25) * NS_PER_SEC,
+ attributionUids1, attributionTags1, "wl1"); // 4:25
+ processor->OnLogEvent(event.get());
+
+ const int64_t duration2StartNs = bucketStartTimeNs + (4 * 60 + 30) * NS_PER_SEC; // 4:30
+ event = CreateScreenStateChangedEvent(duration2StartNs, android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(event.get());
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[4]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[4]->start_ns, duration2StartNs);
+ EXPECT_EQ(eventActivationMap[4]->ttl_ns, event_activation1->ttl_seconds() * NS_PER_SEC);
+
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_GT(buffer.size(), 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(1, reports.reports(0).metrics(0).duration_metrics().data_size());
+
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ // Validate dimension value.
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, appUid);
+ // Validate bucket info.
+ EXPECT_EQ(2, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(bucketStartTimeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(durationEndNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ(durationEndNs - durationStartNs, bucketInfo.duration_nanos());
+
+ bucketInfo = data.bucket_info(1);
+ EXPECT_EQ(durationEndNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - duration2StartNs, bucketInfo.duration_nanos());
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp b/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp
index 7f651d4..594c1e6 100644
--- a/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp
+++ b/cmds/statsd/tests/e2e/GaugeMetric_e2e_pull_test.cpp
@@ -65,482 +65,465 @@
} // namespaces
-// TODO(b/149590301): Update this test to use new socket schema.
-//TEST(GaugeMetricE2eTest, TestRandomSamplePulledEvents) {
-// auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE);
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// ATOM_TAG);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-//
-// // When creating the config, the gauge metric producer should register the alarm at the
-// // end of the current bucket.
-// EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
-// EXPECT_EQ(bucketSizeNs,
-// processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
-// int64_t& nextPullTimeNs =
-// processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, nextPullTimeNs);
-//
-// auto screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 55);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// // Pulling alarm arrives on time and reset the sequential pulling alarm.
-// processor->informPullAlarmFired(nextPullTimeNs + 1);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, nextPullTimeNs);
-//
-// auto screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + bucketSizeNs + 10);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + bucketSizeNs + 100);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// processor->informPullAlarmFired(nextPullTimeNs + 1);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs,
-// nextPullTimeNs);
-//
-// processor->informPullAlarmFired(nextPullTimeNs + 1);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, nextPullTimeNs);
-//
-// screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 3 * bucketSizeNs + 2);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// processor->informPullAlarmFired(nextPullTimeNs + 3);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, nextPullTimeNs);
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 5 * bucketSizeNs + 1);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// processor->informPullAlarmFired(nextPullTimeNs + 2);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 6 * bucketSizeNs, nextPullTimeNs);
-//
-// processor->informPullAlarmFired(nextPullTimeNs + 2);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
-// EXPECT_GT((int)gaugeMetrics.data_size(), 1);
-//
-// auto data = gaugeMetrics.data(0);
-// EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// EXPECT_EQ(6, data.bucket_info_size());
-//
-// EXPECT_EQ(1, data.bucket_info(0).atom_size());
-// EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(1).atom_size());
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 1,
-// data.bucket_info(1).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 1, data.bucket_info(1).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(2).atom_size());
-// EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs + 1,
-// data.bucket_info(2).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(3).atom_size());
-// EXPECT_EQ(1, data.bucket_info(3).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs + 1,
-// data.bucket_info(3).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(3).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(3).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(3).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(3).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(4).atom_size());
-// EXPECT_EQ(1, data.bucket_info(4).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs + 1,
-// data.bucket_info(4).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(4).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(4).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(4).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(4).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(5).atom_size());
-// EXPECT_EQ(1, data.bucket_info(5).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs + 2,
-// data.bucket_info(5).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(5).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(5).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(5).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(5).atom(0).subsystem_sleep_state().time_millis(), 0);
-//}
-//
-//TEST(GaugeMetricE2eTest, TestConditionChangeToTrueSamplePulledEvents) {
-// auto config = CreateStatsdConfig(GaugeMetric::CONDITION_CHANGE_TO_TRUE);
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// ATOM_TAG);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-//
-// auto screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 55);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// auto screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + bucketSizeNs + 10);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + bucketSizeNs + 100);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 3 * bucketSizeNs + 2);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 5 * bucketSizeNs + 1);
-// processor->OnLogEvent(screenOffEvent.get());
-// screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 5 * bucketSizeNs + 3);
-// processor->OnLogEvent(screenOnEvent.get());
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 5 * bucketSizeNs + 10);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 8 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
-// EXPECT_GT((int)gaugeMetrics.data_size(), 1);
-//
-// auto data = gaugeMetrics.data(0);
-// EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// EXPECT_EQ(3, data.bucket_info_size());
-//
-// EXPECT_EQ(1, data.bucket_info(0).atom_size());
-// EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(1).atom_size());
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 100,
-// data.bucket_info(1).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(2, data.bucket_info(2).atom_size());
-// EXPECT_EQ(2, data.bucket_info(2).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs + 1,
-// data.bucket_info(2).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs + 10,
-// data.bucket_info(2).elapsed_timestamp_nanos(1));
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
-// EXPECT_TRUE(data.bucket_info(2).atom(1).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(2).atom(1).subsystem_sleep_state().time_millis(), 0);
-//}
-//
-//
-//TEST(GaugeMetricE2eTest, TestRandomSamplePulledEvent_LateAlarm) {
-// auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE);
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// ATOM_TAG);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-//
-// // When creating the config, the gauge metric producer should register the alarm at the
-// // end of the current bucket.
-// EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
-// EXPECT_EQ(bucketSizeNs,
-// processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
-// int64_t& nextPullTimeNs =
-// processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, nextPullTimeNs);
-//
-// auto screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 55);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// auto screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + bucketSizeNs + 10);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// // Pulling alarm arrives one bucket size late.
-// processor->informPullAlarmFired(nextPullTimeNs + bucketSizeNs);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs, nextPullTimeNs);
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 3 * bucketSizeNs + 11);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// // Pulling alarm arrives more than one bucket size late.
-// processor->informPullAlarmFired(nextPullTimeNs + bucketSizeNs + 12);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, nextPullTimeNs);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
-// EXPECT_GT((int)gaugeMetrics.data_size(), 1);
-//
-// auto data = gaugeMetrics.data(0);
-// EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// EXPECT_EQ(3, data.bucket_info_size());
-//
-// EXPECT_EQ(1, data.bucket_info(0).atom_size());
-// EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(1).atom_size());
-// EXPECT_EQ(configAddedTimeNs + 3 * bucketSizeNs + 11,
-// data.bucket_info(1).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// EXPECT_EQ(1, data.bucket_info(2).atom_size());
-// EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs + 12,
-// data.bucket_info(2).elapsed_timestamp_nanos(0));
-// EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
-//}
-//
-//TEST(GaugeMetricE2eTest, TestRandomSamplePulledEventsWithActivation) {
-// auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE, /*useCondition=*/false);
-//
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
-//
-// auto batterySaverStartMatcher = CreateBatterySaverModeStartAtomMatcher();
-// *config.add_atom_matcher() = batterySaverStartMatcher;
-// const int64_t ttlNs = 2 * bucketSizeNs; // Two buckets.
-// auto metric_activation = config.add_metric_activation();
-// metric_activation->set_metric_id(metricId);
-// metric_activation->set_activation_type(ACTIVATE_IMMEDIATELY);
-// auto event_activation = metric_activation->add_event_activation();
-// event_activation->set_atom_matcher_id(batterySaverStartMatcher.id());
-// event_activation->set_ttl_seconds(ttlNs / 1000000000);
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// ATOM_TAG);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-// EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// // When creating the config, the gauge metric producer should register the alarm at the
-// // end of the current bucket.
-// EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
-// EXPECT_EQ(bucketSizeNs,
-// processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
-// int64_t& nextPullTimeNs =
-// processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, nextPullTimeNs);
-//
-// // Pulling alarm arrives on time and reset the sequential pulling alarm.
-// // Event should not be kept.
-// processor->informPullAlarmFired(nextPullTimeNs + 1); // 15 mins + 1 ns.
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, nextPullTimeNs);
-// EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// // Activate the metric. A pull occurs upon activation.
-// const int64_t activationNs = configAddedTimeNs + bucketSizeNs + (2 * 1000 * 1000); // 2 millis.
-// auto batterySaverOnEvent = CreateBatterySaverOnEvent(activationNs);
-// processor->OnLogEvent(batterySaverOnEvent.get()); // 15 mins + 2 ms.
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// // This event should be kept. 2 total.
-// processor->informPullAlarmFired(nextPullTimeNs + 1); // 20 mins + 1 ns.
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs,
-// nextPullTimeNs);
-//
-// // This event should be kept. 3 total.
-// processor->informPullAlarmFired(nextPullTimeNs + 2); // 25 mins + 2 ns.
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, nextPullTimeNs);
-//
-// // Create random event to deactivate metric.
-// auto deactivationEvent = CreateScreenBrightnessChangedEvent(50, activationNs + ttlNs + 1);
-// processor->OnLogEvent(deactivationEvent.get());
-// EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// // Event should not be kept. 3 total.
-// processor->informPullAlarmFired(nextPullTimeNs + 3);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, nextPullTimeNs);
-//
-// processor->informPullAlarmFired(nextPullTimeNs + 2);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
-// EXPECT_GT((int)gaugeMetrics.data_size(), 0);
-//
-// auto data = gaugeMetrics.data(0);
-// EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// EXPECT_EQ(3, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(1, bucketInfo.atom_size());
-// EXPECT_EQ(1, bucketInfo.elapsed_timestamp_nanos_size());
-// EXPECT_EQ(activationNs, bucketInfo.elapsed_timestamp_nanos(0));
-// EXPECT_EQ(0, bucketInfo.wall_clock_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_TRUE(bucketInfo.atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(bucketInfo.atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// bucketInfo = data.bucket_info(1);
-// EXPECT_EQ(1, bucketInfo.atom_size());
-// EXPECT_EQ(1, bucketInfo.elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs + 1, bucketInfo.elapsed_timestamp_nanos(0));
-// EXPECT_EQ(0, bucketInfo.wall_clock_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_TRUE(bucketInfo.atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(bucketInfo.atom(0).subsystem_sleep_state().time_millis(), 0);
-//
-// bucketInfo = data.bucket_info(2);
-// EXPECT_EQ(1, bucketInfo.atom_size());
-// EXPECT_EQ(1, bucketInfo.elapsed_timestamp_nanos_size());
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs + 2, bucketInfo.elapsed_timestamp_nanos(0));
-// EXPECT_EQ(0, bucketInfo.wall_clock_timestamp_nanos_size());
-// EXPECT_EQ(MillisToNano(NanoToMillis(baseTimeNs + 5 * bucketSizeNs)),
-// bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(MillisToNano(NanoToMillis(activationNs + ttlNs + 1)),
-// bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_TRUE(bucketInfo.atom(0).subsystem_sleep_state().subsystem_name().empty());
-// EXPECT_GT(bucketInfo.atom(0).subsystem_sleep_state().time_millis(), 0);
-//}
+TEST(GaugeMetricE2eTest, TestRandomSamplePulledEvents) {
+ auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE);
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor =
+ CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(), ATOM_TAG);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+
+ // When creating the config, the gauge metric producer should register the alarm at the
+ // end of the current bucket.
+ EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
+ EXPECT_EQ(bucketSizeNs,
+ processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
+ int64_t& nextPullTimeNs =
+ processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, nextPullTimeNs);
+
+ auto screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 55, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ // Pulling alarm arrives on time and reset the sequential pulling alarm.
+ processor->informPullAlarmFired(nextPullTimeNs + 1);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, nextPullTimeNs);
+
+ auto screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + bucketSizeNs + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + bucketSizeNs + 100,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ processor->informPullAlarmFired(nextPullTimeNs + 1);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs, nextPullTimeNs);
+
+ processor->informPullAlarmFired(nextPullTimeNs + 1);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, nextPullTimeNs);
+
+ screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 3 * bucketSizeNs + 2,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ processor->informPullAlarmFired(nextPullTimeNs + 3);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, nextPullTimeNs);
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 5 * bucketSizeNs + 1,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ processor->informPullAlarmFired(nextPullTimeNs + 2);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 6 * bucketSizeNs, nextPullTimeNs);
+
+ processor->informPullAlarmFired(nextPullTimeNs + 2);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
+ EXPECT_GT((int)gaugeMetrics.data_size(), 1);
+
+ auto data = gaugeMetrics.data(0);
+ EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ EXPECT_EQ(6, data.bucket_info_size());
+
+ EXPECT_EQ(1, data.bucket_info(0).atom_size());
+ EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(1).atom_size());
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 1, data.bucket_info(1).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 1, data.bucket_info(1).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(2).atom_size());
+ EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs + 1, data.bucket_info(2).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(3).atom_size());
+ EXPECT_EQ(1, data.bucket_info(3).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs + 1, data.bucket_info(3).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(3).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(3).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(3).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(3).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(4).atom_size());
+ EXPECT_EQ(1, data.bucket_info(4).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs + 1, data.bucket_info(4).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(4).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(4).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(4).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(4).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(5).atom_size());
+ EXPECT_EQ(1, data.bucket_info(5).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs + 2, data.bucket_info(5).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(5).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(5).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(5).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(5).atom(0).subsystem_sleep_state().time_millis(), 0);
+}
+
+TEST(GaugeMetricE2eTest, TestConditionChangeToTrueSamplePulledEvents) {
+ auto config = CreateStatsdConfig(GaugeMetric::CONDITION_CHANGE_TO_TRUE);
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor =
+ CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(), ATOM_TAG);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+
+ auto screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 55, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ auto screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + bucketSizeNs + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + bucketSizeNs + 100,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 3 * bucketSizeNs + 2,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 5 * bucketSizeNs + 1,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+ screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 5 * bucketSizeNs + 3,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 5 * bucketSizeNs + 10,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 8 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
+ EXPECT_GT((int)gaugeMetrics.data_size(), 1);
+
+ auto data = gaugeMetrics.data(0);
+ EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ EXPECT_EQ(3, data.bucket_info_size());
+
+ EXPECT_EQ(1, data.bucket_info(0).atom_size());
+ EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(1).atom_size());
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs + 100, data.bucket_info(1).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(2, data.bucket_info(2).atom_size());
+ EXPECT_EQ(2, data.bucket_info(2).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs + 1, data.bucket_info(2).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs + 10, data.bucket_info(2).elapsed_timestamp_nanos(1));
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
+ EXPECT_TRUE(data.bucket_info(2).atom(1).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(2).atom(1).subsystem_sleep_state().time_millis(), 0);
+}
+
+TEST(GaugeMetricE2eTest, TestRandomSamplePulledEvent_LateAlarm) {
+ auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE);
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor =
+ CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(), ATOM_TAG);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+
+ // When creating the config, the gauge metric producer should register the alarm at the
+ // end of the current bucket.
+ EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
+ EXPECT_EQ(bucketSizeNs,
+ processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
+ int64_t& nextPullTimeNs =
+ processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, nextPullTimeNs);
+
+ auto screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 55, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ auto screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + bucketSizeNs + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ // Pulling alarm arrives one bucket size late.
+ processor->informPullAlarmFired(nextPullTimeNs + bucketSizeNs);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs, nextPullTimeNs);
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 3 * bucketSizeNs + 11,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ // Pulling alarm arrives more than one bucket size late.
+ processor->informPullAlarmFired(nextPullTimeNs + bucketSizeNs + 12);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, nextPullTimeNs);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
+ EXPECT_GT((int)gaugeMetrics.data_size(), 1);
+
+ auto data = gaugeMetrics.data(0);
+ EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ EXPECT_EQ(3, data.bucket_info_size());
+
+ EXPECT_EQ(1, data.bucket_info(0).atom_size());
+ EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(0).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(0).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(1).atom_size());
+ EXPECT_EQ(configAddedTimeNs + 3 * bucketSizeNs + 11,
+ data.bucket_info(1).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(configAddedTimeNs + 55, data.bucket_info(0).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(1).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(1).atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ EXPECT_EQ(1, data.bucket_info(2).atom_size());
+ EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs + 12, data.bucket_info(2).elapsed_timestamp_nanos(0));
+ EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_TRUE(data.bucket_info(2).atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(data.bucket_info(2).atom(0).subsystem_sleep_state().time_millis(), 0);
+}
+
+TEST(GaugeMetricE2eTest, TestRandomSamplePulledEventsWithActivation) {
+ auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE, /*useCondition=*/false);
+
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
+
+ auto batterySaverStartMatcher = CreateBatterySaverModeStartAtomMatcher();
+ *config.add_atom_matcher() = batterySaverStartMatcher;
+ const int64_t ttlNs = 2 * bucketSizeNs; // Two buckets.
+ auto metric_activation = config.add_metric_activation();
+ metric_activation->set_metric_id(metricId);
+ metric_activation->set_activation_type(ACTIVATE_IMMEDIATELY);
+ auto event_activation = metric_activation->add_event_activation();
+ event_activation->set_atom_matcher_id(batterySaverStartMatcher.id());
+ event_activation->set_ttl_seconds(ttlNs / 1000000000);
+
+ ConfigKey cfgKey;
+ auto processor =
+ CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(), ATOM_TAG);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+ EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ // When creating the config, the gauge metric producer should register the alarm at the
+ // end of the current bucket.
+ EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
+ EXPECT_EQ(bucketSizeNs,
+ processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
+ int64_t& nextPullTimeNs =
+ processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, nextPullTimeNs);
+
+ // Pulling alarm arrives on time and reset the sequential pulling alarm.
+ // Event should not be kept.
+ processor->informPullAlarmFired(nextPullTimeNs + 1); // 15 mins + 1 ns.
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, nextPullTimeNs);
+ EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ // Activate the metric. A pull occurs upon activation.
+ const int64_t activationNs = configAddedTimeNs + bucketSizeNs + (2 * 1000 * 1000); // 2 millis.
+ auto batterySaverOnEvent = CreateBatterySaverOnEvent(activationNs);
+ processor->OnLogEvent(batterySaverOnEvent.get()); // 15 mins + 2 ms.
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ // This event should be kept. 2 total.
+ processor->informPullAlarmFired(nextPullTimeNs + 1); // 20 mins + 1 ns.
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs, nextPullTimeNs);
+
+ // This event should be kept. 3 total.
+ processor->informPullAlarmFired(nextPullTimeNs + 2); // 25 mins + 2 ns.
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, nextPullTimeNs);
+
+ // Create random event to deactivate metric.
+ auto deactivationEvent = CreateScreenBrightnessChangedEvent(activationNs + ttlNs + 1, 50);
+ processor->OnLogEvent(deactivationEvent.get());
+ EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ // Event should not be kept. 3 total.
+ processor->informPullAlarmFired(nextPullTimeNs + 3);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, nextPullTimeNs);
+
+ processor->informPullAlarmFired(nextPullTimeNs + 2);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
+ EXPECT_GT((int)gaugeMetrics.data_size(), 0);
+
+ auto data = gaugeMetrics.data(0);
+ EXPECT_EQ(ATOM_TAG, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ EXPECT_EQ(3, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(1, bucketInfo.atom_size());
+ EXPECT_EQ(1, bucketInfo.elapsed_timestamp_nanos_size());
+ EXPECT_EQ(activationNs, bucketInfo.elapsed_timestamp_nanos(0));
+ EXPECT_EQ(0, bucketInfo.wall_clock_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_TRUE(bucketInfo.atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(bucketInfo.atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ bucketInfo = data.bucket_info(1);
+ EXPECT_EQ(1, bucketInfo.atom_size());
+ EXPECT_EQ(1, bucketInfo.elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs + 1, bucketInfo.elapsed_timestamp_nanos(0));
+ EXPECT_EQ(0, bucketInfo.wall_clock_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_TRUE(bucketInfo.atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(bucketInfo.atom(0).subsystem_sleep_state().time_millis(), 0);
+
+ bucketInfo = data.bucket_info(2);
+ EXPECT_EQ(1, bucketInfo.atom_size());
+ EXPECT_EQ(1, bucketInfo.elapsed_timestamp_nanos_size());
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs + 2, bucketInfo.elapsed_timestamp_nanos(0));
+ EXPECT_EQ(0, bucketInfo.wall_clock_timestamp_nanos_size());
+ EXPECT_EQ(MillisToNano(NanoToMillis(baseTimeNs + 5 * bucketSizeNs)),
+ bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(MillisToNano(NanoToMillis(activationNs + ttlNs + 1)),
+ bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_TRUE(bucketInfo.atom(0).subsystem_sleep_state().subsystem_name().empty());
+ EXPECT_GT(bucketInfo.atom(0).subsystem_sleep_state().time_millis(), 0);
+}
TEST(GaugeMetricE2eTest, TestRandomSamplePulledEventsNoCondition) {
auto config = CreateStatsdConfig(GaugeMetric::RANDOM_ONE_SAMPLE, /*useCondition=*/false);
diff --git a/cmds/statsd/tests/e2e/GaugeMetric_e2e_push_test.cpp b/cmds/statsd/tests/e2e/GaugeMetric_e2e_push_test.cpp
index ef6e753..6e3d93a 100644
--- a/cmds/statsd/tests/e2e/GaugeMetric_e2e_push_test.cpp
+++ b/cmds/statsd/tests/e2e/GaugeMetric_e2e_push_test.cpp
@@ -14,12 +14,13 @@
#include <gtest/gtest.h>
+#include <vector>
+
#include "src/StatsLogProcessor.h"
#include "src/stats_log_util.h"
+#include "stats_event.h"
#include "tests/statsd_test_util.h"
-#include <vector>
-
namespace android {
namespace os {
namespace statsd {
@@ -68,221 +69,227 @@
return config;
}
-// TODO(b/149590301): Update this helper to use new socket schema.
-//std::unique_ptr<LogEvent> CreateAppStartOccurredEvent(
-// const int uid, const string& pkg_name, AppStartOccurred::TransitionType type,
-// const string& activity_name, const string& calling_pkg_name, const bool is_instant_app,
-// int64_t activity_start_msec, uint64_t timestampNs) {
-// auto logEvent = std::make_unique<LogEvent>(
-// android::util::APP_START_OCCURRED, timestampNs);
-// logEvent->write(uid);
-// logEvent->write(pkg_name);
-// logEvent->write(type);
-// logEvent->write(activity_name);
-// logEvent->write(calling_pkg_name);
-// logEvent->write(is_instant_app);
-// logEvent->write(activity_start_msec);
-// logEvent->init();
-// return logEvent;
-//}
+std::unique_ptr<LogEvent> CreateAppStartOccurredEvent(
+ uint64_t timestampNs, const int uid, const string& pkg_name,
+ AppStartOccurred::TransitionType type, const string& activity_name,
+ const string& calling_pkg_name, const bool is_instant_app, int64_t activity_start_msec) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::APP_START_OCCURRED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, uid);
+ AStatsEvent_writeString(statsEvent, pkg_name.c_str());
+ AStatsEvent_writeInt32(statsEvent, type);
+ AStatsEvent_writeString(statsEvent, activity_name.c_str());
+ AStatsEvent_writeString(statsEvent, calling_pkg_name.c_str());
+ AStatsEvent_writeInt32(statsEvent, is_instant_app);
+ AStatsEvent_writeInt32(statsEvent, activity_start_msec);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
} // namespace
-// TODO(b/149590301): Update this test to use new socket schema.
-//TEST(GaugeMetricE2eTest, TestMultipleFieldsForPushedEvent) {
-// for (const auto& sampling_type :
-// { GaugeMetric::FIRST_N_SAMPLES, GaugeMetric:: RANDOM_ONE_SAMPLE }) {
-// auto config = CreateStatsdConfigForPushedEvent(sampling_type);
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(
-// bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-//
-// int appUid1 = 123;
-// int appUid2 = 456;
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(CreateMoveToBackgroundEvent(appUid1, bucketStartTimeNs + 15));
-// events.push_back(CreateMoveToForegroundEvent(
-// appUid1, bucketStartTimeNs + bucketSizeNs + 250));
-// events.push_back(CreateMoveToBackgroundEvent(
-// appUid1, bucketStartTimeNs + bucketSizeNs + 350));
-// events.push_back(CreateMoveToForegroundEvent(
-// appUid1, bucketStartTimeNs + 2 * bucketSizeNs + 100));
-//
-//
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid1, "app1", AppStartOccurred::WARM, "activity_name1", "calling_pkg_name1",
-// true /*is_instant_app*/, 101 /*activity_start_msec*/, bucketStartTimeNs + 10));
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid1, "app1", AppStartOccurred::HOT, "activity_name2", "calling_pkg_name2",
-// true /*is_instant_app*/, 102 /*activity_start_msec*/, bucketStartTimeNs + 20));
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid1, "app1", AppStartOccurred::COLD, "activity_name3", "calling_pkg_name3",
-// true /*is_instant_app*/, 103 /*activity_start_msec*/, bucketStartTimeNs + 30));
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid1, "app1", AppStartOccurred::WARM, "activity_name4", "calling_pkg_name4",
-// true /*is_instant_app*/, 104 /*activity_start_msec*/,
-// bucketStartTimeNs + bucketSizeNs + 30));
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid1, "app1", AppStartOccurred::COLD, "activity_name5", "calling_pkg_name5",
-// true /*is_instant_app*/, 105 /*activity_start_msec*/,
-// bucketStartTimeNs + 2 * bucketSizeNs));
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid1, "app1", AppStartOccurred::HOT, "activity_name6", "calling_pkg_name6",
-// false /*is_instant_app*/, 106 /*activity_start_msec*/,
-// bucketStartTimeNs + 2 * bucketSizeNs + 10));
-//
-// events.push_back(CreateMoveToBackgroundEvent(
-// appUid2, bucketStartTimeNs + bucketSizeNs + 10));
-// events.push_back(CreateAppStartOccurredEvent(
-// appUid2, "app2", AppStartOccurred::COLD, "activity_name7", "calling_pkg_name7",
-// true /*is_instant_app*/, 201 /*activity_start_msec*/,
-// bucketStartTimeNs + 2 * bucketSizeNs + 10));
-//
-// sortLogEventsByTimestamp(&events);
-//
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 3 * bucketSizeNs, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).gauge_metrics(), &gaugeMetrics);
-// EXPECT_EQ(2, gaugeMetrics.data_size());
-//
-// auto data = gaugeMetrics.data(0);
-// EXPECT_EQ(android::util::APP_START_OCCURRED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(appUid1, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(3, data.bucket_info_size());
-// if (sampling_type == GaugeMetric::FIRST_N_SAMPLES) {
-// EXPECT_EQ(2, data.bucket_info(0).atom_size());
-// EXPECT_EQ(2, data.bucket_info(0).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::HOT,
-// data.bucket_info(0).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name2",
-// data.bucket_info(0).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(102L,
-// data.bucket_info(0).atom(0).app_start_occurred().activity_start_millis());
-// EXPECT_EQ(AppStartOccurred::COLD,
-// data.bucket_info(0).atom(1).app_start_occurred().type());
-// EXPECT_EQ("activity_name3",
-// data.bucket_info(0).atom(1).app_start_occurred().activity_name());
-// EXPECT_EQ(103L,
-// data.bucket_info(0).atom(1).app_start_occurred().activity_start_millis());
-//
-// EXPECT_EQ(1, data.bucket_info(1).atom_size());
-// EXPECT_EQ(1, data.bucket_info(1).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::WARM,
-// data.bucket_info(1).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name4",
-// data.bucket_info(1).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(104L,
-// data.bucket_info(1).atom(0).app_start_occurred().activity_start_millis());
-//
-// EXPECT_EQ(2, data.bucket_info(2).atom_size());
-// EXPECT_EQ(2, data.bucket_info(2).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::COLD,
-// data.bucket_info(2).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name5",
-// data.bucket_info(2).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(105L,
-// data.bucket_info(2).atom(0).app_start_occurred().activity_start_millis());
-// EXPECT_EQ(AppStartOccurred::HOT,
-// data.bucket_info(2).atom(1).app_start_occurred().type());
-// EXPECT_EQ("activity_name6",
-// data.bucket_info(2).atom(1).app_start_occurred().activity_name());
-// EXPECT_EQ(106L,
-// data.bucket_info(2).atom(1).app_start_occurred().activity_start_millis());
-// } else {
-// EXPECT_EQ(1, data.bucket_info(0).atom_size());
-// EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::HOT,
-// data.bucket_info(0).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name2",
-// data.bucket_info(0).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(102L,
-// data.bucket_info(0).atom(0).app_start_occurred().activity_start_millis());
-//
-// EXPECT_EQ(1, data.bucket_info(1).atom_size());
-// EXPECT_EQ(1, data.bucket_info(1).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::WARM,
-// data.bucket_info(1).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name4",
-// data.bucket_info(1).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(104L,
-// data.bucket_info(1).atom(0).app_start_occurred().activity_start_millis());
-//
-// EXPECT_EQ(1, data.bucket_info(2).atom_size());
-// EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::COLD,
-// data.bucket_info(2).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name5",
-// data.bucket_info(2).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(105L,
-// data.bucket_info(2).atom(0).app_start_occurred().activity_start_millis());
-// }
-//
-// data = gaugeMetrics.data(1);
-//
-// EXPECT_EQ(data.dimensions_in_what().field(), android::util::APP_START_OCCURRED);
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(appUid2, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).atom_size());
-// EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_EQ(AppStartOccurred::COLD, data.bucket_info(0).atom(0).app_start_occurred().type());
-// EXPECT_EQ("activity_name7",
-// data.bucket_info(0).atom(0).app_start_occurred().activity_name());
-// EXPECT_EQ(201L, data.bucket_info(0).atom(0).app_start_occurred().activity_start_millis());
-// }
-//}
+TEST(GaugeMetricE2eTest, TestMultipleFieldsForPushedEvent) {
+ for (const auto& sampling_type :
+ {GaugeMetric::FIRST_N_SAMPLES, GaugeMetric::RANDOM_ONE_SAMPLE}) {
+ auto config = CreateStatsdConfigForPushedEvent(sampling_type);
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.gauge_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor =
+ CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ int appUid1 = 123;
+ int appUid2 = 456;
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(CreateMoveToBackgroundEvent(bucketStartTimeNs + 15, appUid1));
+ events.push_back(
+ CreateMoveToForegroundEvent(bucketStartTimeNs + bucketSizeNs + 250, appUid1));
+ events.push_back(
+ CreateMoveToBackgroundEvent(bucketStartTimeNs + bucketSizeNs + 350, appUid1));
+ events.push_back(
+ CreateMoveToForegroundEvent(bucketStartTimeNs + 2 * bucketSizeNs + 100, appUid1));
+
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + 10, appUid1, "app1", AppStartOccurred::WARM, "activity_name1",
+ "calling_pkg_name1", true /*is_instant_app*/, 101 /*activity_start_msec*/));
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + 20, appUid1, "app1", AppStartOccurred::HOT, "activity_name2",
+ "calling_pkg_name2", true /*is_instant_app*/, 102 /*activity_start_msec*/));
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + 30, appUid1, "app1", AppStartOccurred::COLD, "activity_name3",
+ "calling_pkg_name3", true /*is_instant_app*/, 103 /*activity_start_msec*/));
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + bucketSizeNs + 30, appUid1, "app1", AppStartOccurred::WARM,
+ "activity_name4", "calling_pkg_name4", true /*is_instant_app*/,
+ 104 /*activity_start_msec*/));
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + 2 * bucketSizeNs, appUid1, "app1", AppStartOccurred::COLD,
+ "activity_name5", "calling_pkg_name5", true /*is_instant_app*/,
+ 105 /*activity_start_msec*/));
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + 2 * bucketSizeNs + 10, appUid1, "app1", AppStartOccurred::HOT,
+ "activity_name6", "calling_pkg_name6", false /*is_instant_app*/,
+ 106 /*activity_start_msec*/));
+
+ events.push_back(
+ CreateMoveToBackgroundEvent(bucketStartTimeNs + bucketSizeNs + 10, appUid2));
+ events.push_back(CreateAppStartOccurredEvent(
+ bucketStartTimeNs + 2 * bucketSizeNs + 10, appUid2, "app2", AppStartOccurred::COLD,
+ "activity_name7", "calling_pkg_name7", true /*is_instant_app*/,
+ 201 /*activity_start_msec*/));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 3 * bucketSizeNs, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::GaugeMetricDataWrapper gaugeMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).gauge_metrics(),
+ &gaugeMetrics);
+ EXPECT_EQ(2, gaugeMetrics.data_size());
+
+ auto data = gaugeMetrics.data(0);
+ EXPECT_EQ(android::util::APP_START_OCCURRED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(appUid1, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(3, data.bucket_info_size());
+ if (sampling_type == GaugeMetric::FIRST_N_SAMPLES) {
+ EXPECT_EQ(2, data.bucket_info(0).atom_size());
+ EXPECT_EQ(2, data.bucket_info(0).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(0, data.bucket_info(0).wall_clock_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::HOT,
+ data.bucket_info(0).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name2",
+ data.bucket_info(0).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(102L,
+ data.bucket_info(0).atom(0).app_start_occurred().activity_start_millis());
+ EXPECT_EQ(AppStartOccurred::COLD,
+ data.bucket_info(0).atom(1).app_start_occurred().type());
+ EXPECT_EQ("activity_name3",
+ data.bucket_info(0).atom(1).app_start_occurred().activity_name());
+ EXPECT_EQ(103L,
+ data.bucket_info(0).atom(1).app_start_occurred().activity_start_millis());
+
+ EXPECT_EQ(1, data.bucket_info(1).atom_size());
+ EXPECT_EQ(1, data.bucket_info(1).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
+ data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::WARM,
+ data.bucket_info(1).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name4",
+ data.bucket_info(1).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(104L,
+ data.bucket_info(1).atom(0).app_start_occurred().activity_start_millis());
+
+ EXPECT_EQ(2, data.bucket_info(2).atom_size());
+ EXPECT_EQ(2, data.bucket_info(2).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
+ data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::COLD,
+ data.bucket_info(2).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name5",
+ data.bucket_info(2).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(105L,
+ data.bucket_info(2).atom(0).app_start_occurred().activity_start_millis());
+ EXPECT_EQ(AppStartOccurred::HOT,
+ data.bucket_info(2).atom(1).app_start_occurred().type());
+ EXPECT_EQ("activity_name6",
+ data.bucket_info(2).atom(1).app_start_occurred().activity_name());
+ EXPECT_EQ(106L,
+ data.bucket_info(2).atom(1).app_start_occurred().activity_start_millis());
+ } else {
+ EXPECT_EQ(1, data.bucket_info(0).atom_size());
+ EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::HOT,
+ data.bucket_info(0).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name2",
+ data.bucket_info(0).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(102L,
+ data.bucket_info(0).atom(0).app_start_occurred().activity_start_millis());
+
+ EXPECT_EQ(1, data.bucket_info(1).atom_size());
+ EXPECT_EQ(1, data.bucket_info(1).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
+ data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::WARM,
+ data.bucket_info(1).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name4",
+ data.bucket_info(1).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(104L,
+ data.bucket_info(1).atom(0).app_start_occurred().activity_start_millis());
+
+ EXPECT_EQ(1, data.bucket_info(2).atom_size());
+ EXPECT_EQ(1, data.bucket_info(2).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
+ data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::COLD,
+ data.bucket_info(2).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name5",
+ data.bucket_info(2).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(105L,
+ data.bucket_info(2).atom(0).app_start_occurred().activity_start_millis());
+ }
+
+ data = gaugeMetrics.data(1);
+
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::APP_START_OCCURRED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(appUid2, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).atom_size());
+ EXPECT_EQ(1, data.bucket_info(0).elapsed_timestamp_nanos_size());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_EQ(AppStartOccurred::COLD, data.bucket_info(0).atom(0).app_start_occurred().type());
+ EXPECT_EQ("activity_name7",
+ data.bucket_info(0).atom(0).app_start_occurred().activity_name());
+ EXPECT_EQ(201L, data.bucket_info(0).atom(0).app_start_occurred().activity_start_millis());
+ }
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp b/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp
index f3f7df77..1dd90e2 100644
--- a/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp
@@ -233,1609 +233,1602 @@
} // namespace
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(MetricActivationE2eTest, TestCountMetric) {
-// auto config = CreateStatsdConfig();
-//
-// int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// sp<UidMap> m = new UidMap();
-// sp<StatsPullerManager> pullerManager = new StatsPullerManager();
-// sp<AlarmMonitor> anomalyAlarmMonitor;
-// sp<AlarmMonitor> subscriberAlarmMonitor;
-// vector<int64_t> activeConfigsBroadcast;
-//
-// long timeBase1 = 1;
-// int broadcastCount = 0;
-// StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
-// bucketStartTimeNs, [](const ConfigKey& key) { return true; },
-// [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
-// const vector<int64_t>& activeConfigs) {
-// broadcastCount++;
-// EXPECT_EQ(broadcastUid, uid);
-// activeConfigsBroadcast.clear();
-// activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
-// activeConfigs.begin(), activeConfigs.end());
-// return true;
-// });
-//
-// processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
-//
-// EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-//
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
-// // triggered by screen on event (tracker index 2).
-// EXPECT_EQ(eventActivationMap.size(), 2u);
-// EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 0);
-//
-// // Activated by battery save mode.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-//
-// // First processed event.
-// event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
-//
-// // Activated by screen on event.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 20);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-//
-// // 2nd processed event.
-// // The activation by screen_on event expires, but the one by battery save mode is still active.
-// event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// // No new broadcast since the config should still be active.
-// EXPECT_EQ(broadcastCount, 1);
-//
-// // 3rd processed event.
-// event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-//
-// // All activations expired.
-// event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 2);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-//
-// // Re-activate metric via screen on.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-//
-// // 4th processed event.
-// event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(4, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(4, countMetrics.data_size());
-//
-// auto data = countMetrics.data(0);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(2);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// // Partial bucket as metric is deactivated.
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(3);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
-//
-//TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation) {
-// auto config = CreateStatsdConfigWithOneDeactivation();
-//
-// int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// sp<UidMap> m = new UidMap();
-// sp<StatsPullerManager> pullerManager = new StatsPullerManager();
-// sp<AlarmMonitor> anomalyAlarmMonitor;
-// sp<AlarmMonitor> subscriberAlarmMonitor;
-// vector<int64_t> activeConfigsBroadcast;
-//
-// long timeBase1 = 1;
-// int broadcastCount = 0;
-// StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
-// bucketStartTimeNs, [](const ConfigKey& key) { return true; },
-// [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
-// const vector<int64_t>& activeConfigs) {
-// broadcastCount++;
-// EXPECT_EQ(broadcastUid, uid);
-// activeConfigsBroadcast.clear();
-// activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
-// activeConfigs.begin(), activeConfigs.end());
-// return true;
-// });
-//
-// processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
-//
-// EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
-//
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
-// // triggered by screen on event (tracker index 2).
-// EXPECT_EQ(eventActivationMap.size(), 2u);
-// EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap.size(), 1u);
-// EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
-// EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 0);
-//
-// // Activated by battery save mode.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // First processed event.
-// event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
-//
-// // Activated by screen on event.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 20);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // 2nd processed event.
-// // The activation by screen_on event expires, but the one by battery save mode is still active.
-// event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// processor.OnLogEvent(event.get(),bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// // No new broadcast since the config should still be active.
-// EXPECT_EQ(broadcastCount, 1);
-//
-// // 3rd processed event.
-// event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-//
-// // All activations expired.
-// event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 2);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // Re-activate metric via screen on.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // 4th processed event.
-// event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // 5th processed event.
-// event = CreateAppCrashEvent(777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-//
-// // Cancel battery saver mode activation.
-// event = CreateScreenBrightnessChangedEvent(64, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // Screen-on activation expired.
-// event = CreateAppCrashEvent(888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 4);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// event = CreateAppCrashEvent(999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 5);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// // Cancel battery saver mode activation.
-// event = CreateScreenBrightnessChangedEvent(140, bucketStartTimeNs + NS_PER_SEC * 60 * 16);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 16);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 6);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(5, countMetrics.data_size());
-//
-// auto data = countMetrics.data(0);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(2);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// // Partial bucket as metric is deactivated.
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(3);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 13,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(4);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 13,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
-//
-//TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations) {
-// auto config = CreateStatsdConfigWithTwoDeactivations();
-//
-// int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// sp<UidMap> m = new UidMap();
-// sp<StatsPullerManager> pullerManager = new StatsPullerManager();
-// sp<AlarmMonitor> anomalyAlarmMonitor;
-// sp<AlarmMonitor> subscriberAlarmMonitor;
-// vector<int64_t> activeConfigsBroadcast;
-//
-// long timeBase1 = 1;
-// int broadcastCount = 0;
-// StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
-// bucketStartTimeNs, [](const ConfigKey& key) { return true; },
-// [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
-// const vector<int64_t>& activeConfigs) {
-// broadcastCount++;
-// EXPECT_EQ(broadcastUid, uid);
-// activeConfigsBroadcast.clear();
-// activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
-// activeConfigs.begin(), activeConfigs.end());
-// return true;
-// });
-//
-// processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
-//
-// EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
-//
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
-// // triggered by screen on event (tracker index 2).
-// EXPECT_EQ(eventActivationMap.size(), 2u);
-// EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap.size(), 2u);
-// EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
-// EXPECT_TRUE(eventDeactivationMap.find(4) != eventDeactivationMap.end());
-// EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap[4].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 0);
-//
-// // Activated by battery save mode.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // First processed event.
-// event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
-//
-// // Activated by screen on event.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 20);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // 2nd processed event.
-// // The activation by screen_on event expires, but the one by battery save mode is still active.
-// event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// // No new broadcast since the config should still be active.
-// EXPECT_EQ(broadcastCount, 1);
-//
-// // 3rd processed event.
-// event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-//
-// // All activations expired.
-// event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 2);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // Re-activate metric via screen on.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // 4th processed event.
-// event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // 5th processed event.
-// event = CreateAppCrashEvent(777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-//
-// // Cancel battery saver mode and screen on activation.
-// event = CreateScreenBrightnessChangedEvent(64, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 4);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // Screen-on activation expired.
-// event = CreateAppCrashEvent(888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 4);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// event = CreateAppCrashEvent(999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 5);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// // Cancel battery saver mode and screen on activation.
-// event = CreateScreenBrightnessChangedEvent(140, bucketStartTimeNs + NS_PER_SEC * 60 * 16);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 16);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 6);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(5, countMetrics.data_size());
-//
-// auto data = countMetrics.data(0);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(2);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// // Partial bucket as metric is deactivated.
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(3);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(4);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
-//
-//TEST(MetricActivationE2eTest, TestCountMetricWithSameDeactivation) {
-// auto config = CreateStatsdConfigWithSameDeactivations();
-//
-// int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// sp<UidMap> m = new UidMap();
-// sp<StatsPullerManager> pullerManager = new StatsPullerManager();
-// sp<AlarmMonitor> anomalyAlarmMonitor;
-// sp<AlarmMonitor> subscriberAlarmMonitor;
-// vector<int64_t> activeConfigsBroadcast;
-//
-// long timeBase1 = 1;
-// int broadcastCount = 0;
-// StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
-// bucketStartTimeNs, [](const ConfigKey& key) { return true; },
-// [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
-// const vector<int64_t>& activeConfigs) {
-// broadcastCount++;
-// EXPECT_EQ(broadcastUid, uid);
-// activeConfigsBroadcast.clear();
-// activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
-// activeConfigs.begin(), activeConfigs.end());
-// return true;
-// });
-//
-// processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
-//
-// EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
-//
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
-// // triggered by screen on event (tracker index 2).
-// EXPECT_EQ(eventActivationMap.size(), 2u);
-// EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap.size(), 1u);
-// EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
-// EXPECT_EQ(eventDeactivationMap[3].size(), 2u);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[3][1], eventActivationMap[2]);
-// EXPECT_EQ(broadcastCount, 0);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// // Event that should be ignored.
-// event = CreateAppCrashEvent(111, bucketStartTimeNs + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 1);
-//
-// // Activate metric via screen on for 2 minutes.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 10);
-//
-// // 1st processed event.
-// event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
-//
-// // Enable battery saver mode activation for 5 minutes.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 + 10);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 10);
-//
-// // 2nd processed event.
-// event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 + 40);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 + 40);
-//
-// // Cancel battery saver mode and screen on activation.
-// int64_t firstDeactivation = bucketStartTimeNs + NS_PER_SEC * 61;
-// event = CreateScreenBrightnessChangedEvent(64, firstDeactivation);
-// processor.OnLogEvent(event.get(), firstDeactivation);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 2);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-//
-// // Should be ignored
-// event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 61 + 80);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 61 + 80);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 15);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-//
-// // 3rd processed event.
-// event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 80);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 80);
-//
-// // Cancel battery saver mode activation.
-// int64_t secondDeactivation = bucketStartTimeNs + NS_PER_SEC * 60 * 13;
-// event = CreateScreenBrightnessChangedEvent(140, secondDeactivation);
-// processor.OnLogEvent(event.get(), secondDeactivation);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(broadcastCount, 4);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-//
-// // Should be ignored.
-// event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 13 + 80);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13 + 80);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(3, reports.reports(0).metrics(0).count_metrics().data_size());
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(3, countMetrics.data_size());
-//
-// auto data = countMetrics.data(0);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(firstDeactivation, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(firstDeactivation, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(2);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(555, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// // Partial bucket as metric is deactivated.
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(secondDeactivation, data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
-//
-//TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations) {
-// auto config = CreateStatsdConfigWithTwoMetricsTwoDeactivations();
-//
-// int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
-//
-// int uid = 12345;
-// int64_t cfgId = 98765;
-// ConfigKey cfgKey(uid, cfgId);
-//
-// sp<UidMap> m = new UidMap();
-// sp<StatsPullerManager> pullerManager = new StatsPullerManager();
-// sp<AlarmMonitor> anomalyAlarmMonitor;
-// sp<AlarmMonitor> subscriberAlarmMonitor;
-// vector<int64_t> activeConfigsBroadcast;
-//
-// long timeBase1 = 1;
-// int broadcastCount = 0;
-// StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
-// bucketStartTimeNs, [](const ConfigKey& key) { return true; },
-// [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
-// const vector<int64_t>& activeConfigs) {
-// broadcastCount++;
-// EXPECT_EQ(broadcastUid, uid);
-// activeConfigsBroadcast.clear();
-// activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
-// activeConfigs.begin(), activeConfigs.end());
-// return true;
-// });
-//
-// processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
-//
-// EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
-// sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
-// EXPECT_TRUE(metricsManager->isConfigValid());
-// EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 2);
-// sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
-// auto& eventActivationMap = metricProducer->mEventActivationMap;
-// auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
-// sp<MetricProducer> metricProducer2 = metricsManager->mAllMetricProducers[1];
-// auto& eventActivationMap2 = metricProducer2->mEventActivationMap;
-// auto& eventDeactivationMap2 = metricProducer2->mEventDeactivationMap;
-//
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_FALSE(metricProducer2->mIsActive);
-// // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
-// // triggered by screen on event (tracker index 2).
-// EXPECT_EQ(eventActivationMap.size(), 2u);
-// EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
-// EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap.size(), 2u);
-// EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
-// EXPECT_TRUE(eventDeactivationMap.find(4) != eventDeactivationMap.end());
-// EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap[4].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-//
-// EXPECT_EQ(eventActivationMap2.size(), 2u);
-// EXPECT_TRUE(eventActivationMap2.find(0) != eventActivationMap2.end());
-// EXPECT_TRUE(eventActivationMap2.find(2) != eventActivationMap2.end());
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2.size(), 2u);
-// EXPECT_TRUE(eventDeactivationMap2.find(3) != eventDeactivationMap2.end());
-// EXPECT_TRUE(eventDeactivationMap2.find(4) != eventDeactivationMap2.end());
-// EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap[4].size(), 1u);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// std::unique_ptr<LogEvent> event;
-//
-// event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
-// event = CreateMoveToForegroundEvent(1111, bucketStartTimeNs + 5);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_FALSE(metricProducer2->mIsActive);
-// EXPECT_EQ(broadcastCount, 0);
-//
-// // Activated by battery save mode.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_EQ(broadcastCount, 1);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_TRUE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, 0);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // First processed event.
-// event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
-// event = CreateMoveToForegroundEvent(2222, bucketStartTimeNs + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
-//
-// // Activated by screen on event.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 20);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_TRUE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // 2nd processed event.
-// // The activation by screen_on event expires, but the one by battery save mode is still active.
-// event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// event = CreateMoveToForegroundEvent(3333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_TRUE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-// // No new broadcast since the config should still be active.
-// EXPECT_EQ(broadcastCount, 1);
-//
-// // 3rd processed event.
-// event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-// event = CreateMoveToForegroundEvent(4444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
-//
-// // All activations expired.
-// event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// event = CreateMoveToForegroundEvent(5555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
-// EXPECT_FALSE(metricsManager->isActive());
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 2);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_FALSE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + 20);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // Re-activate metric via screen on.
-// event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_TRUE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // 4th processed event.
-// event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-// event = CreateMoveToForegroundEvent(6666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_EQ(broadcastCount, 3);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_TRUE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // 5th processed event.
-// event = CreateAppCrashEvent(777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-// event = CreateMoveToForegroundEvent(7777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
-//
-// // Cancel battery saver mode and screen on activation.
-// event = CreateScreenBrightnessChangedEvent(64, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
-// processor.OnLogEvent(event.get(),bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
-// EXPECT_FALSE(metricsManager->isActive());
-// // New broadcast since the config is no longer active.
-// EXPECT_EQ(broadcastCount, 4);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_FALSE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // Screen-on activation expired.
-// event = CreateAppCrashEvent(888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// event = CreateMoveToForegroundEvent(8888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_EQ(broadcastCount, 4);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_FALSE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// event = CreateAppCrashEvent(999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-// event = CreateMoveToForegroundEvent(9999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
-//
-// // Re-enable battery saver mode activation.
-// event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_TRUE(metricsManager->isActive());
-// EXPECT_EQ(broadcastCount, 5);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 1);
-// EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-// EXPECT_TRUE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_TRUE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// // Cancel battery saver mode and screen on activation.
-// event = CreateScreenBrightnessChangedEvent(140, bucketStartTimeNs + NS_PER_SEC * 60 * 16);
-// processor.OnLogEvent(event.get(),bucketStartTimeNs + NS_PER_SEC * 60 * 16);
-// EXPECT_FALSE(metricsManager->isActive());
-// EXPECT_EQ(broadcastCount, 6);
-// EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-// EXPECT_FALSE(metricProducer->mIsActive);
-// EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
-// EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
-// EXPECT_FALSE(metricProducer2->mIsActive);
-// EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
-// EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
-// EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
-// EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-// EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
-// EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
-// EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(2, reports.reports(0).metrics_size());
-// EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
-// EXPECT_EQ(5, reports.reports(0).metrics(1).count_metrics().data_size());
-//
-// StatsLogReport::CountMetricDataWrapper countMetrics;
-//
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-// EXPECT_EQ(5, countMetrics.data_size());
-//
-// auto data = countMetrics.data(0);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(2);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// // Partial bucket as metric is deactivated.
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(3);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(4);
-// EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-//
-// countMetrics.clear_data();
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(1).count_metrics(), &countMetrics);
-// EXPECT_EQ(5, countMetrics.data_size());
-//
-// data = countMetrics.data(0);
-// EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(2222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(1);
-// EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(3333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(2);
-// EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(4444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// // Partial bucket as metric is deactivated.
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(3);
-// EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(6666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//
-// data = countMetrics.data(4);
-// EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* uid field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_EQ(7777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
-// EXPECT_EQ(1, data.bucket_info_size());
-// EXPECT_EQ(1, data.bucket_info(0).count());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
-// data.bucket_info(0).end_bucket_elapsed_nanos());
-//}
+TEST(MetricActivationE2eTest, TestCountMetric) {
+ auto config = CreateStatsdConfig();
+
+ int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ sp<UidMap> m = new UidMap();
+ sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+ sp<AlarmMonitor> anomalyAlarmMonitor;
+ sp<AlarmMonitor> subscriberAlarmMonitor;
+ vector<int64_t> activeConfigsBroadcast;
+
+ long timeBase1 = 1;
+ int broadcastCount = 0;
+ StatsLogProcessor processor(
+ m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, bucketStartTimeNs,
+ [](const ConfigKey& key) { return true; },
+ [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+ const vector<int64_t>& activeConfigs) {
+ broadcastCount++;
+ EXPECT_EQ(broadcastUid, uid);
+ activeConfigsBroadcast.clear();
+ activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
+ activeConfigs.end());
+ return true;
+ });
+
+ processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+ EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+ // triggered by screen on event (tracker index 2).
+ EXPECT_EQ(eventActivationMap.size(), 2u);
+ EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+
+ std::unique_ptr<LogEvent> event;
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + 5, 111);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 0);
+
+ // Activated by battery save mode.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+
+ // First processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + 15, 222);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
+
+ // Activated by screen on event.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + 20, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+
+ // 2nd processed event.
+ // The activation by screen_on event expires, but the one by battery save mode is still active.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25, 333);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ // No new broadcast since the config should still be active.
+ EXPECT_EQ(broadcastCount, 1);
+
+ // 3rd processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25, 444);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+
+ // All activations expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 8, 555);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 2);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+
+ // Re-activate metric via screen on.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+
+ // 4th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1, 666);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(4, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(4, countMetrics.data_size());
+
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ // Partial bucket as metric is deactivated.
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation) {
+ auto config = CreateStatsdConfigWithOneDeactivation();
+
+ int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ sp<UidMap> m = new UidMap();
+ sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+ sp<AlarmMonitor> anomalyAlarmMonitor;
+ sp<AlarmMonitor> subscriberAlarmMonitor;
+ vector<int64_t> activeConfigsBroadcast;
+
+ long timeBase1 = 1;
+ int broadcastCount = 0;
+ StatsLogProcessor processor(
+ m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, bucketStartTimeNs,
+ [](const ConfigKey& key) { return true; },
+ [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+ const vector<int64_t>& activeConfigs) {
+ broadcastCount++;
+ EXPECT_EQ(broadcastUid, uid);
+ activeConfigsBroadcast.clear();
+ activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
+ activeConfigs.end());
+ return true;
+ });
+
+ processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+ EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+ // triggered by screen on event (tracker index 2).
+ EXPECT_EQ(eventActivationMap.size(), 2u);
+ EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap.size(), 1u);
+ EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+ EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ std::unique_ptr<LogEvent> event;
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + 5, 111);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 0);
+
+ // Activated by battery save mode.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // First processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + 15, 222);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
+
+ // Activated by screen on event.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + 20, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // 2nd processed event.
+ // The activation by screen_on event expires, but the one by battery save mode is still active.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25, 333);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ // No new broadcast since the config should still be active.
+ EXPECT_EQ(broadcastCount, 1);
+
+ // 3rd processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25, 444);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+
+ // All activations expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 8, 555);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 2);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // Re-activate metric via screen on.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // 4th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1, 666);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // 5th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40, 777);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+
+ // Cancel battery saver mode activation.
+ event = CreateScreenBrightnessChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60, 64);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // Screen-on activation expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 13, 888);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 4);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1, 999);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 5);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ // Cancel battery saver mode activation.
+ event = CreateScreenBrightnessChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 16, 140);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 16);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 6);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(5, countMetrics.data_size());
+
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ // Partial bucket as metric is deactivated.
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 13,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(4);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 13,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations) {
+ auto config = CreateStatsdConfigWithTwoDeactivations();
+
+ int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ sp<UidMap> m = new UidMap();
+ sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+ sp<AlarmMonitor> anomalyAlarmMonitor;
+ sp<AlarmMonitor> subscriberAlarmMonitor;
+ vector<int64_t> activeConfigsBroadcast;
+
+ long timeBase1 = 1;
+ int broadcastCount = 0;
+ StatsLogProcessor processor(
+ m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, bucketStartTimeNs,
+ [](const ConfigKey& key) { return true; },
+ [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+ const vector<int64_t>& activeConfigs) {
+ broadcastCount++;
+ EXPECT_EQ(broadcastUid, uid);
+ activeConfigsBroadcast.clear();
+ activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
+ activeConfigs.end());
+ return true;
+ });
+
+ processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+ EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+ // triggered by screen on event (tracker index 2).
+ EXPECT_EQ(eventActivationMap.size(), 2u);
+ EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap.size(), 2u);
+ EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+ EXPECT_TRUE(eventDeactivationMap.find(4) != eventDeactivationMap.end());
+ EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap[4].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ std::unique_ptr<LogEvent> event;
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + 5, 111);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 0);
+
+ // Activated by battery save mode.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // First processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + 15, 222);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
+
+ // Activated by screen on event.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + 20, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // 2nd processed event.
+ // The activation by screen_on event expires, but the one by battery save mode is still active.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25, 333);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ // No new broadcast since the config should still be active.
+ EXPECT_EQ(broadcastCount, 1);
+
+ // 3rd processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25, 444);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+
+ // All activations expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 8, 555);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 2);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // Re-activate metric via screen on.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // 4th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1, 666);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // 5th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40, 777);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+
+ // Cancel battery saver mode and screen on activation.
+ event = CreateScreenBrightnessChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60, 64);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 4);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // Screen-on activation expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 13, 888);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 4);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1, 999);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 5);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ // Cancel battery saver mode and screen on activation.
+ event = CreateScreenBrightnessChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 16, 140);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 16);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 6);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(5, countMetrics.data_size());
+
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ // Partial bucket as metric is deactivated.
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(4);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(MetricActivationE2eTest, TestCountMetricWithSameDeactivation) {
+ auto config = CreateStatsdConfigWithSameDeactivations();
+
+ int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ sp<UidMap> m = new UidMap();
+ sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+ sp<AlarmMonitor> anomalyAlarmMonitor;
+ sp<AlarmMonitor> subscriberAlarmMonitor;
+ vector<int64_t> activeConfigsBroadcast;
+
+ long timeBase1 = 1;
+ int broadcastCount = 0;
+ StatsLogProcessor processor(
+ m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, bucketStartTimeNs,
+ [](const ConfigKey& key) { return true; },
+ [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+ const vector<int64_t>& activeConfigs) {
+ broadcastCount++;
+ EXPECT_EQ(broadcastUid, uid);
+ activeConfigsBroadcast.clear();
+ activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
+ activeConfigs.end());
+ return true;
+ });
+
+ processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+ EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+ // triggered by screen on event (tracker index 2).
+ EXPECT_EQ(eventActivationMap.size(), 2u);
+ EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap.size(), 1u);
+ EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+ EXPECT_EQ(eventDeactivationMap[3].size(), 2u);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[3][1], eventActivationMap[2]);
+ EXPECT_EQ(broadcastCount, 0);
+
+ std::unique_ptr<LogEvent> event;
+
+ // Event that should be ignored.
+ event = CreateAppCrashEvent(bucketStartTimeNs + 1, 111);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 1);
+
+ // Activate metric via screen on for 2 minutes.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + 10, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 10);
+
+ // 1st processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + 15, 222);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
+
+ // Enable battery saver mode activation for 5 minutes.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 + 10);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 + 10);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 10);
+
+ // 2nd processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 + 40, 333);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 + 40);
+
+ // Cancel battery saver mode and screen on activation.
+ int64_t firstDeactivation = bucketStartTimeNs + NS_PER_SEC * 61;
+ event = CreateScreenBrightnessChangedEvent(firstDeactivation, 64);
+ processor.OnLogEvent(event.get(), firstDeactivation);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 2);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+
+ // Should be ignored
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 61 + 80, 444);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 61 + 80);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 15);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+
+ // 3rd processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 80, 555);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 80);
+
+ // Cancel battery saver mode activation.
+ int64_t secondDeactivation = bucketStartTimeNs + NS_PER_SEC * 60 * 13;
+ event = CreateScreenBrightnessChangedEvent(secondDeactivation, 140);
+ processor.OnLogEvent(event.get(), secondDeactivation);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(broadcastCount, 4);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+
+ // Should be ignored.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 13 + 80, 666);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13 + 80);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(3, reports.reports(0).metrics(0).count_metrics().data_size());
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(3, countMetrics.data_size());
+
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(firstDeactivation, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(firstDeactivation, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(555, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ // Partial bucket as metric is deactivated.
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(secondDeactivation, data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations) {
+ auto config = CreateStatsdConfigWithTwoMetricsTwoDeactivations();
+
+ int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+ int uid = 12345;
+ int64_t cfgId = 98765;
+ ConfigKey cfgKey(uid, cfgId);
+
+ sp<UidMap> m = new UidMap();
+ sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+ sp<AlarmMonitor> anomalyAlarmMonitor;
+ sp<AlarmMonitor> subscriberAlarmMonitor;
+ vector<int64_t> activeConfigsBroadcast;
+
+ long timeBase1 = 1;
+ int broadcastCount = 0;
+ StatsLogProcessor processor(
+ m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, bucketStartTimeNs,
+ [](const ConfigKey& key) { return true; },
+ [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+ const vector<int64_t>& activeConfigs) {
+ broadcastCount++;
+ EXPECT_EQ(broadcastUid, uid);
+ activeConfigsBroadcast.clear();
+ activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
+ activeConfigs.end());
+ return true;
+ });
+
+ processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+ EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+ sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+ EXPECT_TRUE(metricsManager->isConfigValid());
+ EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 2);
+ sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+ auto& eventActivationMap = metricProducer->mEventActivationMap;
+ auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+ sp<MetricProducer> metricProducer2 = metricsManager->mAllMetricProducers[1];
+ auto& eventActivationMap2 = metricProducer2->mEventActivationMap;
+ auto& eventDeactivationMap2 = metricProducer2->mEventDeactivationMap;
+
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_FALSE(metricProducer2->mIsActive);
+ // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+ // triggered by screen on event (tracker index 2).
+ EXPECT_EQ(eventActivationMap.size(), 2u);
+ EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+ EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap.size(), 2u);
+ EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+ EXPECT_TRUE(eventDeactivationMap.find(4) != eventDeactivationMap.end());
+ EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap[4].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+
+ EXPECT_EQ(eventActivationMap2.size(), 2u);
+ EXPECT_TRUE(eventActivationMap2.find(0) != eventActivationMap2.end());
+ EXPECT_TRUE(eventActivationMap2.find(2) != eventActivationMap2.end());
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2.size(), 2u);
+ EXPECT_TRUE(eventDeactivationMap2.find(3) != eventDeactivationMap2.end());
+ EXPECT_TRUE(eventDeactivationMap2.find(4) != eventDeactivationMap2.end());
+ EXPECT_EQ(eventDeactivationMap[3].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap[4].size(), 1u);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ std::unique_ptr<LogEvent> event;
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + 5, 111);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + 5, 1111);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 5);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_FALSE(metricProducer2->mIsActive);
+ EXPECT_EQ(broadcastCount, 0);
+
+ // Activated by battery save mode.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_EQ(broadcastCount, 1);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_TRUE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, 0);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // First processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + 15, 222);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + 15, 2222);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 15);
+
+ // Activated by screen on event.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + 20, android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + 20);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_TRUE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // 2nd processed event.
+ // The activation by screen_on event expires, but the one by battery save mode is still active.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25, 333);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25, 3333);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_TRUE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+ // No new broadcast since the config should still be active.
+ EXPECT_EQ(broadcastCount, 1);
+
+ // 3rd processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25, 444);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25, 4444);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+
+ // All activations expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 8, 555);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 8, 5555);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+ EXPECT_FALSE(metricsManager->isActive());
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 2);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_FALSE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + 20);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // Re-activate metric via screen on.
+ event = CreateScreenStateChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10,
+ android::view::DISPLAY_STATE_ON);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_TRUE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + 10);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // 4th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1, 666);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1, 6666);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_EQ(broadcastCount, 3);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_TRUE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // 5th processed event.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40, 777);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40, 7777);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+
+ // Cancel battery saver mode and screen on activation.
+ event = CreateScreenBrightnessChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60, 64);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
+ EXPECT_FALSE(metricsManager->isActive());
+ // New broadcast since the config is no longer active.
+ EXPECT_EQ(broadcastCount, 4);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_FALSE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // Screen-on activation expired.
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 13, 888);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 13, 8888);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_EQ(broadcastCount, 4);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_FALSE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ event = CreateAppCrashEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1, 999);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+ event = CreateMoveToForegroundEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1, 9999);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+
+ // Re-enable battery saver mode activation.
+ event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_TRUE(metricsManager->isActive());
+ EXPECT_EQ(broadcastCount, 5);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+ EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+ EXPECT_TRUE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_TRUE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ // Cancel battery saver mode and screen on activation.
+ event = CreateScreenBrightnessChangedEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 16, 140);
+ processor.OnLogEvent(event.get(), bucketStartTimeNs + NS_PER_SEC * 60 * 16);
+ EXPECT_FALSE(metricsManager->isActive());
+ EXPECT_EQ(broadcastCount, 6);
+ EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+ EXPECT_FALSE(metricProducer->mIsActive);
+ EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap[3][0], eventActivationMap[0]);
+ EXPECT_EQ(eventDeactivationMap[4][0], eventActivationMap[2]);
+ EXPECT_FALSE(metricProducer2->mIsActive);
+ EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[0]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+ EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+ EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+ EXPECT_EQ(eventActivationMap2[2]->start_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+ EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+ EXPECT_EQ(eventDeactivationMap2[3][0], eventActivationMap2[0]);
+ EXPECT_EQ(eventDeactivationMap2[4][0], eventActivationMap2[2]);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(2, reports.reports(0).metrics_size());
+ EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+ EXPECT_EQ(5, reports.reports(0).metrics(1).count_metrics().data_size());
+
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+ EXPECT_EQ(5, countMetrics.data_size());
+
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ // Partial bucket as metric is deactivated.
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(4);
+ EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ countMetrics.clear_data();
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(1).count_metrics(), &countMetrics);
+ EXPECT_EQ(5, countMetrics.data_size());
+
+ data = countMetrics.data(0);
+ EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(2222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(3333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(4444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ // Partial bucket as metric is deactivated.
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(6666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+
+ data = countMetrics.data(4);
+ EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* uid field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_EQ(7777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+ EXPECT_EQ(1, data.bucket_info_size());
+ EXPECT_EQ(1, data.bucket_info(0).count());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+ data.bucket_info(0).end_bucket_elapsed_nanos());
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp b/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp
index 7d93fcc..e8fb523 100644
--- a/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp
@@ -97,250 +97,247 @@
}
} // namespace
-// TODO(b/149590301): Update these tests to use new socket schema.
-//// If we want to test multiple dump data, we must do it in separate tests, because in the e2e tests,
-//// we should use the real API which will clear the data after dump data is called.
-//TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks1) {
-// auto config = CreateStatsdConfig();
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-//
-// int appUid = 123;
-// auto crashEvent1 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 1);
-// auto crashEvent2 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 201);
-// auto crashEvent3= CreateAppCrashEvent(appUid, bucketStartTimeNs + 2 * bucketSizeNs - 101);
-//
-// auto crashEvent4 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 51);
-// auto crashEvent5 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 299);
-// auto crashEvent6 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 2001);
-//
-// auto crashEvent7 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 16);
-// auto crashEvent8 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 249);
-//
-// auto crashEvent9 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 351);
-// auto crashEvent10 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 2 * bucketSizeNs - 2);
-//
-// auto screenTurnedOnEvent =
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 2);
-// auto screenTurnedOffEvent =
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 200);
-// auto screenTurnedOnEvent2 =
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 2 * bucketSizeNs - 100);
-//
-// std::vector<AttributionNodeInternal> attributions = {
-// CreateAttribution(appUid, "App1"), CreateAttribution(appUid + 1, "GMSCoreModule1")};
-// auto syncOnEvent1 =
-// CreateSyncStartEvent(attributions, "ReadEmail", bucketStartTimeNs + 50);
-// auto syncOffEvent1 =
-// CreateSyncEndEvent(attributions, "ReadEmail", bucketStartTimeNs + bucketSizeNs + 300);
-// auto syncOnEvent2 =
-// CreateSyncStartEvent(attributions, "ReadDoc", bucketStartTimeNs + bucketSizeNs + 2000);
-//
-// auto moveToBackgroundEvent1 =
-// CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + 15);
-// auto moveToForegroundEvent1 =
-// CreateMoveToForegroundEvent(appUid, bucketStartTimeNs + bucketSizeNs + 250);
-//
-// auto moveToBackgroundEvent2 =
-// CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + bucketSizeNs + 350);
-// auto moveToForegroundEvent2 =
-// CreateMoveToForegroundEvent(appUid, bucketStartTimeNs + 2 * bucketSizeNs - 1);
-//
-// /*
-// bucket #1 bucket #2
-//
-//
-// | | | | | | | | | | (crashEvents)
-// |-------------------------------------|-----------------------------------|---------
-//
-// | | (MoveToBkground)
-//
-// | | (MoveToForeground)
-//
-// | | (SyncIsOn)
-// | (SyncIsOff)
-// | | (ScreenIsOn)
-// | (ScreenIsOff)
-// */
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(std::move(crashEvent1));
-// events.push_back(std::move(crashEvent2));
-// events.push_back(std::move(crashEvent3));
-// events.push_back(std::move(crashEvent4));
-// events.push_back(std::move(crashEvent5));
-// events.push_back(std::move(crashEvent6));
-// events.push_back(std::move(crashEvent7));
-// events.push_back(std::move(crashEvent8));
-// events.push_back(std::move(crashEvent9));
-// events.push_back(std::move(crashEvent10));
-// events.push_back(std::move(screenTurnedOnEvent));
-// events.push_back(std::move(screenTurnedOffEvent));
-// events.push_back(std::move(screenTurnedOnEvent2));
-// events.push_back(std::move(syncOnEvent1));
-// events.push_back(std::move(syncOffEvent1));
-// events.push_back(std::move(syncOnEvent2));
-// events.push_back(std::move(moveToBackgroundEvent1));
-// events.push_back(std::move(moveToForegroundEvent1));
-// events.push_back(std::move(moveToBackgroundEvent2));
-// events.push_back(std::move(moveToForegroundEvent2));
-//
-// sortLogEventsByTimestamp(&events);
-//
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs - 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info(0).count(), 1);
-// auto data = reports.reports(0).metrics(0).count_metrics().data(0);
-// // Validate dimension value.
-// EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
-// // Uid field.
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), appUid);
-//}
-//
-//TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks2) {
-// auto config = CreateStatsdConfig();
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(
-// bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-//
-// int appUid = 123;
-// auto crashEvent1 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 1);
-// auto crashEvent2 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 201);
-// auto crashEvent3 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 2 * bucketSizeNs - 101);
-//
-// auto crashEvent4 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 51);
-// auto crashEvent5 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 299);
-// auto crashEvent6 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 2001);
-//
-// auto crashEvent7 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 16);
-// auto crashEvent8 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 249);
-//
-// auto crashEvent9 = CreateAppCrashEvent(appUid, bucketStartTimeNs + bucketSizeNs + 351);
-// auto crashEvent10 = CreateAppCrashEvent(appUid, bucketStartTimeNs + 2 * bucketSizeNs - 2);
-//
-// auto screenTurnedOnEvent = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_ON, bucketStartTimeNs + 2);
-// auto screenTurnedOffEvent = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF, bucketStartTimeNs + 200);
-// auto screenTurnedOnEvent2 =
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + 2 * bucketSizeNs - 100);
-//
-// std::vector<AttributionNodeInternal> attributions = {
-// CreateAttribution(appUid, "App1"), CreateAttribution(appUid + 1, "GMSCoreModule1")};
-// auto syncOnEvent1 = CreateSyncStartEvent(attributions, "ReadEmail", bucketStartTimeNs + 50);
-// auto syncOffEvent1 =
-// CreateSyncEndEvent(attributions, "ReadEmail", bucketStartTimeNs + bucketSizeNs + 300);
-// auto syncOnEvent2 =
-// CreateSyncStartEvent(attributions, "ReadDoc", bucketStartTimeNs + bucketSizeNs + 2000);
-//
-// auto moveToBackgroundEvent1 = CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + 15);
-// auto moveToForegroundEvent1 =
-// CreateMoveToForegroundEvent(appUid, bucketStartTimeNs + bucketSizeNs + 250);
-//
-// auto moveToBackgroundEvent2 =
-// CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + bucketSizeNs + 350);
-// auto moveToForegroundEvent2 =
-// CreateMoveToForegroundEvent(appUid, bucketStartTimeNs + 2 * bucketSizeNs - 1);
-//
-// /*
-// bucket #1 bucket #2
-//
-//
-// | | | | | | | | | | (crashEvents)
-// |-------------------------------------|-----------------------------------|---------
-//
-// | | (MoveToBkground)
-//
-// | | (MoveToForeground)
-//
-// | | (SyncIsOn)
-// | (SyncIsOff)
-// | | (ScreenIsOn)
-// | (ScreenIsOff)
-// */
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(std::move(crashEvent1));
-// events.push_back(std::move(crashEvent2));
-// events.push_back(std::move(crashEvent3));
-// events.push_back(std::move(crashEvent4));
-// events.push_back(std::move(crashEvent5));
-// events.push_back(std::move(crashEvent6));
-// events.push_back(std::move(crashEvent7));
-// events.push_back(std::move(crashEvent8));
-// events.push_back(std::move(crashEvent9));
-// events.push_back(std::move(crashEvent10));
-// events.push_back(std::move(screenTurnedOnEvent));
-// events.push_back(std::move(screenTurnedOffEvent));
-// events.push_back(std::move(screenTurnedOnEvent2));
-// events.push_back(std::move(syncOnEvent1));
-// events.push_back(std::move(syncOffEvent1));
-// events.push_back(std::move(syncOnEvent2));
-// events.push_back(std::move(moveToBackgroundEvent1));
-// events.push_back(std::move(moveToForegroundEvent1));
-// events.push_back(std::move(moveToBackgroundEvent2));
-// events.push_back(std::move(moveToForegroundEvent2));
-//
-// sortLogEventsByTimestamp(&events);
-//
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-//
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info_size(), 2);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info(0).count(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info(1).count(), 3);
-// auto data = reports.reports(0).metrics(0).count_metrics().data(0);
-// // Validate dimension value.
-// EXPECT_EQ(data.dimensions_in_what().field(),
-// android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
-// // Uid field.
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
-// EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), appUid);
-//}
+// If we want to test multiple dump data, we must do it in separate tests, because in the e2e tests,
+// we should use the real API which will clear the data after dump data is called.
+TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks1) {
+ auto config = CreateStatsdConfig();
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ int appUid = 123;
+ auto crashEvent1 = CreateAppCrashEvent(bucketStartTimeNs + 1, appUid);
+ auto crashEvent2 = CreateAppCrashEvent(bucketStartTimeNs + 201, appUid);
+ auto crashEvent3 = CreateAppCrashEvent(bucketStartTimeNs + 2 * bucketSizeNs - 101, appUid);
+
+ auto crashEvent4 = CreateAppCrashEvent(bucketStartTimeNs + 51, appUid);
+ auto crashEvent5 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 299, appUid);
+ auto crashEvent6 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 2001, appUid);
+
+ auto crashEvent7 = CreateAppCrashEvent(bucketStartTimeNs + 16, appUid);
+ auto crashEvent8 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 249, appUid);
+
+ auto crashEvent9 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 351, appUid);
+ auto crashEvent10 = CreateAppCrashEvent(bucketStartTimeNs + 2 * bucketSizeNs - 2, appUid);
+
+ auto screenTurnedOnEvent = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 2, android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+ auto screenTurnedOffEvent = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 200, android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ auto screenTurnedOnEvent2 =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs - 100,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+
+ std::vector<int> attributionUids = {appUid, appUid + 1};
+ std::vector<string> attributionTags = {"App1", "GMSCoreModule1"};
+
+ auto syncOnEvent1 = CreateSyncStartEvent(bucketStartTimeNs + 50, attributionUids,
+ attributionTags, "ReadEmail");
+ auto syncOffEvent1 = CreateSyncEndEvent(bucketStartTimeNs + bucketSizeNs + 300, attributionUids,
+ attributionTags, "ReadEmail");
+ auto syncOnEvent2 = CreateSyncStartEvent(bucketStartTimeNs + bucketSizeNs + 2000,
+ attributionUids, attributionTags, "ReadDoc");
+
+ auto moveToBackgroundEvent1 = CreateMoveToBackgroundEvent(bucketStartTimeNs + 15, appUid);
+ auto moveToForegroundEvent1 =
+ CreateMoveToForegroundEvent(bucketStartTimeNs + bucketSizeNs + 250, appUid);
+
+ auto moveToBackgroundEvent2 =
+ CreateMoveToBackgroundEvent(bucketStartTimeNs + bucketSizeNs + 350, appUid);
+ auto moveToForegroundEvent2 =
+ CreateMoveToForegroundEvent(bucketStartTimeNs + 2 * bucketSizeNs - 1, appUid);
+
+ /*
+ bucket #1 bucket #2
+
+
+ | | | | | | | | | | (crashEvents)
+ |-------------------------------------|-----------------------------------|---------
+
+ | | (MoveToBkground)
+
+ | | (MoveToForeground)
+
+ | | (SyncIsOn)
+ | (SyncIsOff)
+ | | (ScreenIsOn)
+ | (ScreenIsOff)
+ */
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(std::move(crashEvent1));
+ events.push_back(std::move(crashEvent2));
+ events.push_back(std::move(crashEvent3));
+ events.push_back(std::move(crashEvent4));
+ events.push_back(std::move(crashEvent5));
+ events.push_back(std::move(crashEvent6));
+ events.push_back(std::move(crashEvent7));
+ events.push_back(std::move(crashEvent8));
+ events.push_back(std::move(crashEvent9));
+ events.push_back(std::move(crashEvent10));
+ events.push_back(std::move(screenTurnedOnEvent));
+ events.push_back(std::move(screenTurnedOffEvent));
+ events.push_back(std::move(screenTurnedOnEvent2));
+ events.push_back(std::move(syncOnEvent1));
+ events.push_back(std::move(syncOffEvent1));
+ events.push_back(std::move(syncOnEvent2));
+ events.push_back(std::move(moveToBackgroundEvent1));
+ events.push_back(std::move(moveToForegroundEvent1));
+ events.push_back(std::move(moveToBackgroundEvent2));
+ events.push_back(std::move(moveToForegroundEvent2));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs - 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info(0).count(), 1);
+ auto data = reports.reports(0).metrics(0).count_metrics().data(0);
+ // Validate dimension value.
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ // Uid field.
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), appUid);
+}
+
+TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks2) {
+ auto config = CreateStatsdConfig();
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ int appUid = 123;
+ auto crashEvent1 = CreateAppCrashEvent(bucketStartTimeNs + 1, appUid);
+ auto crashEvent2 = CreateAppCrashEvent(bucketStartTimeNs + 201, appUid);
+ auto crashEvent3 = CreateAppCrashEvent(bucketStartTimeNs + 2 * bucketSizeNs - 101, appUid);
+
+ auto crashEvent4 = CreateAppCrashEvent(bucketStartTimeNs + 51, appUid);
+ auto crashEvent5 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 299, appUid);
+ auto crashEvent6 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 2001, appUid);
+
+ auto crashEvent7 = CreateAppCrashEvent(bucketStartTimeNs + 16, appUid);
+ auto crashEvent8 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 249, appUid);
+
+ auto crashEvent9 = CreateAppCrashEvent(bucketStartTimeNs + bucketSizeNs + 351, appUid);
+ auto crashEvent10 = CreateAppCrashEvent(bucketStartTimeNs + 2 * bucketSizeNs - 2, appUid);
+
+ auto screenTurnedOnEvent = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 2, android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+ auto screenTurnedOffEvent = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 200, android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ auto screenTurnedOnEvent2 =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs - 100,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+
+ std::vector<int> attributionUids = {appUid, appUid + 1};
+ std::vector<string> attributionTags = {"App1", "GMSCoreModule1"};
+
+ auto syncOnEvent1 = CreateSyncStartEvent(bucketStartTimeNs + 50, attributionUids,
+ attributionTags, "ReadEmail");
+ auto syncOffEvent1 = CreateSyncEndEvent(bucketStartTimeNs + bucketSizeNs + 300, attributionUids,
+ attributionTags, "ReadEmail");
+ auto syncOnEvent2 = CreateSyncStartEvent(bucketStartTimeNs + bucketSizeNs + 2000,
+ attributionUids, attributionTags, "ReadDoc");
+
+ auto moveToBackgroundEvent1 = CreateMoveToBackgroundEvent(bucketStartTimeNs + 15, appUid);
+ auto moveToForegroundEvent1 =
+ CreateMoveToForegroundEvent(bucketStartTimeNs + bucketSizeNs + 250, appUid);
+
+ auto moveToBackgroundEvent2 =
+ CreateMoveToBackgroundEvent(bucketStartTimeNs + bucketSizeNs + 350, appUid);
+ auto moveToForegroundEvent2 =
+ CreateMoveToForegroundEvent(bucketStartTimeNs + 2 * bucketSizeNs - 1, appUid);
+
+ /*
+ bucket #1 bucket #2
+
+
+ | | | | | | | | | | (crashEvents)
+ |-------------------------------------|-----------------------------------|---------
+
+ | | (MoveToBkground)
+
+ | | (MoveToForeground)
+
+ | | (SyncIsOn)
+ | (SyncIsOff)
+ | | (ScreenIsOn)
+ | (ScreenIsOff)
+ */
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(std::move(crashEvent1));
+ events.push_back(std::move(crashEvent2));
+ events.push_back(std::move(crashEvent3));
+ events.push_back(std::move(crashEvent4));
+ events.push_back(std::move(crashEvent5));
+ events.push_back(std::move(crashEvent6));
+ events.push_back(std::move(crashEvent7));
+ events.push_back(std::move(crashEvent8));
+ events.push_back(std::move(crashEvent9));
+ events.push_back(std::move(crashEvent10));
+ events.push_back(std::move(screenTurnedOnEvent));
+ events.push_back(std::move(screenTurnedOffEvent));
+ events.push_back(std::move(screenTurnedOnEvent2));
+ events.push_back(std::move(syncOnEvent1));
+ events.push_back(std::move(syncOffEvent1));
+ events.push_back(std::move(syncOnEvent2));
+ events.push_back(std::move(moveToBackgroundEvent1));
+ events.push_back(std::move(moveToForegroundEvent1));
+ events.push_back(std::move(moveToBackgroundEvent2));
+ events.push_back(std::move(moveToForegroundEvent2));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info_size(), 2);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info(0).count(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).count_metrics().data(0).bucket_info(1).count(), 3);
+ auto data = reports.reports(0).metrics(0).count_metrics().data(0);
+ // Validate dimension value.
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ // Uid field.
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), appUid);
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp b/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp
index 9ec831b..b975907 100644
--- a/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/PartialBucket_e2e_test.cpp
@@ -113,96 +113,107 @@
}
} // anonymous namespace
-// TODO(b/149590301): Update this test to use new socket schema.
-//TEST(PartialBucketE2eTest, TestCountMetricWithoutSplit) {
-// shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
-// SendConfig(service, MakeConfig());
-// int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
-// // initialized with.
-//
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 1).get());
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 2).get());
-//
-// ConfigMetricsReport report = GetReports(service->mProcessor, start + 3);
-// // Expect no metrics since the bucket has not finished yet.
-// EXPECT_EQ(1, report.metrics_size());
-// EXPECT_EQ(0, report.metrics(0).count_metrics().data_size());
-//}
-//
-//TEST(PartialBucketE2eTest, TestCountMetricNoSplitOnNewApp) {
-// shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
-// SendConfig(service, MakeConfig());
-// int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
-// // initialized with.
-//
-// // Force the uidmap to update at timestamp 2.
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 1).get());
-// // This is a new installation, so there shouldn't be a split (should be same as the without
-// // split case).
-// service->mUidMap->updateApp(start + 2, String16(kApp1.c_str()), 1, 2, String16("v2"),
-// String16(""));
-// // Goes into the second bucket.
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 3).get());
-//
-// ConfigMetricsReport report = GetReports(service->mProcessor, start + 4);
-// EXPECT_EQ(1, report.metrics_size());
-// EXPECT_EQ(0, report.metrics(0).count_metrics().data_size());
-//}
-//
-//TEST(PartialBucketE2eTest, TestCountMetricSplitOnUpgrade) {
-// shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
-// SendConfig(service, MakeConfig());
-// int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
-// // initialized with.
-// service->mUidMap->updateMap(start, {1}, {1}, {String16("v1")}, {String16(kApp1.c_str())},
-// {String16("")});
-//
-// // Force the uidmap to update at timestamp 2.
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 1).get());
-// service->mUidMap->updateApp(start + 2, String16(kApp1.c_str()), 1, 2, String16("v2"),
-// String16(""));
-// // Goes into the second bucket.
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 3).get());
-//
-// ConfigMetricsReport report = GetReports(service->mProcessor, start + 4);
-// backfillStartEndTimestamp(&report);
-//
-// ASSERT_EQ(1, report.metrics_size());
-// ASSERT_EQ(1, report.metrics(0).count_metrics().data_size());
-// ASSERT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info_size());
-// EXPECT_TRUE(report.metrics(0).count_metrics().data(0).bucket_info(0).
-// has_start_bucket_elapsed_nanos());
-// EXPECT_TRUE(report.metrics(0).count_metrics().data(0).bucket_info(0).
-// has_end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info(0).count());
-//}
-//
-//TEST(PartialBucketE2eTest, TestCountMetricSplitOnRemoval) {
-// shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
-// SendConfig(service, MakeConfig());
-// int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
-// // initialized with.
-// service->mUidMap->updateMap(start, {1}, {1}, {String16("v1")}, {String16(kApp1.c_str())},
-// {String16("")});
-//
-// // Force the uidmap to update at timestamp 2.
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 1).get());
-// service->mUidMap->removeApp(start + 2, String16(kApp1.c_str()), 1);
-// // Goes into the second bucket.
-// service->mProcessor->OnLogEvent(CreateAppCrashEvent(100, start + 3).get());
-//
-// ConfigMetricsReport report = GetReports(service->mProcessor, start + 4);
-// backfillStartEndTimestamp(&report);
-//
-// ASSERT_EQ(1, report.metrics_size());
-// ASSERT_EQ(1, report.metrics(0).count_metrics().data_size());
-// ASSERT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info_size());
-// EXPECT_TRUE(report.metrics(0).count_metrics().data(0).bucket_info(0).
-// has_start_bucket_elapsed_nanos());
-// EXPECT_TRUE(report.metrics(0).count_metrics().data(0).bucket_info(0).
-// has_end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info(0).count());
-//}
+TEST(PartialBucketE2eTest, TestCountMetricWithoutSplit) {
+ shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
+ SendConfig(service, MakeConfig());
+ int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
+ // initialized with.
+
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 1, 100).get());
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 2, 100).get());
+
+ ConfigMetricsReport report = GetReports(service->mProcessor, start + 3);
+ // Expect no metrics since the bucket has not finished yet.
+ EXPECT_EQ(1, report.metrics_size());
+ EXPECT_EQ(0, report.metrics(0).count_metrics().data_size());
+}
+
+TEST(PartialBucketE2eTest, TestCountMetricNoSplitOnNewApp) {
+ shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
+ SendConfig(service, MakeConfig());
+ int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
+ // initialized with.
+
+ // Force the uidmap to update at timestamp 2.
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 1, 100).get());
+ // This is a new installation, so there shouldn't be a split (should be same as the without
+ // split case).
+ service->mUidMap->updateApp(start + 2, String16(kApp1.c_str()), 1, 2, String16("v2"),
+ String16(""));
+ // Goes into the second bucket.
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 3, 100).get());
+
+ ConfigMetricsReport report = GetReports(service->mProcessor, start + 4);
+ EXPECT_EQ(1, report.metrics_size());
+ EXPECT_EQ(0, report.metrics(0).count_metrics().data_size());
+}
+
+TEST(PartialBucketE2eTest, TestCountMetricSplitOnUpgrade) {
+ shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
+ SendConfig(service, MakeConfig());
+ int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
+ // initialized with.
+ service->mUidMap->updateMap(start, {1}, {1}, {String16("v1")}, {String16(kApp1.c_str())},
+ {String16("")});
+
+ // Force the uidmap to update at timestamp 2.
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 1, 100).get());
+ service->mUidMap->updateApp(start + 2, String16(kApp1.c_str()), 1, 2, String16("v2"),
+ String16(""));
+ // Goes into the second bucket.
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 3, 100).get());
+
+ ConfigMetricsReport report = GetReports(service->mProcessor, start + 4);
+ backfillStartEndTimestamp(&report);
+
+ ASSERT_EQ(1, report.metrics_size());
+ ASSERT_EQ(1, report.metrics(0).count_metrics().data_size());
+ ASSERT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info_size());
+ EXPECT_TRUE(report.metrics(0)
+ .count_metrics()
+ .data(0)
+ .bucket_info(0)
+ .has_start_bucket_elapsed_nanos());
+ EXPECT_TRUE(report.metrics(0)
+ .count_metrics()
+ .data(0)
+ .bucket_info(0)
+ .has_end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info(0).count());
+}
+
+TEST(PartialBucketE2eTest, TestCountMetricSplitOnRemoval) {
+ shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
+ SendConfig(service, MakeConfig());
+ int64_t start = getElapsedRealtimeNs(); // This is the start-time the metrics producers are
+ // initialized with.
+ service->mUidMap->updateMap(start, {1}, {1}, {String16("v1")}, {String16(kApp1.c_str())},
+ {String16("")});
+
+ // Force the uidmap to update at timestamp 2.
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 1, 100).get());
+ service->mUidMap->removeApp(start + 2, String16(kApp1.c_str()), 1);
+ // Goes into the second bucket.
+ service->mProcessor->OnLogEvent(CreateAppCrashEvent(start + 3, 100).get());
+
+ ConfigMetricsReport report = GetReports(service->mProcessor, start + 4);
+ backfillStartEndTimestamp(&report);
+
+ ASSERT_EQ(1, report.metrics_size());
+ ASSERT_EQ(1, report.metrics(0).count_metrics().data_size());
+ ASSERT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info_size());
+ EXPECT_TRUE(report.metrics(0)
+ .count_metrics()
+ .data(0)
+ .bucket_info(0)
+ .has_start_bucket_elapsed_nanos());
+ EXPECT_TRUE(report.metrics(0)
+ .count_metrics()
+ .data(0)
+ .bucket_info(0)
+ .has_end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, report.metrics(0).count_metrics().data(0).bucket_info(0).count());
+}
TEST(PartialBucketE2eTest, TestValueMetricWithoutMinPartialBucket) {
shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
diff --git a/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp b/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp
index 99dbaf1..a87bb71 100644
--- a/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/ValueMetric_pull_e2e_test.cpp
@@ -64,317 +64,313 @@
} // namespace
-// TODO(b/149590301): Update this test to use new socket schema.
-//TEST(ValueMetricE2eTest, TestPulledEvents) {
-// auto config = CreateStatsdConfig();
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.value_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// android::util::SUBSYSTEM_SLEEP_STATE);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-//
-// // When creating the config, the value metric producer should register the alarm at the
-// // end of the current bucket.
-// EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
-// EXPECT_EQ(bucketSizeNs,
-// processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
-// int64_t& expectedPullTimeNs =
-// processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, expectedPullTimeNs);
-//
-// auto screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 55);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// auto screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 65);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 75);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// // Pulling alarm arrives on time and reset the sequential pulling alarm.
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, expectedPullTimeNs);
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-//
-// screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 2 * bucketSizeNs + 15);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 4 * bucketSizeNs + 11);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::ValueMetricDataWrapper valueMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).value_metrics(), &valueMetrics);
-// EXPECT_GT((int)valueMetrics.data_size(), 1);
-//
-// auto data = valueMetrics.data(0);
-// EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// // We have 4 buckets, the first one was incomplete since the condition was unknown.
-// EXPECT_EQ(4, data.bucket_info_size());
-//
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(0).values_size());
-//
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(1).values_size());
-//
-// EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(2).values_size());
-//
-// EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(3).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(3).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(3).values_size());
-//}
-//
-//TEST(ValueMetricE2eTest, TestPulledEvents_LateAlarm) {
-// auto config = CreateStatsdConfig();
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// // 10 mins == 2 bucket durations.
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.value_metric(0).bucket()) * 1000000;
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// android::util::SUBSYSTEM_SLEEP_STATE);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-//
-// // When creating the config, the value metric producer should register the alarm at the
-// // end of the current bucket.
-// EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
-// EXPECT_EQ(bucketSizeNs,
-// processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
-// int64_t& expectedPullTimeNs =
-// processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, expectedPullTimeNs);
-//
-// // Screen off/on/off events.
-// auto screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 55);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// auto screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 65);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 75);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// // Pulling alarm arrives late by 2 buckets and 1 ns. 2 buckets late is too far away in the
-// // future, data will be skipped.
-// processor->informPullAlarmFired(expectedPullTimeNs + 2 * bucketSizeNs + 1);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, expectedPullTimeNs);
-//
-// // This screen state change will start a new bucket.
-// screenOnEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
-// configAddedTimeNs + 4 * bucketSizeNs + 65);
-// processor->OnLogEvent(screenOnEvent.get());
-//
-// // The alarm is delayed but we already created a bucket thanks to the screen state condition.
-// // This bucket does not have to be skipped since the alarm arrives in time for the next bucket.
-// processor->informPullAlarmFired(expectedPullTimeNs + bucketSizeNs + 21);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 6 * bucketSizeNs, expectedPullTimeNs);
-//
-// screenOffEvent = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
-// configAddedTimeNs + 6 * bucketSizeNs + 31);
-// processor->OnLogEvent(screenOffEvent.get());
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + bucketSizeNs + 21);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 8 * bucketSizeNs, expectedPullTimeNs);
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 9 * bucketSizeNs, expectedPullTimeNs);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 9 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::ValueMetricDataWrapper valueMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).value_metrics(), &valueMetrics);
-// EXPECT_GT((int)valueMetrics.data_size(), 1);
-//
-// auto data = valueMetrics.data(0);
-// EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// EXPECT_EQ(3, data.bucket_info_size());
-//
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(0).values_size());
-//
-// EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(1).values_size());
-//
-// EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 10 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, data.bucket_info(2).values_size());
-//}
-//
-//TEST(ValueMetricE2eTest, TestPulledEvents_WithActivation) {
-// auto config = CreateStatsdConfig(false);
-// int64_t baseTimeNs = getElapsedRealtimeNs();
-// int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
-// int64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.value_metric(0).bucket()) * 1000000;
-//
-// auto batterySaverStartMatcher = CreateBatterySaverModeStartAtomMatcher();
-// *config.add_atom_matcher() = batterySaverStartMatcher;
-// const int64_t ttlNs = 2 * bucketSizeNs; // Two buckets.
-// auto metric_activation = config.add_metric_activation();
-// metric_activation->set_metric_id(metricId);
-// metric_activation->set_activation_type(ACTIVATE_IMMEDIATELY);
-// auto event_activation = metric_activation->add_event_activation();
-// event_activation->set_atom_matcher_id(batterySaverStartMatcher.id());
-// event_activation->set_ttl_seconds(ttlNs / 1000000000);
-//
-// ConfigKey cfgKey;
-// auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
-// SharedRefBase::make<FakeSubsystemSleepCallback>(),
-// android::util::SUBSYSTEM_SLEEP_STATE);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// processor->mPullerManager->ForceClearPullerCache();
-//
-// int startBucketNum = processor->mMetricsManagers.begin()->second->
-// mAllMetricProducers[0]->getCurrentBucketNum();
-// EXPECT_GT(startBucketNum, (int64_t)0);
-// EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// // When creating the config, the value metric producer should register the alarm at the
-// // end of the current bucket.
-// EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
-// EXPECT_EQ(bucketSizeNs,
-// processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
-// int64_t& expectedPullTimeNs =
-// processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, expectedPullTimeNs);
-//
-// // Pulling alarm arrives on time and reset the sequential pulling alarm.
-// processor->informPullAlarmFired(expectedPullTimeNs + 1); // 15 mins + 1 ns.
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, expectedPullTimeNs);
-// EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// // Activate the metric. A pull occurs here
-// const int64_t activationNs = configAddedTimeNs + bucketSizeNs + (2 * 1000 * 1000); // 2 millis.
-// auto batterySaverOnEvent = CreateBatterySaverOnEvent(activationNs);
-// processor->OnLogEvent(batterySaverOnEvent.get()); // 15 mins + 2 ms.
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 1); // 20 mins + 1 ns.
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs, expectedPullTimeNs);
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 2); // 25 mins + 2 ns.
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, expectedPullTimeNs);
-//
-// // Create random event to deactivate metric.
-// auto deactivationEvent = CreateScreenBrightnessChangedEvent(50, activationNs + ttlNs + 1);
-// processor->OnLogEvent(deactivationEvent.get());
-// EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 3);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, expectedPullTimeNs);
-//
-// processor->informPullAlarmFired(expectedPullTimeNs + 4);
-// EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 6 * bucketSizeNs, expectedPullTimeNs);
-//
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(1, reports.reports_size());
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// StatsLogReport::ValueMetricDataWrapper valueMetrics;
-// sortMetricDataByDimensionsValue(
-// reports.reports(0).metrics(0).value_metrics(), &valueMetrics);
-// EXPECT_GT((int)valueMetrics.data_size(), 0);
-//
-// auto data = valueMetrics.data(0);
-// EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
-// EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
-// EXPECT_EQ(1 /* subsystem name field */,
-// data.dimensions_in_what().value_tuple().dimensions_value(0).field());
-// EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
-// // We have 2 full buckets, the two surrounding the activation are dropped.
-// EXPECT_EQ(2, data.bucket_info_size());
-//
-// auto bucketInfo = data.bucket_info(0);
-// EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, bucketInfo.values_size());
-//
-// bucketInfo = data.bucket_info(1);
-// EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
-// EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
-// EXPECT_EQ(1, bucketInfo.values_size());
-//}
+TEST(ValueMetricE2eTest, TestPulledEvents) {
+ auto config = CreateStatsdConfig();
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.value_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(),
+ android::util::SUBSYSTEM_SLEEP_STATE);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+
+ // When creating the config, the value metric producer should register the alarm at the
+ // end of the current bucket.
+ EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
+ EXPECT_EQ(bucketSizeNs,
+ processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
+ int64_t& expectedPullTimeNs =
+ processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, expectedPullTimeNs);
+
+ auto screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 55, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ auto screenOnEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 65, android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 75, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ // Pulling alarm arrives on time and reset the sequential pulling alarm.
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, expectedPullTimeNs);
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+
+ screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 2 * bucketSizeNs + 15,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 4 * bucketSizeNs + 11,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::ValueMetricDataWrapper valueMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).value_metrics(), &valueMetrics);
+ EXPECT_GT((int)valueMetrics.data_size(), 1);
+
+ auto data = valueMetrics.data(0);
+ EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ // We have 4 buckets, the first one was incomplete since the condition was unknown.
+ EXPECT_EQ(4, data.bucket_info_size());
+
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(0).values_size());
+
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(1).values_size());
+
+ EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(2).values_size());
+
+ EXPECT_EQ(baseTimeNs + 7 * bucketSizeNs, data.bucket_info(3).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(3).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(3).values_size());
+}
+
+TEST(ValueMetricE2eTest, TestPulledEvents_LateAlarm) {
+ auto config = CreateStatsdConfig();
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ // 10 mins == 2 bucket durations.
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.value_metric(0).bucket()) * 1000000;
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(),
+ android::util::SUBSYSTEM_SLEEP_STATE);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+
+ // When creating the config, the value metric producer should register the alarm at the
+ // end of the current bucket.
+ EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
+ EXPECT_EQ(bucketSizeNs,
+ processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
+ int64_t& expectedPullTimeNs =
+ processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, expectedPullTimeNs);
+
+ // Screen off/on/off events.
+ auto screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 55, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ auto screenOnEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 65, android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ screenOffEvent =
+ CreateScreenStateChangedEvent(configAddedTimeNs + 75, android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ // Pulling alarm arrives late by 2 buckets and 1 ns. 2 buckets late is too far away in the
+ // future, data will be skipped.
+ processor->informPullAlarmFired(expectedPullTimeNs + 2 * bucketSizeNs + 1);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, expectedPullTimeNs);
+
+ // This screen state change will start a new bucket.
+ screenOnEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 4 * bucketSizeNs + 65,
+ android::view::DISPLAY_STATE_ON);
+ processor->OnLogEvent(screenOnEvent.get());
+
+ // The alarm is delayed but we already created a bucket thanks to the screen state condition.
+ // This bucket does not have to be skipped since the alarm arrives in time for the next bucket.
+ processor->informPullAlarmFired(expectedPullTimeNs + bucketSizeNs + 21);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 6 * bucketSizeNs, expectedPullTimeNs);
+
+ screenOffEvent = CreateScreenStateChangedEvent(configAddedTimeNs + 6 * bucketSizeNs + 31,
+ android::view::DISPLAY_STATE_OFF);
+ processor->OnLogEvent(screenOffEvent.get());
+
+ processor->informPullAlarmFired(expectedPullTimeNs + bucketSizeNs + 21);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 8 * bucketSizeNs, expectedPullTimeNs);
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 9 * bucketSizeNs, expectedPullTimeNs);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 9 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::ValueMetricDataWrapper valueMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).value_metrics(), &valueMetrics);
+ EXPECT_GT((int)valueMetrics.data_size(), 1);
+
+ auto data = valueMetrics.data(0);
+ EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ EXPECT_EQ(3, data.bucket_info_size());
+
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 6 * bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(0).values_size());
+
+ EXPECT_EQ(baseTimeNs + 8 * bucketSizeNs, data.bucket_info(1).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(1).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(1).values_size());
+
+ EXPECT_EQ(baseTimeNs + 9 * bucketSizeNs, data.bucket_info(2).start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 10 * bucketSizeNs, data.bucket_info(2).end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, data.bucket_info(2).values_size());
+}
+
+TEST(ValueMetricE2eTest, TestPulledEvents_WithActivation) {
+ auto config = CreateStatsdConfig(false);
+ int64_t baseTimeNs = getElapsedRealtimeNs();
+ int64_t configAddedTimeNs = 10 * 60 * NS_PER_SEC + baseTimeNs;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.value_metric(0).bucket()) * 1000000;
+
+ auto batterySaverStartMatcher = CreateBatterySaverModeStartAtomMatcher();
+ *config.add_atom_matcher() = batterySaverStartMatcher;
+ const int64_t ttlNs = 2 * bucketSizeNs; // Two buckets.
+ auto metric_activation = config.add_metric_activation();
+ metric_activation->set_metric_id(metricId);
+ metric_activation->set_activation_type(ACTIVATE_IMMEDIATELY);
+ auto event_activation = metric_activation->add_event_activation();
+ event_activation->set_atom_matcher_id(batterySaverStartMatcher.id());
+ event_activation->set_ttl_seconds(ttlNs / 1000000000);
+
+ ConfigKey cfgKey;
+ auto processor = CreateStatsLogProcessor(baseTimeNs, configAddedTimeNs, config, cfgKey,
+ SharedRefBase::make<FakeSubsystemSleepCallback>(),
+ android::util::SUBSYSTEM_SLEEP_STATE);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ processor->mPullerManager->ForceClearPullerCache();
+
+ int startBucketNum = processor->mMetricsManagers.begin()
+ ->second->mAllMetricProducers[0]
+ ->getCurrentBucketNum();
+ EXPECT_GT(startBucketNum, (int64_t)0);
+ EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ // When creating the config, the value metric producer should register the alarm at the
+ // end of the current bucket.
+ EXPECT_EQ((size_t)1, processor->mPullerManager->mReceivers.size());
+ EXPECT_EQ(bucketSizeNs,
+ processor->mPullerManager->mReceivers.begin()->second.front().intervalNs);
+ int64_t& expectedPullTimeNs =
+ processor->mPullerManager->mReceivers.begin()->second.front().nextPullTimeNs;
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + bucketSizeNs, expectedPullTimeNs);
+
+ // Pulling alarm arrives on time and reset the sequential pulling alarm.
+ processor->informPullAlarmFired(expectedPullTimeNs + 1); // 15 mins + 1 ns.
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 2 * bucketSizeNs, expectedPullTimeNs);
+ EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ // Activate the metric. A pull occurs here
+ const int64_t activationNs = configAddedTimeNs + bucketSizeNs + (2 * 1000 * 1000); // 2 millis.
+ auto batterySaverOnEvent = CreateBatterySaverOnEvent(activationNs);
+ processor->OnLogEvent(batterySaverOnEvent.get()); // 15 mins + 2 ms.
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 1); // 20 mins + 1 ns.
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 3 * bucketSizeNs, expectedPullTimeNs);
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 2); // 25 mins + 2 ns.
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 4 * bucketSizeNs, expectedPullTimeNs);
+
+ // Create random event to deactivate metric.
+ auto deactivationEvent = CreateScreenBrightnessChangedEvent(activationNs + ttlNs + 1, 50);
+ processor->OnLogEvent(deactivationEvent.get());
+ EXPECT_FALSE(processor->mMetricsManagers.begin()->second->mAllMetricProducers[0]->isActive());
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 3);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 5 * bucketSizeNs, expectedPullTimeNs);
+
+ processor->informPullAlarmFired(expectedPullTimeNs + 4);
+ EXPECT_EQ(baseTimeNs + startBucketNum * bucketSizeNs + 6 * bucketSizeNs, expectedPullTimeNs);
+
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, configAddedTimeNs + 7 * bucketSizeNs + 10, false, true,
+ ADB_DUMP, FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(1, reports.reports_size());
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ StatsLogReport::ValueMetricDataWrapper valueMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).value_metrics(), &valueMetrics);
+ EXPECT_GT((int)valueMetrics.data_size(), 0);
+
+ auto data = valueMetrics.data(0);
+ EXPECT_EQ(android::util::SUBSYSTEM_SLEEP_STATE, data.dimensions_in_what().field());
+ EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+ EXPECT_EQ(1 /* subsystem name field */,
+ data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+ EXPECT_FALSE(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str().empty());
+ // We have 2 full buckets, the two surrounding the activation are dropped.
+ EXPECT_EQ(2, data.bucket_info_size());
+
+ auto bucketInfo = data.bucket_info(0);
+ EXPECT_EQ(baseTimeNs + 3 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, bucketInfo.values_size());
+
+ bucketInfo = data.bucket_info(1);
+ EXPECT_EQ(baseTimeNs + 4 * bucketSizeNs, bucketInfo.start_bucket_elapsed_nanos());
+ EXPECT_EQ(baseTimeNs + 5 * bucketSizeNs, bucketInfo.end_bucket_elapsed_nanos());
+ EXPECT_EQ(1, bucketInfo.values_size());
+}
/**
* Test initialization of a simple value metric that is sliced by a state.
diff --git a/cmds/statsd/tests/e2e/WakelockDuration_e2e_test.cpp b/cmds/statsd/tests/e2e/WakelockDuration_e2e_test.cpp
index 21092e2..ddd8f95 100644
--- a/cmds/statsd/tests/e2e/WakelockDuration_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/WakelockDuration_e2e_test.cpp
@@ -61,292 +61,290 @@
return config;
}
-std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1"),
- CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
+std::vector<int> attributionUids1 = {111, 222, 222};
+std::vector<string> attributionTags1 = {"App1", "GMSCoreModule1", "GMSCoreModule2"};
-std::vector<AttributionNodeInternal> attributions2 = {CreateAttribution(111, "App2"),
- CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
+std::vector<int> attributionUids2 = {111, 222, 222};
+std::vector<string> attributionTags2 = {"App2", "GMSCoreModule1", "GMSCoreModule2"};
-// TODO(b/149590301): Update this helper to use new socket schema.
-///*
-//Events:
-//Screen off is met from (200ns,1 min+500ns].
-//Acquire event for wl1 from 2ns to 1min+2ns
-//Acquire event for wl2 from 1min-10ns to 2min-15ns
-//*/
-//void FeedEvents(StatsdConfig config, sp<StatsLogProcessor> processor) {
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-//
-// auto screenTurnedOnEvent = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_ON, bucketStartTimeNs + 1);
-// auto screenTurnedOffEvent = CreateScreenStateChangedEvent(
-// android::view::DisplayStateEnum::DISPLAY_STATE_OFF, bucketStartTimeNs + 200);
-// auto screenTurnedOnEvent2 =
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
-// bucketStartTimeNs + bucketSizeNs + 500);
-//
-// auto acquireEvent1 = CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 2);
-// auto releaseEvent1 =
-// CreateReleaseWakelockEvent(attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + 2);
-// auto acquireEvent2 =
-// CreateAcquireWakelockEvent(attributions2, "wl2", bucketStartTimeNs + bucketSizeNs - 10);
-// auto releaseEvent2 = CreateReleaseWakelockEvent(attributions2, "wl2",
-// bucketStartTimeNs + 2 * bucketSizeNs - 15);
-//
-// std::vector<std::unique_ptr<LogEvent>> events;
-//
-// events.push_back(std::move(screenTurnedOnEvent));
-// events.push_back(std::move(screenTurnedOffEvent));
-// events.push_back(std::move(screenTurnedOnEvent2));
-// events.push_back(std::move(acquireEvent1));
-// events.push_back(std::move(acquireEvent2));
-// events.push_back(std::move(releaseEvent1));
-// events.push_back(std::move(releaseEvent2));
-//
-// sortLogEventsByTimestamp(&events);
-//
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//}
+/*
+Events:
+Screen off is met from (200ns,1 min+500ns].
+Acquire event for wl1 from 2ns to 1min+2ns
+Acquire event for wl2 from 1min-10ns to 2min-15ns
+*/
+void FeedEvents(StatsdConfig config, sp<StatsLogProcessor> processor) {
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+
+ auto screenTurnedOnEvent = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 1, android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+ auto screenTurnedOffEvent = CreateScreenStateChangedEvent(
+ bucketStartTimeNs + 200, android::view::DisplayStateEnum::DISPLAY_STATE_OFF);
+ auto screenTurnedOnEvent2 =
+ CreateScreenStateChangedEvent(bucketStartTimeNs + bucketSizeNs + 500,
+ android::view::DisplayStateEnum::DISPLAY_STATE_ON);
+
+ auto acquireEvent1 = CreateAcquireWakelockEvent(bucketStartTimeNs + 2, attributionUids1,
+ attributionTags1, "wl1");
+ auto releaseEvent1 = CreateReleaseWakelockEvent(bucketStartTimeNs + bucketSizeNs + 2,
+ attributionUids1, attributionTags1, "wl1");
+ auto acquireEvent2 = CreateAcquireWakelockEvent(bucketStartTimeNs + bucketSizeNs - 10,
+ attributionUids2, attributionTags2, "wl2");
+ auto releaseEvent2 = CreateReleaseWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs - 15,
+ attributionUids2, attributionTags2, "wl2");
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+
+ events.push_back(std::move(screenTurnedOnEvent));
+ events.push_back(std::move(screenTurnedOffEvent));
+ events.push_back(std::move(screenTurnedOnEvent2));
+ events.push_back(std::move(acquireEvent1));
+ events.push_back(std::move(acquireEvent2));
+ events.push_back(std::move(releaseEvent1));
+ events.push_back(std::move(releaseEvent2));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+}
} // namespace
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForSumDuration1) {
-// ConfigKey cfgKey;
-// auto config = CreateStatsdConfig(DurationMetric::SUM);
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// FeedEvents(config, processor);
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs - 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// // Only 1 dimension output. The tag dimension in the predicate has been aggregated.
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
-//
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// // Validate dimension value.
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, 111);
-// // Validate bucket info.
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 1);
-// data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// // The wakelock holding interval starts from the screen off event and to the end of the 1st
-// // bucket.
-// EXPECT_EQ((unsigned long long)data.bucket_info(0).duration_nanos(), bucketSizeNs - 200);
-//}
-//
-//TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForSumDuration2) {
-// ConfigKey cfgKey;
-// auto config = CreateStatsdConfig(DurationMetric::SUM);
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// FeedEvents(config, processor);
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
-// // Dump the report after the end of 2nd bucket.
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 2);
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// // Validate dimension value.
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, 111);
-// // Two output buckets.
-// // The wakelock holding interval in the 1st bucket starts from the screen off event and to
-// // the end of the 1st bucket.
-// EXPECT_EQ((unsigned long long)data.bucket_info(0).duration_nanos(),
-// bucketStartTimeNs + bucketSizeNs - (bucketStartTimeNs + 200));
-// // The wakelock holding interval in the 2nd bucket starts at the beginning of the bucket and
-// // ends at the second screen on event.
-// EXPECT_EQ((unsigned long long)data.bucket_info(1).duration_nanos(), 500UL);
-//}
-//TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForSumDuration3) {
-// ConfigKey cfgKey;
-// auto config = CreateStatsdConfig(DurationMetric::SUM);
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// FeedEvents(config, processor);
-// vector<uint8_t> buffer;
-// ConfigMetricsReportList reports;
-//
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 2 * bucketSizeNs + 90));
-// events.push_back(CreateAcquireWakelockEvent(attributions1, "wl3",
-// bucketStartTimeNs + 2 * bucketSizeNs + 100));
-// events.push_back(CreateReleaseWakelockEvent(attributions1, "wl3",
-// bucketStartTimeNs + 5 * bucketSizeNs + 100));
-// sortLogEventsByTimestamp(&events);
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 6 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 6);
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, 111);
-// // The last wakelock holding spans 4 buckets.
-// EXPECT_EQ((unsigned long long)data.bucket_info(2).duration_nanos(), bucketSizeNs - 100);
-// EXPECT_EQ((unsigned long long)data.bucket_info(3).duration_nanos(), bucketSizeNs);
-// EXPECT_EQ((unsigned long long)data.bucket_info(4).duration_nanos(), bucketSizeNs);
-// EXPECT_EQ((unsigned long long)data.bucket_info(5).duration_nanos(), 100UL);
-//}
-//
-//TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForMaxDuration1) {
-// ConfigKey cfgKey;
-// auto config = CreateStatsdConfig(DurationMetric::MAX_SPARSE);
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// FeedEvents(config, processor);
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs - 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-//
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-//
-// EXPECT_EQ(reports.reports_size(), 1);
-//
-// // When using ProtoOutputStream, if nothing written to a sub msg, it won't be treated as
-// // one. It was previsouly 1 because we had a fake onDumpReport which calls add_metric() by
-// // itself.
-// EXPECT_EQ(1, reports.reports(0).metrics_size());
-// EXPECT_EQ(0, reports.reports(0).metrics(0).duration_metrics().data_size());
-//}
-//
-//TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForMaxDuration2) {
-// ConfigKey cfgKey;
-// auto config = CreateStatsdConfig(DurationMetric::MAX_SPARSE);
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// FeedEvents(config, processor);
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
-// // Dump the report after the end of 2nd bucket. One dimension with one bucket.
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 1);
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// // Validate dimension value.
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, 111);
-// // The max is acquire event for wl1 to screen off start.
-// EXPECT_EQ((unsigned long long)data.bucket_info(0).duration_nanos(), bucketSizeNs + 2 - 200);
-//}
-//
-//TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForMaxDuration3) {
-// ConfigKey cfgKey;
-// auto config = CreateStatsdConfig(DurationMetric::MAX_SPARSE);
-// uint64_t bucketStartTimeNs = 10000000000;
-// uint64_t bucketSizeNs =
-// TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-// auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
-// EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
-// EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-// FeedEvents(config, processor);
-// ConfigMetricsReportList reports;
-// vector<uint8_t> buffer;
-//
-// std::vector<std::unique_ptr<LogEvent>> events;
-// events.push_back(
-// CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_OFF,
-// bucketStartTimeNs + 2 * bucketSizeNs + 90));
-// events.push_back(CreateAcquireWakelockEvent(attributions1, "wl3",
-// bucketStartTimeNs + 2 * bucketSizeNs + 100));
-// events.push_back(CreateReleaseWakelockEvent(attributions1, "wl3",
-// bucketStartTimeNs + 5 * bucketSizeNs + 100));
-// sortLogEventsByTimestamp(&events);
-// for (const auto& event : events) {
-// processor->OnLogEvent(event.get());
-// }
-//
-// processor->onDumpReport(cfgKey, bucketStartTimeNs + 6 * bucketSizeNs + 1, false, true,
-// ADB_DUMP, FAST, &buffer);
-// EXPECT_TRUE(buffer.size() > 0);
-// EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
-// backfillDimensionPath(&reports);
-// backfillStringInReport(&reports);
-// backfillStartEndTimestamp(&reports);
-// EXPECT_EQ(reports.reports_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
-// EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 2);
-// auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
-// ValidateAttributionUidDimension(data.dimensions_in_what(),
-// android::util::WAKELOCK_STATE_CHANGED, 111);
-// // The last wakelock holding spans 4 buckets.
-// EXPECT_EQ((unsigned long long)data.bucket_info(1).duration_nanos(), 3 * bucketSizeNs);
-// EXPECT_EQ((unsigned long long)data.bucket_info(1).start_bucket_elapsed_nanos(),
-// bucketStartTimeNs + 5 * bucketSizeNs);
-// EXPECT_EQ((unsigned long long)data.bucket_info(1).end_bucket_elapsed_nanos(),
-// bucketStartTimeNs + 6 * bucketSizeNs);
-//}
+TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForSumDuration1) {
+ ConfigKey cfgKey;
+ auto config = CreateStatsdConfig(DurationMetric::SUM);
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ FeedEvents(config, processor);
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs - 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ // Only 1 dimension output. The tag dimension in the predicate has been aggregated.
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
+
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ // Validate dimension value.
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 111);
+ // Validate bucket info.
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 1);
+ data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ // The wakelock holding interval starts from the screen off event and to the end of the 1st
+ // bucket.
+ EXPECT_EQ((unsigned long long)data.bucket_info(0).duration_nanos(), bucketSizeNs - 200);
+}
+
+TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForSumDuration2) {
+ ConfigKey cfgKey;
+ auto config = CreateStatsdConfig(DurationMetric::SUM);
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ FeedEvents(config, processor);
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
+ // Dump the report after the end of 2nd bucket.
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 2);
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ // Validate dimension value.
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 111);
+ // Two output buckets.
+ // The wakelock holding interval in the 1st bucket starts from the screen off event and to
+ // the end of the 1st bucket.
+ EXPECT_EQ((unsigned long long)data.bucket_info(0).duration_nanos(),
+ bucketStartTimeNs + bucketSizeNs - (bucketStartTimeNs + 200));
+ // The wakelock holding interval in the 2nd bucket starts at the beginning of the bucket and
+ // ends at the second screen on event.
+ EXPECT_EQ((unsigned long long)data.bucket_info(1).duration_nanos(), 500UL);
+}
+
+TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForSumDuration3) {
+ ConfigKey cfgKey;
+ auto config = CreateStatsdConfig(DurationMetric::SUM);
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ FeedEvents(config, processor);
+ vector<uint8_t> buffer;
+ ConfigMetricsReportList reports;
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs + 90,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 100,
+ attributionUids1, attributionTags1, "wl3"));
+ events.push_back(CreateReleaseWakelockEvent(bucketStartTimeNs + 5 * bucketSizeNs + 100,
+ attributionUids1, attributionTags1, "wl3"));
+ sortLogEventsByTimestamp(&events);
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 6 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 6);
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 111);
+ // The last wakelock holding spans 4 buckets.
+ EXPECT_EQ((unsigned long long)data.bucket_info(2).duration_nanos(), bucketSizeNs - 100);
+ EXPECT_EQ((unsigned long long)data.bucket_info(3).duration_nanos(), bucketSizeNs);
+ EXPECT_EQ((unsigned long long)data.bucket_info(4).duration_nanos(), bucketSizeNs);
+ EXPECT_EQ((unsigned long long)data.bucket_info(5).duration_nanos(), 100UL);
+}
+
+TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForMaxDuration1) {
+ ConfigKey cfgKey;
+ auto config = CreateStatsdConfig(DurationMetric::MAX_SPARSE);
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ FeedEvents(config, processor);
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs - 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+
+ EXPECT_EQ(reports.reports_size(), 1);
+
+ // When using ProtoOutputStream, if nothing written to a sub msg, it won't be treated as
+ // one. It was previsouly 1 because we had a fake onDumpReport which calls add_metric() by
+ // itself.
+ EXPECT_EQ(1, reports.reports(0).metrics_size());
+ EXPECT_EQ(0, reports.reports(0).metrics(0).duration_metrics().data_size());
+}
+
+TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForMaxDuration2) {
+ ConfigKey cfgKey;
+ auto config = CreateStatsdConfig(DurationMetric::MAX_SPARSE);
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ FeedEvents(config, processor);
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
+ // Dump the report after the end of 2nd bucket. One dimension with one bucket.
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 1);
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ // Validate dimension value.
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 111);
+ // The max is acquire event for wl1 to screen off start.
+ EXPECT_EQ((unsigned long long)data.bucket_info(0).duration_nanos(), bucketSizeNs + 2 - 200);
+}
+
+TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensionsForMaxDuration3) {
+ ConfigKey cfgKey;
+ auto config = CreateStatsdConfig(DurationMetric::MAX_SPARSE);
+ uint64_t bucketStartTimeNs = 10000000000;
+ uint64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ FeedEvents(config, processor);
+ ConfigMetricsReportList reports;
+ vector<uint8_t> buffer;
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(
+ CreateScreenStateChangedEvent(bucketStartTimeNs + 2 * bucketSizeNs + 90,
+ android::view::DisplayStateEnum::DISPLAY_STATE_OFF));
+ events.push_back(CreateAcquireWakelockEvent(bucketStartTimeNs + 2 * bucketSizeNs + 100,
+ attributionUids1, attributionTags1, "wl3"));
+ events.push_back(CreateReleaseWakelockEvent(bucketStartTimeNs + 5 * bucketSizeNs + 100,
+ attributionUids1, attributionTags1, "wl3"));
+ sortLogEventsByTimestamp(&events);
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 6 * bucketSizeNs + 1, false, true, ADB_DUMP,
+ FAST, &buffer);
+ EXPECT_TRUE(buffer.size() > 0);
+ EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+ backfillDimensionPath(&reports);
+ backfillStringInReport(&reports);
+ backfillStartEndTimestamp(&reports);
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics(0).duration_metrics().data(0).bucket_info_size(), 2);
+ auto data = reports.reports(0).metrics(0).duration_metrics().data(0);
+ ValidateAttributionUidDimension(data.dimensions_in_what(),
+ android::util::WAKELOCK_STATE_CHANGED, 111);
+ // The last wakelock holding spans 4 buckets.
+ EXPECT_EQ((unsigned long long)data.bucket_info(1).duration_nanos(), 3 * bucketSizeNs);
+ EXPECT_EQ((unsigned long long)data.bucket_info(1).start_bucket_elapsed_nanos(),
+ bucketStartTimeNs + 5 * bucketSizeNs);
+ EXPECT_EQ((unsigned long long)data.bucket_info(1).end_bucket_elapsed_nanos(),
+ bucketStartTimeNs + 6 * bucketSizeNs);
+}
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/cmds/statsd/tests/external/StatsPuller_test.cpp b/cmds/statsd/tests/external/StatsPuller_test.cpp
index c0b4f43..e8200d5 100644
--- a/cmds/statsd/tests/external/StatsPuller_test.cpp
+++ b/cmds/statsd/tests/external/StatsPuller_test.cpp
@@ -15,11 +15,14 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <stdio.h>
+
#include <chrono>
#include <thread>
#include <vector>
+
#include "../metrics/metrics_test_helper.h"
#include "src/stats_log_util.h"
+#include "stats_event.h"
#include "tests/statsd_test_util.h"
#ifdef __ANDROID__
@@ -57,13 +60,22 @@
FakePuller puller;
-// TODO(b/149590301): Update this helper to use new socket schema.
-//shared_ptr<LogEvent> createSimpleEvent(int64_t eventTimeNs, int64_t value) {
-// shared_ptr<LogEvent> event = make_shared<LogEvent>(pullTagId, eventTimeNs);
-// event->write(value);
-// event->init();
-// return event;
-//}
+std::unique_ptr<LogEvent> createSimpleEvent(int64_t eventTimeNs, int64_t value) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, pullTagId);
+ AStatsEvent_overwriteTimestamp(statsEvent, eventTimeNs);
+
+ AStatsEvent_writeInt64(statsEvent, value);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
class StatsPullerTest : public ::testing::Test {
public:
@@ -80,149 +92,148 @@
} // Anonymous namespace.
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST_F(StatsPullerTest, PullSuccess) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-//
-// pullSuccess = true;
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_TRUE(puller.Pull(&dataHolder));
-// EXPECT_EQ(1, dataHolder.size());
-// EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
-// EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
-// EXPECT_EQ(1, dataHolder[0]->size());
-// EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
-//
-// sleep_for(std::chrono::seconds(1));
-//
-// pullData.clear();
-// pullData.push_back(createSimpleEvent(2222L, 44));
-//
-// pullSuccess = true;
-//
-// EXPECT_TRUE(puller.Pull(&dataHolder));
-// EXPECT_EQ(1, dataHolder.size());
-// EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
-// EXPECT_EQ(2222L, dataHolder[0]->GetElapsedTimestampNs());
-// EXPECT_EQ(1, dataHolder[0]->size());
-// EXPECT_EQ(44, dataHolder[0]->getValues()[0].mValue.int_value);
-//}
-//
-//TEST_F(StatsPullerTest, PullFailAfterSuccess) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-//
-// pullSuccess = true;
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_TRUE(puller.Pull(&dataHolder));
-// EXPECT_EQ(1, dataHolder.size());
-// EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
-// EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
-// EXPECT_EQ(1, dataHolder[0]->size());
-// EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
-//
-// sleep_for(std::chrono::seconds(1));
-//
-// pullData.clear();
-// pullData.push_back(createSimpleEvent(2222L, 44));
-//
-// pullSuccess = false;
-// dataHolder.clear();
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//
-// pullSuccess = true;
-// dataHolder.clear();
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//}
-//
-//// Test pull takes longer than timeout, 2nd pull happens shorter than cooldown
-//TEST_F(StatsPullerTest, PullTakeTooLongAndPullFast) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-// pullSuccess = true;
-// // timeout is 0.5
-// pullDelayNs = (long)(0.8 * NS_PER_SEC);
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//
-// pullData.clear();
-// pullData.push_back(createSimpleEvent(2222L, 44));
-//
-// pullSuccess = true;
-// dataHolder.clear();
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//}
-//
-//TEST_F(StatsPullerTest, PullFail) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-//
-// pullSuccess = false;
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//}
-//
-//TEST_F(StatsPullerTest, PullTakeTooLong) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-//
-// pullSuccess = true;
-// pullDelayNs = NS_PER_SEC;
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//}
-//
-//TEST_F(StatsPullerTest, PullTooFast) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-//
-// pullSuccess = true;
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_TRUE(puller.Pull(&dataHolder));
-// EXPECT_EQ(1, dataHolder.size());
-// EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
-// EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
-// EXPECT_EQ(1, dataHolder[0]->size());
-// EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
-//
-// pullData.clear();
-// pullData.push_back(createSimpleEvent(2222L, 44));
-//
-// pullSuccess = true;
-//
-// dataHolder.clear();
-// EXPECT_TRUE(puller.Pull(&dataHolder));
-// EXPECT_EQ(1, dataHolder.size());
-// EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
-// EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
-// EXPECT_EQ(1, dataHolder[0]->size());
-// EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
-//}
-//
-//TEST_F(StatsPullerTest, PullFailsAndTooFast) {
-// pullData.push_back(createSimpleEvent(1111L, 33));
-//
-// pullSuccess = false;
-//
-// vector<std::shared_ptr<LogEvent>> dataHolder;
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//
-// pullData.clear();
-// pullData.push_back(createSimpleEvent(2222L, 44));
-//
-// pullSuccess = true;
-//
-// EXPECT_FALSE(puller.Pull(&dataHolder));
-// EXPECT_EQ(0, dataHolder.size());
-//}
+TEST_F(StatsPullerTest, PullSuccess) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+
+ pullSuccess = true;
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_TRUE(puller.Pull(&dataHolder));
+ EXPECT_EQ(1, dataHolder.size());
+ EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
+ EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_EQ(1, dataHolder[0]->size());
+ EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
+
+ sleep_for(std::chrono::seconds(1));
+
+ pullData.clear();
+ pullData.push_back(createSimpleEvent(2222L, 44));
+
+ pullSuccess = true;
+
+ EXPECT_TRUE(puller.Pull(&dataHolder));
+ EXPECT_EQ(1, dataHolder.size());
+ EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
+ EXPECT_EQ(2222L, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_EQ(1, dataHolder[0]->size());
+ EXPECT_EQ(44, dataHolder[0]->getValues()[0].mValue.int_value);
+}
+
+TEST_F(StatsPullerTest, PullFailAfterSuccess) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+
+ pullSuccess = true;
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_TRUE(puller.Pull(&dataHolder));
+ EXPECT_EQ(1, dataHolder.size());
+ EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
+ EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_EQ(1, dataHolder[0]->size());
+ EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
+
+ sleep_for(std::chrono::seconds(1));
+
+ pullData.clear();
+ pullData.push_back(createSimpleEvent(2222L, 44));
+
+ pullSuccess = false;
+ dataHolder.clear();
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+
+ pullSuccess = true;
+ dataHolder.clear();
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+// Test pull takes longer than timeout, 2nd pull happens shorter than cooldown
+TEST_F(StatsPullerTest, PullTakeTooLongAndPullFast) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+ pullSuccess = true;
+ // timeout is 0.5
+ pullDelayNs = (long)(0.8 * NS_PER_SEC);
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+
+ pullData.clear();
+ pullData.push_back(createSimpleEvent(2222L, 44));
+
+ pullSuccess = true;
+ dataHolder.clear();
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+TEST_F(StatsPullerTest, PullFail) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+
+ pullSuccess = false;
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+TEST_F(StatsPullerTest, PullTakeTooLong) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+
+ pullSuccess = true;
+ pullDelayNs = NS_PER_SEC;
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+}
+
+TEST_F(StatsPullerTest, PullTooFast) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+
+ pullSuccess = true;
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_TRUE(puller.Pull(&dataHolder));
+ EXPECT_EQ(1, dataHolder.size());
+ EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
+ EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_EQ(1, dataHolder[0]->size());
+ EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
+
+ pullData.clear();
+ pullData.push_back(createSimpleEvent(2222L, 44));
+
+ pullSuccess = true;
+
+ dataHolder.clear();
+ EXPECT_TRUE(puller.Pull(&dataHolder));
+ EXPECT_EQ(1, dataHolder.size());
+ EXPECT_EQ(pullTagId, dataHolder[0]->GetTagId());
+ EXPECT_EQ(1111L, dataHolder[0]->GetElapsedTimestampNs());
+ EXPECT_EQ(1, dataHolder[0]->size());
+ EXPECT_EQ(33, dataHolder[0]->getValues()[0].mValue.int_value);
+}
+
+TEST_F(StatsPullerTest, PullFailsAndTooFast) {
+ pullData.push_back(createSimpleEvent(1111L, 33));
+
+ pullSuccess = false;
+
+ vector<std::shared_ptr<LogEvent>> dataHolder;
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+
+ pullData.clear();
+ pullData.push_back(createSimpleEvent(2222L, 44));
+
+ pullSuccess = true;
+
+ EXPECT_FALSE(puller.Pull(&dataHolder));
+ EXPECT_EQ(0, dataHolder.size());
+}
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/tests/external/puller_util_test.cpp b/cmds/statsd/tests/external/puller_util_test.cpp
index 81590a2..f21954f2 100644
--- a/cmds/statsd/tests/external/puller_util_test.cpp
+++ b/cmds/statsd/tests/external/puller_util_test.cpp
@@ -13,12 +13,16 @@
// limitations under the License.
#include "external/puller_util.h"
+
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <stdio.h>
+
#include <vector>
-#include "statslog.h"
+
#include "../metrics/metrics_test_helper.h"
+#include "stats_event.h"
+#include "statslog.h"
#ifdef __ANDROID__
@@ -58,212 +62,187 @@
ret.push_back(vec);
}
}
+
+std::shared_ptr<LogEvent> makeUidLogEvent(uint64_t timestampNs, int uid, int data1, int data2) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, uidAtomTagId);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, uid);
+ AStatsEvent_writeInt32(statsEvent, data1);
+ AStatsEvent_writeInt32(statsEvent, data2);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::shared_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::shared_ptr<LogEvent> makeNonUidAtomLogEvent(uint64_t timestampNs, int data1) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, nonUidAtomTagId);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, data1);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::shared_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
} // anonymous namespace
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(puller_util, MergeNoDimension) {
-// vector<shared_ptr<LogEvent>> inputData;
-// shared_ptr<LogEvent> event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// // 30->22->31
-// event->write(isolatedUid);
-// event->write(hostNonAdditiveData);
-// event->write(isolatedAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 20->22->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(hostUid);
-// event->write(hostNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid))
-// .WillRepeatedly(Return(hostUid));
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid)))
-// .WillRepeatedly(ReturnArg<0>());
-// mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
-//
-// vector<vector<int>> actual;
-// extractIntoVector(inputData, actual);
-// vector<int> expectedV1 = {20, 22, 52};
-// EXPECT_EQ(1, (int)actual.size());
-// EXPECT_THAT(actual, Contains(expectedV1));
-//}
-//
-//TEST(puller_util, MergeWithDimension) {
-// vector<shared_ptr<LogEvent>> inputData;
-// shared_ptr<LogEvent> event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// // 30->32->31
-// event->write(isolatedUid);
-// event->write(isolatedNonAdditiveData);
-// event->write(isolatedAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 20->32->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(hostUid);
-// event->write(isolatedNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 20->22->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(hostUid);
-// event->write(hostNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid))
-// .WillRepeatedly(Return(hostUid));
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid)))
-// .WillRepeatedly(ReturnArg<0>());
-// mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
-//
-// vector<vector<int>> actual;
-// extractIntoVector(inputData, actual);
-// vector<int> expectedV1 = {20, 22, 21};
-// vector<int> expectedV2 = {20, 32, 52};
-// EXPECT_EQ(2, (int)actual.size());
-// EXPECT_THAT(actual, Contains(expectedV1));
-// EXPECT_THAT(actual, Contains(expectedV2));
-//}
-//
-//TEST(puller_util, NoMergeHostUidOnly) {
-// vector<shared_ptr<LogEvent>> inputData;
-// shared_ptr<LogEvent> event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// // 20->32->31
-// event->write(hostUid);
-// event->write(isolatedNonAdditiveData);
-// event->write(isolatedAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 20->22->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(hostUid);
-// event->write(hostNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid))
-// .WillRepeatedly(Return(hostUid));
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid)))
-// .WillRepeatedly(ReturnArg<0>());
-// mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
-//
-// // 20->32->31
-// // 20->22->21
-// vector<vector<int>> actual;
-// extractIntoVector(inputData, actual);
-// vector<int> expectedV1 = {20, 32, 31};
-// vector<int> expectedV2 = {20, 22, 21};
-// EXPECT_EQ(2, (int)actual.size());
-// EXPECT_THAT(actual, Contains(expectedV1));
-// EXPECT_THAT(actual, Contains(expectedV2));
-//}
-//
-//TEST(puller_util, IsolatedUidOnly) {
-// vector<shared_ptr<LogEvent>> inputData;
-// shared_ptr<LogEvent> event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// // 30->32->31
-// event->write(hostUid);
-// event->write(isolatedNonAdditiveData);
-// event->write(isolatedAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 30->22->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(hostUid);
-// event->write(hostNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid))
-// .WillRepeatedly(Return(hostUid));
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid)))
-// .WillRepeatedly(ReturnArg<0>());
-// mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
-//
-// // 20->32->31
-// // 20->22->21
-// vector<vector<int>> actual;
-// extractIntoVector(inputData, actual);
-// vector<int> expectedV1 = {20, 32, 31};
-// vector<int> expectedV2 = {20, 22, 21};
-// EXPECT_EQ(2, (int)actual.size());
-// EXPECT_THAT(actual, Contains(expectedV1));
-// EXPECT_THAT(actual, Contains(expectedV2));
-//}
-//
-//TEST(puller_util, MultipleIsolatedUidToOneHostUid) {
-// vector<shared_ptr<LogEvent>> inputData;
-// shared_ptr<LogEvent> event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// // 30->32->31
-// event->write(isolatedUid);
-// event->write(isolatedNonAdditiveData);
-// event->write(isolatedAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 31->32->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(isolatedUid + 1);
-// event->write(isolatedNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// // 20->32->21
-// event = make_shared<LogEvent>(uidAtomTagId, timestamp);
-// event->write(hostUid);
-// event->write(isolatedNonAdditiveData);
-// event->write(hostAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
-// EXPECT_CALL(*uidMap, getHostUidOrSelf(_)).WillRepeatedly(Return(hostUid));
-// mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
-//
-// vector<vector<int>> actual;
-// extractIntoVector(inputData, actual);
-// vector<int> expectedV1 = {20, 32, 73};
-// EXPECT_EQ(1, (int)actual.size());
-// EXPECT_THAT(actual, Contains(expectedV1));
-//}
-//
-//TEST(puller_util, NoNeedToMerge) {
-// vector<shared_ptr<LogEvent>> inputData;
-// shared_ptr<LogEvent> event =
-// make_shared<LogEvent>(nonUidAtomTagId, timestamp);
-// // 32
-// event->write(isolatedNonAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// event = make_shared<LogEvent>(nonUidAtomTagId, timestamp);
-// // 22
-// event->write(hostNonAdditiveData);
-// event->init();
-// inputData.push_back(event);
-//
-// sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
-// mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, nonUidAtomTagId, {} /*no additive fields*/);
-//
-// EXPECT_EQ(2, (int)inputData.size());
-//}
+TEST(puller_util, MergeNoDimension) {
+ vector<shared_ptr<LogEvent>> inputData;
+
+ // 30->22->31
+ inputData.push_back(
+ makeUidLogEvent(timestamp, isolatedUid, hostNonAdditiveData, isolatedAdditiveData));
+
+ // 20->22->21
+ inputData.push_back(makeUidLogEvent(timestamp, hostUid, hostNonAdditiveData, hostAdditiveData));
+
+ sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid)).WillRepeatedly(Return(hostUid));
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid))).WillRepeatedly(ReturnArg<0>());
+ mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
+
+ vector<vector<int>> actual;
+ extractIntoVector(inputData, actual);
+ vector<int> expectedV1 = {20, 22, 52};
+ EXPECT_EQ(1, (int)actual.size());
+ EXPECT_THAT(actual, Contains(expectedV1));
+}
+
+TEST(puller_util, MergeWithDimension) {
+ vector<shared_ptr<LogEvent>> inputData;
+
+ // 30->32->31
+ inputData.push_back(
+ makeUidLogEvent(timestamp, isolatedUid, isolatedNonAdditiveData, isolatedAdditiveData));
+
+ // 20->32->21
+ inputData.push_back(
+ makeUidLogEvent(timestamp, hostUid, isolatedNonAdditiveData, hostAdditiveData));
+
+ // 20->22->21
+ inputData.push_back(makeUidLogEvent(timestamp, hostUid, hostNonAdditiveData, hostAdditiveData));
+
+ sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid)).WillRepeatedly(Return(hostUid));
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid))).WillRepeatedly(ReturnArg<0>());
+ mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
+
+ vector<vector<int>> actual;
+ extractIntoVector(inputData, actual);
+ vector<int> expectedV1 = {20, 22, 21};
+ vector<int> expectedV2 = {20, 32, 52};
+ EXPECT_EQ(2, (int)actual.size());
+ EXPECT_THAT(actual, Contains(expectedV1));
+ EXPECT_THAT(actual, Contains(expectedV2));
+}
+
+TEST(puller_util, NoMergeHostUidOnly) {
+ vector<shared_ptr<LogEvent>> inputData;
+
+ // 20->32->31
+ inputData.push_back(
+ makeUidLogEvent(timestamp, hostUid, isolatedNonAdditiveData, isolatedAdditiveData));
+
+ // 20->22->21
+ inputData.push_back(makeUidLogEvent(timestamp, hostUid, hostNonAdditiveData, hostAdditiveData));
+
+ sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid)).WillRepeatedly(Return(hostUid));
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid))).WillRepeatedly(ReturnArg<0>());
+ mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
+
+ // 20->32->31
+ // 20->22->21
+ vector<vector<int>> actual;
+ extractIntoVector(inputData, actual);
+ vector<int> expectedV1 = {20, 32, 31};
+ vector<int> expectedV2 = {20, 22, 21};
+ EXPECT_EQ(2, (int)actual.size());
+ EXPECT_THAT(actual, Contains(expectedV1));
+ EXPECT_THAT(actual, Contains(expectedV2));
+}
+
+TEST(puller_util, IsolatedUidOnly) {
+ vector<shared_ptr<LogEvent>> inputData;
+
+ // 30->32->31
+ inputData.push_back(
+ makeUidLogEvent(timestamp, hostUid, isolatedNonAdditiveData, isolatedAdditiveData));
+
+ // 30->22->21
+ inputData.push_back(makeUidLogEvent(timestamp, hostUid, hostNonAdditiveData, hostAdditiveData));
+
+ sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(isolatedUid)).WillRepeatedly(Return(hostUid));
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(Ne(isolatedUid))).WillRepeatedly(ReturnArg<0>());
+ mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
+
+ // 20->32->31
+ // 20->22->21
+ vector<vector<int>> actual;
+ extractIntoVector(inputData, actual);
+ vector<int> expectedV1 = {20, 32, 31};
+ vector<int> expectedV2 = {20, 22, 21};
+ EXPECT_EQ(2, (int)actual.size());
+ EXPECT_THAT(actual, Contains(expectedV1));
+ EXPECT_THAT(actual, Contains(expectedV2));
+}
+
+TEST(puller_util, MultipleIsolatedUidToOneHostUid) {
+ vector<shared_ptr<LogEvent>> inputData;
+
+ // 30->32->31
+ inputData.push_back(
+ makeUidLogEvent(timestamp, isolatedUid, isolatedNonAdditiveData, isolatedAdditiveData));
+
+ // 31->32->21
+ inputData.push_back(
+ makeUidLogEvent(timestamp, isolatedUid + 1, isolatedNonAdditiveData, hostAdditiveData));
+
+ // 20->32->21
+ inputData.push_back(
+ makeUidLogEvent(timestamp, hostUid, isolatedNonAdditiveData, hostAdditiveData));
+
+ sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
+ EXPECT_CALL(*uidMap, getHostUidOrSelf(_)).WillRepeatedly(Return(hostUid));
+ mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, uidAtomTagId, uidAdditiveFields);
+
+ vector<vector<int>> actual;
+ extractIntoVector(inputData, actual);
+ vector<int> expectedV1 = {20, 32, 73};
+ EXPECT_EQ(1, (int)actual.size());
+ EXPECT_THAT(actual, Contains(expectedV1));
+}
+
+TEST(puller_util, NoNeedToMerge) {
+ vector<shared_ptr<LogEvent>> inputData;
+
+ // 32
+ inputData.push_back(makeNonUidAtomLogEvent(timestamp, isolatedNonAdditiveData));
+
+ // 22
+ inputData.push_back(makeNonUidAtomLogEvent(timestamp, hostNonAdditiveData));
+
+ sp<MockUidMap> uidMap = new NaggyMock<MockUidMap>();
+ mapAndMergeIsolatedUidsToHostUid(inputData, uidMap, nonUidAtomTagId, {} /*no additive fields*/);
+
+ EXPECT_EQ(2, (int)inputData.size());
+}
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/tests/log_event/LogEventQueue_test.cpp b/cmds/statsd/tests/log_event/LogEventQueue_test.cpp
index c4407f4..6dc041f 100644
--- a/cmds/statsd/tests/log_event/LogEventQueue_test.cpp
+++ b/cmds/statsd/tests/log_event/LogEventQueue_test.cpp
@@ -42,7 +42,7 @@
size_t size;
uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
- std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/-1, /*pid=*/-1);
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
logEvent->parseBuffer(buf, size);
AStatsEvent_release(statsEvent);
return logEvent;
diff --git a/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp b/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
index b882678..d55996c 100644
--- a/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
@@ -13,16 +13,19 @@
// limitations under the License.
#include "src/metrics/CountMetricProducer.h"
-#include "src/stats_log_util.h"
-#include "metrics_test_helper.h"
-#include "tests/statsd_test_util.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <math.h>
#include <stdio.h>
+
#include <vector>
+#include "metrics_test_helper.h"
+#include "src/stats_log_util.h"
+#include "stats_event.h"
+#include "tests/statsd_test_util.h"
+
using namespace testing;
using android::sp;
using std::set;
@@ -37,366 +40,392 @@
const ConfigKey kConfigKey(0, 12345);
-// TODO(b/149590301): Update these tests to use new socket schema.
-//TEST(CountMetricProducerTest, TestFirstBucket) {
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-//
-// CountMetricProducer countProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, 5,
-// 600 * NS_PER_SEC + NS_PER_SEC / 2);
-// EXPECT_EQ(600500000000, countProducer.mCurrentBucketStartTimeNs);
-// EXPECT_EQ(10, countProducer.mCurrentBucketNum);
-// EXPECT_EQ(660000000005, countProducer.getCurrentBucketEndTimeNs());
-//}
-//
-//TEST(CountMetricProducerTest, TestNonDimensionalEvents) {
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t bucket2StartTimeNs = bucketStartTimeNs + bucketSizeNs;
-// int64_t bucket3StartTimeNs = bucketStartTimeNs + 2 * bucketSizeNs;
-// int tagId = 1;
-//
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-//
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.init();
-// LogEvent event2(tagId, bucketStartTimeNs + 2);
-// event2.init();
-//
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-//
-// CountMetricProducer countProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
-// bucketStartTimeNs, bucketStartTimeNs);
-//
-// // 2 events in bucket 1.
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
-//
-// // Flushes at event #2.
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + 2);
-// EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
-//
-// // Flushes.
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
-// EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// countProducer.mPastBuckets.end());
-// const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets.size());
-// EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
-// EXPECT_EQ(2LL, buckets[0].mCount);
-//
-// // 1 matched event happens in bucket 2.
-// LogEvent event3(tagId, bucketStartTimeNs + bucketSizeNs + 2);
-// event3.init();
-//
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
-// EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// countProducer.mPastBuckets.end());
-// EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// const auto& bucketInfo2 = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1];
-// EXPECT_EQ(bucket2StartTimeNs, bucketInfo2.mBucketStartNs);
-// EXPECT_EQ(bucket2StartTimeNs + bucketSizeNs, bucketInfo2.mBucketEndNs);
-// EXPECT_EQ(1LL, bucketInfo2.mCount);
-//
-// // nothing happens in bucket 3. we should not record anything for bucket 3.
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + 3 * bucketSizeNs + 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
-// EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// countProducer.mPastBuckets.end());
-// const auto& buckets3 = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(2UL, buckets3.size());
-//}
-//
-//TEST(CountMetricProducerTest, TestEventsWithNonSlicedCondition) {
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-//
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_condition(StringToId("SCREEN_ON"));
-//
-// LogEvent event1(1, bucketStartTimeNs + 1);
-// event1.init();
-//
-// LogEvent event2(1, bucketStartTimeNs + 10);
-// event2.init();
-//
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-//
-// CountMetricProducer countProducer(kConfigKey, metric, 1, wizard, bucketStartTimeNs,
-// bucketStartTimeNs);
-//
-// countProducer.onConditionChanged(true, bucketStartTimeNs);
-// countProducer.onMatchedLogEvent(1 /*matcher index*/, event1);
-// EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
-//
-// countProducer.onConditionChanged(false /*new condition*/, bucketStartTimeNs + 2);
-// // Upon this match event, the matched event1 is flushed.
-// countProducer.onMatchedLogEvent(1 /*matcher index*/, event2);
-// EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
-//
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
-// EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// countProducer.mPastBuckets.end());
-// {
-// const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets.size());
-// const auto& bucketInfo = buckets[0];
-// EXPECT_EQ(bucketStartTimeNs, bucketInfo.mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.mBucketEndNs);
-// EXPECT_EQ(1LL, bucketInfo.mCount);
-// }
-//}
-//
-//TEST(CountMetricProducerTest, TestEventsWithSlicedCondition) {
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-//
-// int tagId = 1;
-// int conditionTagId = 2;
-//
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_condition(StringToId("APP_IN_BACKGROUND_PER_UID_AND_SCREEN_ON"));
-// MetricConditionLink* link = metric.add_links();
-// link->set_condition(StringToId("APP_IN_BACKGROUND_PER_UID"));
-// buildSimpleAtomFieldMatcher(tagId, 1, link->mutable_fields_in_what());
-// buildSimpleAtomFieldMatcher(conditionTagId, 2, link->mutable_fields_in_condition());
-//
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.write("111"); // uid
-// event1.init();
-// ConditionKey key1;
-// key1[StringToId("APP_IN_BACKGROUND_PER_UID")] =
-// {getMockedDimensionKey(conditionTagId, 2, "111")};
-//
-// LogEvent event2(tagId, bucketStartTimeNs + 10);
-// event2.write("222"); // uid
-// event2.init();
-// ConditionKey key2;
-// key2[StringToId("APP_IN_BACKGROUND_PER_UID")] =
-// {getMockedDimensionKey(conditionTagId, 2, "222")};
-//
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// EXPECT_CALL(*wizard, query(_, key1, _)).WillOnce(Return(ConditionState::kFalse));
-//
-// EXPECT_CALL(*wizard, query(_, key2, _)).WillOnce(Return(ConditionState::kTrue));
-//
-// CountMetricProducer countProducer(kConfigKey, metric, 1 /*condition tracker index*/, wizard,
-// bucketStartTimeNs, bucketStartTimeNs);
-//
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + 1);
-// EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
-//
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
-// countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
-// EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// countProducer.mPastBuckets.end());
-// const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets.size());
-// const auto& bucketInfo = buckets[0];
-// EXPECT_EQ(bucketStartTimeNs, bucketInfo.mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.mBucketEndNs);
-// EXPECT_EQ(1LL, bucketInfo.mCount);
-//}
-//
-//TEST(CountMetricProducerTest, TestEventWithAppUpgrade) {
-// sp<AlarmMonitor> alarmMonitor;
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
-//
-// int tagId = 1;
-// int conditionTagId = 2;
-//
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// Alert alert;
-// alert.set_num_buckets(3);
-// alert.set_trigger_if_sum_gt(2);
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.write("111"); // uid
-// event1.init();
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// CountMetricProducer countProducer(kConfigKey, metric, -1 /* no condition */, wizard,
-// bucketStartTimeNs, bucketStartTimeNs);
-//
-// sp<AnomalyTracker> anomalyTracker = countProducer.addAnomalyTracker(alert, alarmMonitor);
-// EXPECT_TRUE(anomalyTracker != nullptr);
-//
-// // Bucket is flushed yet.
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
-// EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
-// EXPECT_EQ(0, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
-//
-// // App upgrade forces bucket flush.
-// // Check that there's a past bucket and the bucket end is not adjusted.
-// countProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ((long long)bucketStartTimeNs,
-// countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketStartNs);
-// EXPECT_EQ((long long)eventUpgradeTimeNs,
-// countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketEndNs);
-// EXPECT_EQ(eventUpgradeTimeNs, countProducer.mCurrentBucketStartTimeNs);
-// // Anomaly tracker only contains full buckets.
-// EXPECT_EQ(0, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
-//
-// int64_t lastEndTimeNs = countProducer.getCurrentBucketEndTimeNs();
-// // Next event occurs in same bucket as partial bucket created.
-// LogEvent event2(tagId, bucketStartTimeNs + 59 * NS_PER_SEC + 10);
-// event2.write("222"); // uid
-// event2.init();
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ(eventUpgradeTimeNs, countProducer.mCurrentBucketStartTimeNs);
-// EXPECT_EQ(0, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
-//
-// // Third event in following bucket.
-// LogEvent event3(tagId, bucketStartTimeNs + 62 * NS_PER_SEC + 10);
-// event3.write("333"); // uid
-// event3.init();
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
-// EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ(lastEndTimeNs, countProducer.mCurrentBucketStartTimeNs);
-// EXPECT_EQ(2, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
-//}
-//
-//TEST(CountMetricProducerTest, TestEventWithAppUpgradeInNextBucket) {
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 65 * NS_PER_SEC;
-//
-// int tagId = 1;
-// int conditionTagId = 2;
-//
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.write("111"); // uid
-// event1.init();
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// CountMetricProducer countProducer(kConfigKey, metric, -1 /* no condition */, wizard,
-// bucketStartTimeNs, bucketStartTimeNs);
-//
-// // Bucket is flushed yet.
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
-// EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
-//
-// // App upgrade forces bucket flush.
-// // Check that there's a past bucket and the bucket end is not adjusted.
-// countProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ((int64_t)bucketStartTimeNs,
-// countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
-// countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketEndNs);
-// EXPECT_EQ(eventUpgradeTimeNs, countProducer.mCurrentBucketStartTimeNs);
-//
-// // Next event occurs in same bucket as partial bucket created.
-// LogEvent event2(tagId, bucketStartTimeNs + 70 * NS_PER_SEC + 10);
-// event2.write("222"); // uid
-// event2.init();
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
-// EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-//
-// // Third event in following bucket.
-// LogEvent event3(tagId, bucketStartTimeNs + 121 * NS_PER_SEC + 10);
-// event3.write("333"); // uid
-// event3.init();
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
-// EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ((int64_t)eventUpgradeTimeNs,
-// countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
-// countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1].mBucketEndNs);
-//}
-//
-//TEST(CountMetricProducerTest, TestAnomalyDetectionUnSliced) {
-// sp<AlarmMonitor> alarmMonitor;
-// Alert alert;
-// alert.set_id(11);
-// alert.set_metric_id(1);
-// alert.set_trigger_if_sum_gt(2);
-// alert.set_num_buckets(2);
-// const int32_t refPeriodSec = 1;
-// alert.set_refractory_period_secs(refPeriodSec);
-//
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t bucket2StartTimeNs = bucketStartTimeNs + bucketSizeNs;
-// int64_t bucket3StartTimeNs = bucketStartTimeNs + 2 * bucketSizeNs;
-//
-// CountMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-//
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// CountMetricProducer countProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
-// bucketStartTimeNs, bucketStartTimeNs);
-//
-// sp<AnomalyTracker> anomalyTracker = countProducer.addAnomalyTracker(alert, alarmMonitor);
-//
-// int tagId = 1;
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.init();
-// LogEvent event2(tagId, bucketStartTimeNs + 2);
-// event2.init();
-// LogEvent event3(tagId, bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// event3.init();
-// LogEvent event4(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 1);
-// event4.init();
-// LogEvent event5(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 2);
-// event5.init();
-// LogEvent event6(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 3);
-// event6.init();
-// LogEvent event7(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 2 * NS_PER_SEC);
-// event7.init();
-//
-// // Two events in bucket #0.
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
-//
-// EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
-// EXPECT_EQ(2L, countProducer.mCurrentSlicedCounter->begin()->second);
-// EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
-//
-// // One event in bucket #2. No alarm as bucket #0 is trashed out.
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
-// EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
-// EXPECT_EQ(1L, countProducer.mCurrentSlicedCounter->begin()->second);
-// EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
-//
-// // Two events in bucket #3.
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event4);
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event5);
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event6);
-// EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
-// EXPECT_EQ(3L, countProducer.mCurrentSlicedCounter->begin()->second);
-// // Anomaly at event 6 is within refractory period. The alarm is at event 5 timestamp not event 6
-// EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
-// std::ceil(1.0 * event5.GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec));
-//
-// countProducer.onMatchedLogEvent(1 /*log matcher index*/, event7);
-// EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
-// EXPECT_EQ(4L, countProducer.mCurrentSlicedCounter->begin()->second);
-// EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
-// std::ceil(1.0 * event7.GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec));
-//}
+namespace {
+
+void makeLogEvent(LogEvent* logEvent, int64_t timestampNs, int atomId) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, atomId);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+}
+
+void makeLogEvent(LogEvent* logEvent, int64_t timestampNs, int atomId, string uid) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, atomId);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeString(statsEvent, uid.c_str());
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+}
+
+} // namespace
+
+TEST(CountMetricProducerTest, TestFirstBucket) {
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+
+ CountMetricProducer countProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, 5,
+ 600 * NS_PER_SEC + NS_PER_SEC / 2);
+ EXPECT_EQ(600500000000, countProducer.mCurrentBucketStartTimeNs);
+ EXPECT_EQ(10, countProducer.mCurrentBucketNum);
+ EXPECT_EQ(660000000005, countProducer.getCurrentBucketEndTimeNs());
+}
+
+TEST(CountMetricProducerTest, TestNonDimensionalEvents) {
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t bucket2StartTimeNs = bucketStartTimeNs + bucketSizeNs;
+ int64_t bucket3StartTimeNs = bucketStartTimeNs + 2 * bucketSizeNs;
+ int tagId = 1;
+
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+
+ CountMetricProducer countProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
+ bucketStartTimeNs, bucketStartTimeNs);
+
+ // 2 events in bucket 1.
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 2, tagId);
+
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
+
+ // Flushes at event #2.
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + 2);
+ EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
+
+ // Flushes.
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ countProducer.mPastBuckets.end());
+ const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets.size());
+ EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
+ EXPECT_EQ(2LL, buckets[0].mCount);
+
+ // 1 matched event happens in bucket 2.
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event3, bucketStartTimeNs + bucketSizeNs + 2, tagId);
+
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
+
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ countProducer.mPastBuckets.end());
+ EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ const auto& bucketInfo2 = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1];
+ EXPECT_EQ(bucket2StartTimeNs, bucketInfo2.mBucketStartNs);
+ EXPECT_EQ(bucket2StartTimeNs + bucketSizeNs, bucketInfo2.mBucketEndNs);
+ EXPECT_EQ(1LL, bucketInfo2.mCount);
+
+ // nothing happens in bucket 3. we should not record anything for bucket 3.
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + 3 * bucketSizeNs + 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ countProducer.mPastBuckets.end());
+ const auto& buckets3 = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(2UL, buckets3.size());
+}
+
+TEST(CountMetricProducerTest, TestEventsWithNonSlicedCondition) {
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_condition(StringToId("SCREEN_ON"));
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+
+ CountMetricProducer countProducer(kConfigKey, metric, 1, wizard, bucketStartTimeNs,
+ bucketStartTimeNs);
+
+ countProducer.onConditionChanged(true, bucketStartTimeNs);
+
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, /*atomId=*/1);
+ countProducer.onMatchedLogEvent(1 /*matcher index*/, event1);
+
+ EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
+
+ countProducer.onConditionChanged(false /*new condition*/, bucketStartTimeNs + 2);
+
+ // Upon this match event, the matched event1 is flushed.
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 10, /*atomId=*/1);
+ countProducer.onMatchedLogEvent(1 /*matcher index*/, event2);
+ EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
+
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ countProducer.mPastBuckets.end());
+
+ const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets.size());
+ const auto& bucketInfo = buckets[0];
+ EXPECT_EQ(bucketStartTimeNs, bucketInfo.mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.mBucketEndNs);
+ EXPECT_EQ(1LL, bucketInfo.mCount);
+}
+
+TEST(CountMetricProducerTest, TestEventsWithSlicedCondition) {
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+
+ int tagId = 1;
+ int conditionTagId = 2;
+
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_condition(StringToId("APP_IN_BACKGROUND_PER_UID_AND_SCREEN_ON"));
+ MetricConditionLink* link = metric.add_links();
+ link->set_condition(StringToId("APP_IN_BACKGROUND_PER_UID"));
+ buildSimpleAtomFieldMatcher(tagId, 1, link->mutable_fields_in_what());
+ buildSimpleAtomFieldMatcher(conditionTagId, 2, link->mutable_fields_in_condition());
+
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId, /*uid=*/"111");
+
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 10, tagId, /*uid=*/"222");
+
+ ConditionKey key1;
+ key1[StringToId("APP_IN_BACKGROUND_PER_UID")] = {
+ getMockedDimensionKey(conditionTagId, 2, "111")};
+
+ ConditionKey key2;
+ key2[StringToId("APP_IN_BACKGROUND_PER_UID")] = {
+ getMockedDimensionKey(conditionTagId, 2, "222")};
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ EXPECT_CALL(*wizard, query(_, key1, _)).WillOnce(Return(ConditionState::kFalse));
+
+ EXPECT_CALL(*wizard, query(_, key2, _)).WillOnce(Return(ConditionState::kTrue));
+
+ CountMetricProducer countProducer(kConfigKey, metric, 1 /*condition tracker index*/, wizard,
+ bucketStartTimeNs, bucketStartTimeNs);
+
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + 1);
+ EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
+
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
+ countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ countProducer.mPastBuckets.end());
+ const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets.size());
+ const auto& bucketInfo = buckets[0];
+ EXPECT_EQ(bucketStartTimeNs, bucketInfo.mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, bucketInfo.mBucketEndNs);
+ EXPECT_EQ(1LL, bucketInfo.mCount);
+}
+
+TEST(CountMetricProducerTest, TestEventWithAppUpgrade) {
+ sp<AlarmMonitor> alarmMonitor;
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
+
+ int tagId = 1;
+ int conditionTagId = 2;
+
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ Alert alert;
+ alert.set_num_buckets(3);
+ alert.set_trigger_if_sum_gt(2);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ CountMetricProducer countProducer(kConfigKey, metric, -1 /* no condition */, wizard,
+ bucketStartTimeNs, bucketStartTimeNs);
+
+ sp<AnomalyTracker> anomalyTracker = countProducer.addAnomalyTracker(alert, alarmMonitor);
+ EXPECT_TRUE(anomalyTracker != nullptr);
+
+ // Bucket is flushed yet.
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId, /*uid=*/"111");
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
+ EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
+ EXPECT_EQ(0, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
+
+ // App upgrade forces bucket flush.
+ // Check that there's a past bucket and the bucket end is not adjusted.
+ countProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ((long long)bucketStartTimeNs,
+ countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketStartNs);
+ EXPECT_EQ((long long)eventUpgradeTimeNs,
+ countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketEndNs);
+ EXPECT_EQ(eventUpgradeTimeNs, countProducer.mCurrentBucketStartTimeNs);
+ // Anomaly tracker only contains full buckets.
+ EXPECT_EQ(0, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
+
+ int64_t lastEndTimeNs = countProducer.getCurrentBucketEndTimeNs();
+ // Next event occurs in same bucket as partial bucket created.
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 59 * NS_PER_SEC + 10, tagId, /*uid=*/"222");
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ(eventUpgradeTimeNs, countProducer.mCurrentBucketStartTimeNs);
+ EXPECT_EQ(0, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
+
+ // Third event in following bucket.
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event3, bucketStartTimeNs + 62 * NS_PER_SEC + 10, tagId, /*uid=*/"333");
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
+ EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ(lastEndTimeNs, countProducer.mCurrentBucketStartTimeNs);
+ EXPECT_EQ(2, anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
+}
+
+TEST(CountMetricProducerTest, TestEventWithAppUpgradeInNextBucket) {
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 65 * NS_PER_SEC;
+
+ int tagId = 1;
+ int conditionTagId = 2;
+
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ CountMetricProducer countProducer(kConfigKey, metric, -1 /* no condition */, wizard,
+ bucketStartTimeNs, bucketStartTimeNs);
+
+ // Bucket is flushed yet.
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId, /*uid=*/"111");
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
+ EXPECT_EQ(0UL, countProducer.mPastBuckets.size());
+
+ // App upgrade forces bucket flush.
+ // Check that there's a past bucket and the bucket end is not adjusted.
+ countProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ((int64_t)bucketStartTimeNs,
+ countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs,
+ countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketEndNs);
+ EXPECT_EQ(eventUpgradeTimeNs, countProducer.mCurrentBucketStartTimeNs);
+
+ // Next event occurs in same bucket as partial bucket created.
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 70 * NS_PER_SEC + 10, tagId, /*uid=*/"222");
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
+ EXPECT_EQ(1UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+
+ // Third event in following bucket.
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event3, bucketStartTimeNs + 121 * NS_PER_SEC + 10, tagId, /*uid=*/"333");
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
+ EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ((int64_t)eventUpgradeTimeNs,
+ countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+ countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1].mBucketEndNs);
+}
+
+TEST(CountMetricProducerTest, TestAnomalyDetectionUnSliced) {
+ sp<AlarmMonitor> alarmMonitor;
+ Alert alert;
+ alert.set_id(11);
+ alert.set_metric_id(1);
+ alert.set_trigger_if_sum_gt(2);
+ alert.set_num_buckets(2);
+ const int32_t refPeriodSec = 1;
+ alert.set_refractory_period_secs(refPeriodSec);
+
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t bucket2StartTimeNs = bucketStartTimeNs + bucketSizeNs;
+ int64_t bucket3StartTimeNs = bucketStartTimeNs + 2 * bucketSizeNs;
+
+ CountMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ CountMetricProducer countProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard,
+ bucketStartTimeNs, bucketStartTimeNs);
+
+ sp<AnomalyTracker> anomalyTracker = countProducer.addAnomalyTracker(alert, alarmMonitor);
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 2, tagId);
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event3, bucketStartTimeNs + 2 * bucketSizeNs + 1, tagId);
+ LogEvent event4(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event4, bucketStartTimeNs + 3 * bucketSizeNs + 1, tagId);
+ LogEvent event5(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event5, bucketStartTimeNs + 3 * bucketSizeNs + 2, tagId);
+ LogEvent event6(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event6, bucketStartTimeNs + 3 * bucketSizeNs + 3, tagId);
+ LogEvent event7(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event7, bucketStartTimeNs + 3 * bucketSizeNs + 2 * NS_PER_SEC, tagId);
+
+ // Two events in bucket #0.
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event1);
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
+
+ EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
+ EXPECT_EQ(2L, countProducer.mCurrentSlicedCounter->begin()->second);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
+
+ // One event in bucket #2. No alarm as bucket #0 is trashed out.
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
+ EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
+ EXPECT_EQ(1L, countProducer.mCurrentSlicedCounter->begin()->second);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
+
+ // Two events in bucket #3.
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event4);
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event5);
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event6);
+ EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
+ EXPECT_EQ(3L, countProducer.mCurrentSlicedCounter->begin()->second);
+ // Anomaly at event 6 is within refractory period. The alarm is at event 5 timestamp not event 6
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
+ std::ceil(1.0 * event5.GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec));
+
+ countProducer.onMatchedLogEvent(1 /*log matcher index*/, event7);
+ EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
+ EXPECT_EQ(4L, countProducer.mCurrentSlicedCounter->begin()->second);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
+ std::ceil(1.0 * event7.GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec));
+}
TEST(CountMetricProducerTest, TestOneWeekTimeUnit) {
CountMetric metric;
diff --git a/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp b/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp
index 6661374..6143dc0 100644
--- a/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp
@@ -13,17 +13,20 @@
// limitations under the License.
#include "src/metrics/DurationMetricProducer.h"
-#include "src/stats_log_util.h"
-#include "metrics_test_helper.h"
-#include "src/condition/ConditionWizard.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <stdio.h>
+
#include <set>
#include <unordered_map>
#include <vector>
+#include "metrics_test_helper.h"
+#include "src/condition/ConditionWizard.h"
+#include "src/stats_log_util.h"
+#include "stats_event.h"
+
using namespace android::os::statsd;
using namespace testing;
using android::sp;
@@ -39,6 +42,22 @@
const ConfigKey kConfigKey(0, 12345);
+namespace {
+
+void makeLogEvent(LogEvent* logEvent, int64_t timestampNs, int atomId) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, atomId);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+}
+
+} // namespace
+
TEST(DurationMetricTrackerTest, TestFirstBucket) {
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
DurationMetric metric;
@@ -56,383 +75,386 @@
EXPECT_EQ(660000000005, durationProducer.getCurrentBucketEndTimeNs());
}
-// TODO(b/149590301): Update these to use new socket schema.
-//TEST(DurationMetricTrackerTest, TestNoCondition) {
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
-//
-// int tagId = 1;
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.init();
-// LogEvent event2(tagId, bucketStartTimeNs + bucketSizeNs + 2);
-// event2.init();
-//
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, -1 /*no condition*/, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
-// EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// durationProducer.mPastBuckets.end());
-// const auto& buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(2UL, buckets.size());
-// EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
-// EXPECT_EQ(bucketSizeNs - 1LL, buckets[0].mDuration);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[1].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[1].mBucketEndNs);
-// EXPECT_EQ(2LL, buckets[1].mDuration);
-//}
-//
-//TEST(DurationMetricTrackerTest, TestNonSlicedCondition) {
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
-//
-// int tagId = 1;
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.init();
-// LogEvent event2(tagId, bucketStartTimeNs + 2);
-// event2.init();
-// LogEvent event3(tagId, bucketStartTimeNs + bucketSizeNs + 1);
-// event3.init();
-// LogEvent event4(tagId, bucketStartTimeNs + bucketSizeNs + 3);
-// event4.init();
-//
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, 0 /* condition index */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-// durationProducer.mCondition = ConditionState::kFalse;
-//
-// EXPECT_FALSE(durationProducer.mCondition);
-// EXPECT_FALSE(durationProducer.isConditionSliced());
-//
-// durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
-//
-// durationProducer.onMatchedLogEvent(1 /* start index*/, event3);
-// durationProducer.onConditionChanged(true /* condition */, bucketStartTimeNs + bucketSizeNs + 2);
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, event4);
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
-// EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
-// durationProducer.mPastBuckets.end());
-// const auto& buckets2 = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets2.size());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets2[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets2[0].mBucketEndNs);
-// EXPECT_EQ(1LL, buckets2[0].mDuration);
-//}
-//
-//TEST(DurationMetricTrackerTest, TestNonSlicedConditionUnknownState) {
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
-//
-// int tagId = 1;
-// LogEvent event1(tagId, bucketStartTimeNs + 1);
-// event1.init();
-// LogEvent event2(tagId, bucketStartTimeNs + 2);
-// event2.init();
-// LogEvent event3(tagId, bucketStartTimeNs + bucketSizeNs + 1);
-// event3.init();
-// LogEvent event4(tagId, bucketStartTimeNs + bucketSizeNs + 3);
-// event4.init();
-//
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, 0 /* condition index */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// EXPECT_EQ(ConditionState::kUnknown, durationProducer.mCondition);
-// EXPECT_FALSE(durationProducer.isConditionSliced());
-//
-// durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
-//
-// durationProducer.onMatchedLogEvent(1 /* start index*/, event3);
-// durationProducer.onConditionChanged(true /* condition */, bucketStartTimeNs + bucketSizeNs + 2);
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, event4);
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
-// const auto& buckets2 = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets2.size());
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets2[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets2[0].mBucketEndNs);
-// EXPECT_EQ(1LL, buckets2[0].mDuration);
-//}
-//
-//TEST(DurationMetricTrackerTest, TestSumDurationWithUpgrade) {
-// /**
-// * The duration starts from the first bucket, through the two partial buckets (10-70sec),
-// * another bucket, and ends at the beginning of the next full bucket.
-// * Expected buckets:
-// * - [10,25]: 14 secs
-// * - [25,70]: All 45 secs
-// * - [70,130]: All 60 secs
-// * - [130, 210]: Only 5 secs (event ended at 135sec)
-// */
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
-// int64_t startTimeNs = bucketStartTimeNs + 1 * NS_PER_SEC;
-// int64_t endTimeNs = startTimeNs + 125 * NS_PER_SEC;
-//
-// int tagId = 1;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, -1 /* no condition */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// LogEvent start_event(tagId, startTimeNs);
-// start_event.init();
-// durationProducer.onMatchedLogEvent(1 /* start index*/, start_event);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
-// EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// EXPECT_EQ(1UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// std::vector<DurationBucket> buckets =
-// durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
-// EXPECT_EQ(eventUpgradeTimeNs, buckets[0].mBucketEndNs);
-// EXPECT_EQ(eventUpgradeTimeNs - startTimeNs, buckets[0].mDuration);
-// EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
-// LogEvent end_event(tagId, endTimeNs);
-// end_event.init();
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, end_event);
-// buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(3UL, buckets.size());
-// EXPECT_EQ(eventUpgradeTimeNs, buckets[1].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[1].mBucketEndNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - eventUpgradeTimeNs, buckets[1].mDuration);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[2].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[2].mBucketEndNs);
-// EXPECT_EQ(bucketSizeNs, buckets[2].mDuration);
-//}
-//
-//TEST(DurationMetricTrackerTest, TestSumDurationWithUpgradeInFollowingBucket) {
-// /**
-// * Expected buckets (start at 11s, upgrade at 75s, end at 135s):
-// * - [10,70]: 59 secs
-// * - [70,75]: 5 sec
-// * - [75,130]: 55 secs
-// */
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 65 * NS_PER_SEC;
-// int64_t startTimeNs = bucketStartTimeNs + 1 * NS_PER_SEC;
-// int64_t endTimeNs = startTimeNs + 125 * NS_PER_SEC;
-//
-// int tagId = 1;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, -1 /* no condition */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// LogEvent start_event(tagId, startTimeNs);
-// start_event.init();
-// durationProducer.onMatchedLogEvent(1 /* start index*/, start_event);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
-// EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// EXPECT_EQ(2UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// std::vector<DurationBucket> buckets =
-// durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - startTimeNs, buckets[0].mDuration);
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[1].mBucketStartNs);
-// EXPECT_EQ(eventUpgradeTimeNs, buckets[1].mBucketEndNs);
-// EXPECT_EQ(eventUpgradeTimeNs - (bucketStartTimeNs + bucketSizeNs), buckets[1].mDuration);
-// EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
-// LogEvent end_event(tagId, endTimeNs);
-// end_event.init();
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, end_event);
-// buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(3UL, buckets.size());
-// EXPECT_EQ(eventUpgradeTimeNs, buckets[2].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[2].mBucketEndNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs - eventUpgradeTimeNs, buckets[2].mDuration);
-//}
-//
-//TEST(DurationMetricTrackerTest, TestSumDurationAnomalyWithUpgrade) {
-// sp<AlarmMonitor> alarmMonitor;
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
-// int64_t startTimeNs = bucketStartTimeNs + 1;
-// int64_t endTimeNs = startTimeNs + 65 * NS_PER_SEC;
-//
-// int tagId = 1;
-//
-// // Setup metric with alert.
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
-// Alert alert;
-// alert.set_num_buckets(3);
-// alert.set_trigger_if_sum_gt(2);
-//
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, -1 /* no condition */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// sp<AnomalyTracker> anomalyTracker = durationProducer.addAnomalyTracker(alert, alarmMonitor);
-// EXPECT_TRUE(anomalyTracker != nullptr);
-//
-// LogEvent start_event(tagId, startTimeNs);
-// start_event.init();
-// durationProducer.onMatchedLogEvent(1 /* start index*/, start_event);
-// durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
-// LogEvent end_event(tagId, endTimeNs);
-// end_event.init();
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, end_event);
-//
-// EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - startTimeNs,
-// anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
-//}
-//
-//TEST(DurationMetricTrackerTest, TestMaxDurationWithUpgrade) {
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
-// int64_t startTimeNs = bucketStartTimeNs + 1;
-// int64_t endTimeNs = startTimeNs + 125 * NS_PER_SEC;
-//
-// int tagId = 1;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_MAX_SPARSE);
-// LogEvent event1(tagId, startTimeNs);
-// event1.write("111"); // uid
-// event1.init();
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, -1 /* no condition */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// LogEvent start_event(tagId, startTimeNs);
-// start_event.init();
-// durationProducer.onMatchedLogEvent(1 /* start index*/, start_event);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
-// EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
-// LogEvent end_event(tagId, endTimeNs);
-// end_event.init();
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, end_event);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-//
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + 3 * bucketSizeNs + 1);
-// std::vector<DurationBucket> buckets =
-// durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets.size());
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, buckets[0].mBucketEndNs);
-// EXPECT_EQ(endTimeNs - startTimeNs, buckets[0].mDuration);
-//}
-//
-//TEST(DurationMetricTrackerTest, TestMaxDurationWithUpgradeInNextBucket) {
-// int64_t bucketStartTimeNs = 10000000000;
-// int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
-// int64_t eventUpgradeTimeNs = bucketStartTimeNs + 65 * NS_PER_SEC;
-// int64_t startTimeNs = bucketStartTimeNs + 1;
-// int64_t endTimeNs = startTimeNs + 115 * NS_PER_SEC;
-//
-// int tagId = 1;
-//
-// DurationMetric metric;
-// metric.set_id(1);
-// metric.set_bucket(ONE_MINUTE);
-// metric.set_aggregation_type(DurationMetric_AggregationType_MAX_SPARSE);
-// LogEvent event1(tagId, startTimeNs);
-// event1.write("111"); // uid
-// event1.init();
-// sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
-// FieldMatcher dimensions;
-// DurationMetricProducer durationProducer(
-// kConfigKey, metric, -1 /* no condition */, 1 /* start index */, 2 /* stop index */,
-// 3 /* stop_all index */, false /*nesting*/, wizard, dimensions, bucketStartTimeNs, bucketStartTimeNs);
-//
-// LogEvent start_event(tagId, startTimeNs);
-// start_event.init();
-// durationProducer.onMatchedLogEvent(1 /* start index*/, start_event);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
-// EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// // Stop occurs in the same partial bucket as created for the app upgrade.
-// LogEvent end_event(tagId, endTimeNs);
-// end_event.init();
-// durationProducer.onMatchedLogEvent(2 /* stop index*/, end_event);
-// EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
-// EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
-//
-// durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
-// std::vector<DurationBucket> buckets =
-// durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
-// EXPECT_EQ(1UL, buckets.size());
-// EXPECT_EQ(eventUpgradeTimeNs, buckets[0].mBucketStartNs);
-// EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[0].mBucketEndNs);
-// EXPECT_EQ(endTimeNs - startTimeNs, buckets[0].mDuration);
-//}
+TEST(DurationMetricTrackerTest, TestNoCondition) {
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + bucketSizeNs + 2, tagId);
+
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, -1 /*no condition*/,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
+ EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
+ EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ durationProducer.mPastBuckets.end());
+ const auto& buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(2UL, buckets.size());
+ EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
+ EXPECT_EQ(bucketSizeNs - 1LL, buckets[0].mDuration);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[1].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[1].mBucketEndNs);
+ EXPECT_EQ(2LL, buckets[1].mDuration);
+}
+
+TEST(DurationMetricTrackerTest, TestNonSlicedCondition) {
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 2, tagId);
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event3, bucketStartTimeNs + bucketSizeNs + 1, tagId);
+ LogEvent event4(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event4, bucketStartTimeNs + bucketSizeNs + 3, tagId);
+
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, 0 /* condition index */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+ durationProducer.mCondition = ConditionState::kFalse;
+
+ EXPECT_FALSE(durationProducer.mCondition);
+ EXPECT_FALSE(durationProducer.isConditionSliced());
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event3);
+ durationProducer.onConditionChanged(true /* condition */, bucketStartTimeNs + bucketSizeNs + 2);
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event4);
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
+ EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
+ EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
+ durationProducer.mPastBuckets.end());
+ const auto& buckets2 = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets2.size());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets2[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets2[0].mBucketEndNs);
+ EXPECT_EQ(1LL, buckets2[0].mDuration);
+}
+
+TEST(DurationMetricTrackerTest, TestNonSlicedConditionUnknownState) {
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, bucketStartTimeNs + 1, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, bucketStartTimeNs + 2, tagId);
+ LogEvent event3(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event3, bucketStartTimeNs + bucketSizeNs + 1, tagId);
+ LogEvent event4(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event4, bucketStartTimeNs + bucketSizeNs + 3, tagId);
+
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, 0 /* condition index */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ EXPECT_EQ(ConditionState::kUnknown, durationProducer.mCondition);
+ EXPECT_FALSE(durationProducer.isConditionSliced());
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event3);
+ durationProducer.onConditionChanged(true /* condition */, bucketStartTimeNs + bucketSizeNs + 2);
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event4);
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
+ EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
+ const auto& buckets2 = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets2.size());
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets2[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets2[0].mBucketEndNs);
+ EXPECT_EQ(1LL, buckets2[0].mDuration);
+}
+
+TEST(DurationMetricTrackerTest, TestSumDurationWithUpgrade) {
+ /**
+ * The duration starts from the first bucket, through the two partial buckets (10-70sec),
+ * another bucket, and ends at the beginning of the next full bucket.
+ * Expected buckets:
+ * - [10,25]: 14 secs
+ * - [25,70]: All 45 secs
+ * - [70,130]: All 60 secs
+ * - [130, 210]: Only 5 secs (event ended at 135sec)
+ */
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
+ int64_t startTimeNs = bucketStartTimeNs + 1 * NS_PER_SEC;
+ int64_t endTimeNs = startTimeNs + 125 * NS_PER_SEC;
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, startTimeNs, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, endTimeNs, tagId);
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, -1 /* no condition */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
+ EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+ EXPECT_EQ(1UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ std::vector<DurationBucket> buckets =
+ durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
+ EXPECT_EQ(eventUpgradeTimeNs, buckets[0].mBucketEndNs);
+ EXPECT_EQ(eventUpgradeTimeNs - startTimeNs, buckets[0].mDuration);
+ EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(3UL, buckets.size());
+ EXPECT_EQ(eventUpgradeTimeNs, buckets[1].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[1].mBucketEndNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - eventUpgradeTimeNs, buckets[1].mDuration);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[2].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[2].mBucketEndNs);
+ EXPECT_EQ(bucketSizeNs, buckets[2].mDuration);
+}
+
+TEST(DurationMetricTrackerTest, TestSumDurationWithUpgradeInFollowingBucket) {
+ /**
+ * Expected buckets (start at 11s, upgrade at 75s, end at 135s):
+ * - [10,70]: 59 secs
+ * - [70,75]: 5 sec
+ * - [75,130]: 55 secs
+ */
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 65 * NS_PER_SEC;
+ int64_t startTimeNs = bucketStartTimeNs + 1 * NS_PER_SEC;
+ int64_t endTimeNs = startTimeNs + 125 * NS_PER_SEC;
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, startTimeNs, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, endTimeNs, tagId);
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, -1 /* no condition */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
+ EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+ EXPECT_EQ(2UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ std::vector<DurationBucket> buckets =
+ durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - startTimeNs, buckets[0].mDuration);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[1].mBucketStartNs);
+ EXPECT_EQ(eventUpgradeTimeNs, buckets[1].mBucketEndNs);
+ EXPECT_EQ(eventUpgradeTimeNs - (bucketStartTimeNs + bucketSizeNs), buckets[1].mDuration);
+ EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(3UL, buckets.size());
+ EXPECT_EQ(eventUpgradeTimeNs, buckets[2].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[2].mBucketEndNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs - eventUpgradeTimeNs, buckets[2].mDuration);
+}
+
+TEST(DurationMetricTrackerTest, TestSumDurationAnomalyWithUpgrade) {
+ sp<AlarmMonitor> alarmMonitor;
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
+ int64_t startTimeNs = bucketStartTimeNs + 1;
+ int64_t endTimeNs = startTimeNs + 65 * NS_PER_SEC;
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, startTimeNs, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, endTimeNs, tagId);
+
+ // Setup metric with alert.
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_SUM);
+ Alert alert;
+ alert.set_num_buckets(3);
+ alert.set_trigger_if_sum_gt(2);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, -1 /* no condition */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ sp<AnomalyTracker> anomalyTracker = durationProducer.addAnomalyTracker(alert, alarmMonitor);
+ EXPECT_TRUE(anomalyTracker != nullptr);
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+
+ // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ EXPECT_EQ(bucketStartTimeNs + bucketSizeNs - startTimeNs,
+ anomalyTracker->getSumOverPastBuckets(DEFAULT_METRIC_DIMENSION_KEY));
+}
+
+TEST(DurationMetricTrackerTest, TestMaxDurationWithUpgrade) {
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 15 * NS_PER_SEC;
+ int64_t startTimeNs = bucketStartTimeNs + 1;
+ int64_t endTimeNs = startTimeNs + 125 * NS_PER_SEC;
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, startTimeNs, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, endTimeNs, tagId);
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_MAX_SPARSE);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, -1 /* no condition */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
+ EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ // We skip ahead one bucket, so we fill in the first two partial buckets and one full bucket.
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + 3 * bucketSizeNs + 1);
+ std::vector<DurationBucket> buckets =
+ durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets.size());
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, buckets[0].mBucketEndNs);
+ EXPECT_EQ(endTimeNs - startTimeNs, buckets[0].mDuration);
+}
+
+TEST(DurationMetricTrackerTest, TestMaxDurationWithUpgradeInNextBucket) {
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL;
+ int64_t eventUpgradeTimeNs = bucketStartTimeNs + 65 * NS_PER_SEC;
+ int64_t startTimeNs = bucketStartTimeNs + 1;
+ int64_t endTimeNs = startTimeNs + 115 * NS_PER_SEC;
+
+ int tagId = 1;
+ LogEvent event1(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event1, startTimeNs, tagId);
+ LogEvent event2(/*uid=*/0, /*pid=*/0);
+ makeLogEvent(&event2, endTimeNs, tagId);
+
+ DurationMetric metric;
+ metric.set_id(1);
+ metric.set_bucket(ONE_MINUTE);
+ metric.set_aggregation_type(DurationMetric_AggregationType_MAX_SPARSE);
+
+ sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
+ FieldMatcher dimensions;
+ DurationMetricProducer durationProducer(kConfigKey, metric, -1 /* no condition */,
+ 1 /* start index */, 2 /* stop index */,
+ 3 /* stop_all index */, false /*nesting*/, wizard,
+ dimensions, bucketStartTimeNs, bucketStartTimeNs);
+
+ durationProducer.onMatchedLogEvent(1 /* start index*/, event1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets.size());
+ EXPECT_EQ(bucketStartTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ durationProducer.notifyAppUpgrade(eventUpgradeTimeNs, "ANY.APP", 1, 1);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ // Stop occurs in the same partial bucket as created for the app upgrade.
+ durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
+ EXPECT_EQ(0UL, durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ EXPECT_EQ(eventUpgradeTimeNs, durationProducer.mCurrentBucketStartTimeNs);
+
+ durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
+ std::vector<DurationBucket> buckets =
+ durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
+ EXPECT_EQ(1UL, buckets.size());
+ EXPECT_EQ(eventUpgradeTimeNs, buckets[0].mBucketStartNs);
+ EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[0].mBucketEndNs);
+ EXPECT_EQ(endTimeNs - startTimeNs, buckets[0].mDuration);
+}
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/tests/statsd_test_util.cpp b/cmds/statsd/tests/statsd_test_util.cpp
index d416f13..e2eee03 100644
--- a/cmds/statsd/tests/statsd_test_util.cpp
+++ b/cmds/statsd/tests/statsd_test_util.cpp
@@ -410,40 +410,75 @@
return dimensions;
}
-// TODO(b/149590301): Update these helpers to use new socket schema.
-//std::unique_ptr<LogEvent> CreateScreenStateChangedEvent(
-// const android::view::DisplayStateEnum state, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(android::util::SCREEN_STATE_CHANGED, timestampNs);
-// EXPECT_TRUE(event->write(state));
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateBatterySaverOnEvent(uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(
-// android::util::BATTERY_SAVER_MODE_STATE_CHANGED, timestampNs);
-// EXPECT_TRUE(event->write(BatterySaverModeStateChanged::ON));
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(
-// android::util::BATTERY_SAVER_MODE_STATE_CHANGED, timestampNs);
-// EXPECT_TRUE(event->write(BatterySaverModeStateChanged::OFF));
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(
-// int level, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(android::util::SCREEN_BRIGHTNESS_CHANGED, timestampNs);
-// EXPECT_TRUE(event->write(level));
-// event->init();
-// return event;
-//
-//}
-//
+std::unique_ptr<LogEvent> CreateScreenStateChangedEvent(
+ uint64_t timestampNs, const android::view::DisplayStateEnum state) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::SCREEN_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, state);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateBatterySaverOnEvent(uint64_t timestampNs) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::BATTERY_SAVER_MODE_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, BatterySaverModeStateChanged::ON);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::BATTERY_SAVER_MODE_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, BatterySaverModeStateChanged::OFF);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(uint64_t timestampNs, int level) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::SCREEN_BRIGHTNESS_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, level);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
//std::unique_ptr<LogEvent> CreateScheduledJobStateChangedEvent(
// const std::vector<AttributionNodeInternal>& attributions, const string& jobName,
// const ScheduledJobStateChanged::State state, uint64_t timestampNs) {
@@ -470,121 +505,212 @@
// attributions, name, ScheduledJobStateChanged::FINISHED, timestampNs);
//}
//
-//std::unique_ptr<LogEvent> CreateWakelockStateChangedEvent(
-// const std::vector<AttributionNodeInternal>& attributions, const string& wakelockName,
-// const WakelockStateChanged::State state, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(android::util::WAKELOCK_STATE_CHANGED, timestampNs);
-// event->write(attributions);
-// event->write(android::os::WakeLockLevelEnum::PARTIAL_WAKE_LOCK);
-// event->write(wakelockName);
-// event->write(state);
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateAcquireWakelockEvent(
-// const std::vector<AttributionNodeInternal>& attributions, const string& wakelockName,
-// uint64_t timestampNs) {
-// return CreateWakelockStateChangedEvent(
-// attributions, wakelockName, WakelockStateChanged::ACQUIRE, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateReleaseWakelockEvent(
-// const std::vector<AttributionNodeInternal>& attributions, const string& wakelockName,
-// uint64_t timestampNs) {
-// return CreateWakelockStateChangedEvent(
-// attributions, wakelockName, WakelockStateChanged::RELEASE, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateActivityForegroundStateChangedEvent(
-// const int uid, const ActivityForegroundStateChanged::State state, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(
-// android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, timestampNs);
-// event->write(uid);
-// event->write("pkg_name");
-// event->write("class_name");
-// event->write(state);
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(const int uid, uint64_t timestampNs) {
-// return CreateActivityForegroundStateChangedEvent(
-// uid, ActivityForegroundStateChanged::BACKGROUND, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateMoveToForegroundEvent(const int uid, uint64_t timestampNs) {
-// return CreateActivityForegroundStateChangedEvent(
-// uid, ActivityForegroundStateChanged::FOREGROUND, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateSyncStateChangedEvent(
-// const std::vector<AttributionNodeInternal>& attributions, const string& name,
-// const SyncStateChanged::State state, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(android::util::SYNC_STATE_CHANGED, timestampNs);
-// event->write(attributions);
-// event->write(name);
-// event->write(state);
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateSyncStartEvent(
-// const std::vector<AttributionNodeInternal>& attributions, const string& name,
-// uint64_t timestampNs) {
-// return CreateSyncStateChangedEvent(attributions, name, SyncStateChanged::ON, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateSyncEndEvent(
-// const std::vector<AttributionNodeInternal>& attributions, const string& name,
-// uint64_t timestampNs) {
-// return CreateSyncStateChangedEvent(attributions, name, SyncStateChanged::OFF, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateProcessLifeCycleStateChangedEvent(
-// const int uid, const ProcessLifeCycleStateChanged::State state, uint64_t timestampNs) {
-// auto logEvent = std::make_unique<LogEvent>(
-// android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, timestampNs);
-// logEvent->write(uid);
-// logEvent->write("");
-// logEvent->write(state);
-// logEvent->init();
-// return logEvent;
-//}
-//
-//std::unique_ptr<LogEvent> CreateAppCrashEvent(const int uid, uint64_t timestampNs) {
-// return CreateProcessLifeCycleStateChangedEvent(
-// uid, ProcessLifeCycleStateChanged::CRASHED, timestampNs);
-//}
-//
-//std::unique_ptr<LogEvent> CreateAppCrashOccurredEvent(const int uid, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(android::util::APP_CRASH_OCCURRED, timestampNs);
-// event->write(uid);
-// event->write("eventType");
-// event->write("processName");
-// event->init();
-// return event;
-//}
-//
-//std::unique_ptr<LogEvent> CreateIsolatedUidChangedEvent(
-// int isolatedUid, int hostUid, bool is_create, uint64_t timestampNs) {
-// auto logEvent = std::make_unique<LogEvent>(
-// android::util::ISOLATED_UID_CHANGED, timestampNs);
-// logEvent->write(hostUid);
-// logEvent->write(isolatedUid);
-// logEvent->write(is_create);
-// logEvent->init();
-// return logEvent;
-//}
-//
-//std::unique_ptr<LogEvent> CreateUidProcessStateChangedEvent(
-// int uid, const android::app::ProcessStateEnum state, uint64_t timestampNs) {
-// auto event = std::make_unique<LogEvent>(android::util::UID_PROCESS_STATE_CHANGED, timestampNs);
-// event->write(uid);
-// event->write(state);
-// event->init();
-// return event;
-//}
+std::unique_ptr<LogEvent> CreateWakelockStateChangedEvent(uint64_t timestampNs,
+ const vector<int>& attributionUids,
+ const vector<string>& attributionTags,
+ const string& wakelockName,
+ const WakelockStateChanged::State state) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::WAKELOCK_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ vector<const char*> cTags(attributionTags.size());
+ for (int i = 0; i < cTags.size(); i++) {
+ cTags[i] = attributionTags[i].c_str();
+ }
+
+ AStatsEvent_writeAttributionChain(statsEvent,
+ reinterpret_cast<const uint32_t*>(attributionUids.data()),
+ cTags.data(), attributionUids.size());
+ AStatsEvent_writeInt32(statsEvent, android::os::WakeLockLevelEnum::PARTIAL_WAKE_LOCK);
+ AStatsEvent_writeString(statsEvent, wakelockName.c_str());
+ AStatsEvent_writeInt32(statsEvent, state);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateAcquireWakelockEvent(uint64_t timestampNs,
+ const vector<int>& attributionUids,
+ const vector<string>& attributionTags,
+ const string& wakelockName) {
+ return CreateWakelockStateChangedEvent(timestampNs, attributionUids, attributionTags,
+ wakelockName, WakelockStateChanged::ACQUIRE);
+}
+
+std::unique_ptr<LogEvent> CreateReleaseWakelockEvent(uint64_t timestampNs,
+ const vector<int>& attributionUids,
+ const vector<string>& attributionTags,
+ const string& wakelockName) {
+ return CreateWakelockStateChangedEvent(timestampNs, attributionUids, attributionTags,
+ wakelockName, WakelockStateChanged::RELEASE);
+}
+
+std::unique_ptr<LogEvent> CreateActivityForegroundStateChangedEvent(
+ uint64_t timestampNs, const int uid, const ActivityForegroundStateChanged::State state) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::ACTIVITY_FOREGROUND_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, uid);
+ AStatsEvent_writeString(statsEvent, "pkg_name");
+ AStatsEvent_writeString(statsEvent, "class_name");
+ AStatsEvent_writeInt32(statsEvent, state);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(uint64_t timestampNs, const int uid) {
+ return CreateActivityForegroundStateChangedEvent(timestampNs, uid,
+ ActivityForegroundStateChanged::BACKGROUND);
+}
+
+std::unique_ptr<LogEvent> CreateMoveToForegroundEvent(uint64_t timestampNs, const int uid) {
+ return CreateActivityForegroundStateChangedEvent(timestampNs, uid,
+ ActivityForegroundStateChanged::FOREGROUND);
+}
+
+std::unique_ptr<LogEvent> CreateSyncStateChangedEvent(uint64_t timestampNs,
+ const vector<int>& attributionUids,
+ const vector<string>& attributionTags,
+ const string& name,
+ const SyncStateChanged::State state) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::SYNC_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ vector<const char*> cTags(attributionTags.size());
+ for (int i = 0; i < cTags.size(); i++) {
+ cTags[i] = attributionTags[i].c_str();
+ }
+
+ AStatsEvent_writeAttributionChain(statsEvent,
+ reinterpret_cast<const uint32_t*>(attributionUids.data()),
+ cTags.data(), attributionUids.size());
+ AStatsEvent_writeString(statsEvent, name.c_str());
+ AStatsEvent_writeInt32(statsEvent, state);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateSyncStartEvent(uint64_t timestampNs,
+ const vector<int>& attributionUids,
+ const vector<string>& attributionTags,
+ const string& name) {
+ return CreateSyncStateChangedEvent(timestampNs, attributionUids, attributionTags, name,
+ SyncStateChanged::ON);
+}
+
+std::unique_ptr<LogEvent> CreateSyncEndEvent(uint64_t timestampNs,
+ const vector<int>& attributionUids,
+ const vector<string>& attributionTags,
+ const string& name) {
+ return CreateSyncStateChangedEvent(timestampNs, attributionUids, attributionTags, name,
+ SyncStateChanged::OFF);
+}
+
+std::unique_ptr<LogEvent> CreateProcessLifeCycleStateChangedEvent(
+ uint64_t timestampNs, const int uid, const ProcessLifeCycleStateChanged::State state) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, uid);
+ AStatsEvent_writeString(statsEvent, "");
+ AStatsEvent_writeInt32(statsEvent, state);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateAppCrashEvent(uint64_t timestampNs, const int uid) {
+ return CreateProcessLifeCycleStateChangedEvent(timestampNs, uid,
+ ProcessLifeCycleStateChanged::CRASHED);
+}
+
+std::unique_ptr<LogEvent> CreateAppCrashOccurredEvent(uint64_t timestampNs, const int uid) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::APP_CRASH_OCCURRED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, uid);
+ AStatsEvent_writeString(statsEvent, "eventType");
+ AStatsEvent_writeString(statsEvent, "processName");
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateIsolatedUidChangedEvent(uint64_t timestampNs, int hostUid,
+ int isolatedUid, bool is_create) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::ISOLATED_UID_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, hostUid);
+ AStatsEvent_writeInt32(statsEvent, isolatedUid);
+ AStatsEvent_writeInt32(statsEvent, is_create);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
+
+std::unique_ptr<LogEvent> CreateUidProcessStateChangedEvent(
+ uint64_t timestampNs, int uid, const android::app::ProcessStateEnum state) {
+ AStatsEvent* statsEvent = AStatsEvent_obtain();
+ AStatsEvent_setAtomId(statsEvent, android::util::UID_PROCESS_STATE_CHANGED);
+ AStatsEvent_overwriteTimestamp(statsEvent, timestampNs);
+
+ AStatsEvent_writeInt32(statsEvent, uid);
+ AStatsEvent_writeInt32(statsEvent, state);
+ AStatsEvent_build(statsEvent);
+
+ size_t size;
+ uint8_t* buf = AStatsEvent_getBuffer(statsEvent, &size);
+
+ std::unique_ptr<LogEvent> logEvent = std::make_unique<LogEvent>(/*uid=*/0, /*pid=*/0);
+ logEvent->parseBuffer(buf, size);
+ AStatsEvent_release(statsEvent);
+ return logEvent;
+}
sp<StatsLogProcessor> CreateStatsLogProcessor(const int64_t timeBaseNs, const int64_t currentTimeNs,
const StatsdConfig& config, const ConfigKey& key,
diff --git a/cmds/statsd/tests/statsd_test_util.h b/cmds/statsd/tests/statsd_test_util.h
index c8326ee..4371015 100644
--- a/cmds/statsd/tests/statsd_test_util.h
+++ b/cmds/statsd/tests/statsd_test_util.h
@@ -166,11 +166,10 @@
// Create log event for screen state changed.
std::unique_ptr<LogEvent> CreateScreenStateChangedEvent(
- const android::view::DisplayStateEnum state, uint64_t timestampNs);
+ uint64_t timestampNs, const android::view::DisplayStateEnum state);
// Create log event for screen brightness state changed.
-std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(
- int level, uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(uint64_t timestampNs, int level);
// Create log event when scheduled job starts.
std::unique_ptr<LogEvent> CreateStartScheduledJobEvent(
@@ -188,45 +187,42 @@
std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs);
// Create log event for app moving to background.
-std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(const int uid, uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(uint64_t timestampNs, const int uid);
// Create log event for app moving to foreground.
-std::unique_ptr<LogEvent> CreateMoveToForegroundEvent(const int uid, uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateMoveToForegroundEvent(uint64_t timestampNs, const int uid);
// Create log event when the app sync starts.
-std::unique_ptr<LogEvent> CreateSyncStartEvent(
- const std::vector<AttributionNodeInternal>& attributions, const string& name,
- uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateSyncStartEvent(uint64_t timestampNs, const vector<int>& uids,
+ const vector<string>& tags, const string& name);
// Create log event when the app sync ends.
-std::unique_ptr<LogEvent> CreateSyncEndEvent(
- const std::vector<AttributionNodeInternal>& attributions, const string& name,
- uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateSyncEndEvent(uint64_t timestampNs, const vector<int>& uids,
+ const vector<string>& tags, const string& name);
// Create log event when the app sync ends.
-std::unique_ptr<LogEvent> CreateAppCrashEvent(
- const int uid, uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateAppCrashEvent(uint64_t timestampNs, const int uid);
// Create log event for an app crash.
-std::unique_ptr<LogEvent> CreateAppCrashOccurredEvent(const int uid, uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateAppCrashOccurredEvent(uint64_t timestampNs, const int uid);
// Create log event for acquiring wakelock.
-std::unique_ptr<LogEvent> CreateAcquireWakelockEvent(
- const std::vector<AttributionNodeInternal>& attributions, const string& wakelockName,
- uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateAcquireWakelockEvent(uint64_t timestampNs, const vector<int>& uids,
+ const vector<string>& tags,
+ const string& wakelockName);
// Create log event for releasing wakelock.
-std::unique_ptr<LogEvent> CreateReleaseWakelockEvent(
- const std::vector<AttributionNodeInternal>& attributions, const string& wakelockName,
- uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateReleaseWakelockEvent(uint64_t timestampNs, const vector<int>& uids,
+ const vector<string>& tags,
+ const string& wakelockName);
// Create log event for releasing wakelock.
-std::unique_ptr<LogEvent> CreateIsolatedUidChangedEvent(
- int isolatedUid, int hostUid, bool is_create, uint64_t timestampNs);
+std::unique_ptr<LogEvent> CreateIsolatedUidChangedEvent(uint64_t timestampNs, int hostUid,
+ int isolatedUid, bool is_create);
// Create log event for uid process state change.
std::unique_ptr<LogEvent> CreateUidProcessStateChangedEvent(
- int uid, const android::app::ProcessStateEnum state, uint64_t timestampNs);
+ uint64_t timestampNs, int uid, const android::app::ProcessStateEnum state);
// Helper function to create an AttributionNodeInternal proto.
AttributionNodeInternal CreateAttribution(const int& uid, const string& tag);
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index 3a3eea9..e7036bb 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -48,6 +48,7 @@
import android.util.SparseArray;
import android.view.Display;
import android.view.KeyEvent;
+import android.view.SurfaceControl;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.view.WindowManagerImpl;
@@ -1937,8 +1938,8 @@
* to declare the capability to take screenshot by setting the
* {@link android.R.styleable#AccessibilityService_canTakeScreenshot}
* property in its meta-data. For details refer to {@link #SERVICE_META_DATA}.
- * Besides, This API is only supported for default display now
- * {@link Display#DEFAULT_DISPLAY}.
+ * This API only will support {@link Display#DEFAULT_DISPLAY} until {@link SurfaceControl}
+ * supports non-default displays.
* </p>
*
* @param displayId The logic display id, must be {@link Display#DEFAULT_DISPLAY} for
@@ -1948,11 +1949,17 @@
*
* @return {@code true} if the taking screenshot accepted, {@code false} if too little time
* has elapsed since the last screenshot, invalid display or internal errors.
+ * @throws IllegalArgumentException if displayId is not {@link Display#DEFAULT_DISPLAY}.
*/
public boolean takeScreenshot(int displayId, @NonNull @CallbackExecutor Executor executor,
@NonNull Consumer<ScreenshotResult> callback) {
Preconditions.checkNotNull(executor, "executor cannot be null");
Preconditions.checkNotNull(callback, "callback cannot be null");
+
+ if (displayId != Display.DEFAULT_DISPLAY) {
+ throw new IllegalArgumentException("DisplayId isn't the default display");
+ }
+
final IAccessibilityServiceConnection connection =
AccessibilityInteractionClient.getInstance().getConnection(
mConnectionId);
diff --git a/core/java/android/animation/ValueAnimator.java b/core/java/android/animation/ValueAnimator.java
index ca37e9b..2c41e8d 100644
--- a/core/java/android/animation/ValueAnimator.java
+++ b/core/java/android/animation/ValueAnimator.java
@@ -18,6 +18,7 @@
import android.annotation.CallSuper;
import android.annotation.IntDef;
+import android.annotation.Nullable;
import android.annotation.TestApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
@@ -269,6 +270,11 @@
private float mDurationScale = -1f;
/**
+ * Animation handler used to schedule updates for this animation.
+ */
+ private AnimationHandler mAnimationHandler;
+
+ /**
* Public constants
*/
@@ -1684,6 +1690,15 @@
* @hide
*/
public AnimationHandler getAnimationHandler() {
- return AnimationHandler.getInstance();
+ return mAnimationHandler != null ? mAnimationHandler : AnimationHandler.getInstance();
+ }
+
+ /**
+ * Sets the animation handler used to schedule updates for this animator or {@code null} to use
+ * the default handler.
+ * @hide
+ */
+ public void setAnimationHandler(@Nullable AnimationHandler animationHandler) {
+ mAnimationHandler = animationHandler;
}
}
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 8d6bc72..6480a6a 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -5829,7 +5829,7 @@
intent.prepareToLeaveProcess(this);
result = ActivityTaskManager.getService()
.startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
- getFeatureId(), intent,
+ getAttributionTag(), intent,
intent.resolveTypeIfNeeded(getContentResolver()), mToken, mEmbeddedID,
requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, options);
} catch (RemoteException e) {
@@ -6624,12 +6624,10 @@
String packageName = getPackageName();
try {
data.prepareToLeaveProcess(this);
- IIntentSender target =
- ActivityManager.getService().getIntentSenderWithFeature(
- ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, getFeatureId(),
- mParent == null ? mToken : mParent.mToken,
- mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
- getUserId());
+ IIntentSender target = ActivityManager.getService().getIntentSenderWithFeature(
+ ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, getAttributionTag(),
+ mParent == null ? mToken : mParent.mToken, mEmbeddedID, requestCode,
+ new Intent[]{data}, null, flags, null, getUserId());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
// Empty
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index dd4788e..1a92b75 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -4243,6 +4243,7 @@
* @hide
*/
@SystemApi
+ @TestApi
@RequiresPermission(android.Manifest.permission.CHANGE_CONFIGURATION)
public boolean updateMccMncConfiguration(@NonNull String mcc, @NonNull String mnc) {
if (mcc == null || mnc == null) {
diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java
index ec11043..489a0de 100644
--- a/core/java/android/app/ActivityManagerInternal.java
+++ b/core/java/android/app/ActivityManagerInternal.java
@@ -34,6 +34,7 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
/**
* Activity manager local system service interface.
@@ -124,6 +125,12 @@
public abstract int getUidProcessState(int uid);
/**
+ * Get a map of pid and package name that process of that pid Android/data and Android/obb
+ * directory is not mounted to lowerfs.
+ */
+ public abstract Map<Integer, String> getProcessesWithPendingBindMounts(int userId);
+
+ /**
* @return {@code true} if system is ready, {@code false} otherwise.
*/
public abstract boolean isSystemReady();
diff --git a/core/java/android/app/AppOps.md b/core/java/android/app/AppOps.md
new file mode 100644
index 0000000..bee701a
--- /dev/null
+++ b/core/java/android/app/AppOps.md
@@ -0,0 +1,212 @@
+<!--
+ Copyright (C) 2020 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
+ -->
+
+# App-ops
+
+App-ops are used for two purposes: Access control and tracking.
+
+App-ops cover a wide variety of functionality from helping with runtime permissions to battery
+consumption tracking.
+
+App-ops are defined in `AppOpsManager` as `OP_...` and need to be continuously numbered. The
+integer values of the app-ops are not exposed. For app-ops visible to 3rd party apps,
+the name of the app-op might be exposed as `OPSTR_`. As the integers are not part of the API, they
+might (and have) changed between platform versions and OEM implementations.
+`AppOpsManager.opToPublicName` and `AppOpsManager.strOpToOp` allow for conversion between integer
+and string identifier for the op.
+
+## App-ops as access restrictions
+
+App-ops can either be controlled for each [uid](../os/Users.md#int-uid) or for each package. Which
+one is used depends on the API provider maintaining this app-op.
+
+For any security or privacy related app-ops the provider needs to control the app-op per uid
+as all security and privacy is based on uid in Android.
+
+App-op used for non-security related tasks are usually controlled per package to provide finer
+granularity.
+
+### Setting the app-op mode
+
+To control access the app-op can be set to:
+
+`MODE_DEFAULT`
+: Default behavior, might differ from app-op to app-op
+
+`MODE_ALLOWED`
+: Allow the access
+
+`MODE_FOREGROUND`
+: Allow the access but only if the app is currently in the [foreground](#foreground)
+
+`MODE_IGNORED`
+: Don't allow the access, i.e. don't perform the requested action or return dummy data
+
+`MODE_ERRORED`
+: Throw a `SecurityException` on access. This can be suppressed by using a `...noThrow` method to
+check the mode
+
+The initial state of an app-op is defined in `AppOpsManager.sOpDefaultMode`. Confusingly the
+initial state is often not `MODE_DEFAULT`
+
+Per-package modes can be set using `AppOpsManager.setMode` and per-uid modes can be set using
+`AppOpsManager.setUidMode`.
+
+**Warning**: Do not use `setMode` and `setUidMode` for the same app-op. Due to the way the
+internal storage for the mode works this can lead to very confusing behavior. If this ever happened
+by accident this needs to be cleaned up for any affected user as the app-op mode is retained over
+reboot.
+
+App-ops can also be set via the shell using the `appops set` command. The target package/uid can be
+defined via parameters to this command.
+
+The current state of the app-op can be read via the `appops get` command or via `dumpsys appops`.
+If the app-op is not mentioned in the output the app-op is in it's initial state.
+
+For example `dumpsys appops`:
+```
+[...]
+ Uid 2000:
+ [...]
+ COARSE_LOCATION: mode=foreground
+ START_FOREGROUND: mode=foreground
+ LEGACY_STORAGE: mode=ignore
+ [...]
+```
+
+### Guarding access based on app-ops
+
+API providers need to check the mode returned by `AppOpsManager.noteOp` if they are are allowing
+access to operations gated by the app-op. `AppOpsManager.unsafeCheckOp` should be used to check the
+mode if no access is granted. E.g. this can be for displaying app-op state in the UI or when
+checking the state before later calling `noteOp` anyway.
+
+If an operation refers to a time span (e.g. a audio-recording session) the API provider should
+use `AppOpsManager.startOp` and `AppOpsManager.finishOp` instead of `noteOp`.
+
+`noteOp` and `startOp` take a `packageName` and `featureId` parameter. These need to be read from
+the calling apps context as `Context.getOpPackageName` and `Context.getFeatureId`, then send to
+the data provider and then passed on the `noteOp`/`startOp` method.
+
+#### App-ops and permissions
+
+Access guarding is often done in combination with permissions using [runtime permissions
+](../permission/Permissions.md#runtime-permissions-and-app-ops) or [app-op permissions
+](../permission/Permissions.md#app-op-permissions). This is preferred over just using an app-op
+ as permissions a concept more familiar to app developers.
+
+### Foreground
+
+The `AppOpsService` tracks the apps' proc state (== foreground-ness) by following the
+`ActivityManagerService`'s proc state. It reduces the possible proc states to only those needed
+for app-ops. It also delays the changes by a _settle time_. This delay is needed as the proc state
+can fluctuate when switching apps. By delaying the change the appops service is not affected by
+those.
+
+The proc state is used for two use cases: Firstly, Tracking remembers the proc state for each
+tracked event. Secondly, `noteOp`/`checkOp` calls for app-op that are set to `MODE_FOREGROUND` are
+translated using the `AppOpsService.UidState.evalMode` method into `MODE_ALLOWED` when the app is
+counted as foreground and `MODE_IGNORED` when the app is counted as background. `checkOpRaw`
+calls are not affected.
+
+The current proc state for an app can be read from `dumpsys appops`. The tracking information can
+be read from `dumpsys appops`
+
+```
+Uid u0a118:
+ state=fg
+ capability=6
+```
+
+## App-ops for tracking
+
+App-ops track many important events, including all accesses to runtime permission protected
+APIs. This is done by tracking when an app-op was noted or started. The tracked data can only be
+read by system components.
+
+**Note:** Only `noteOp`/`startOp` calls are tracked; `unsafeCheckOp` is not tracked. Hence it is
+important to eventually call `noteOp` or `startOp` when providing access to protected operations
+or data.
+
+Some apps are forwarding access to other apps. E.g. an app might get the location from the
+system's location provider and then send the location further to a 3rd app. In this case the
+app passing on the data needs to call `AppOpsManager.noteProxyOp` to signal the access proxying.
+This might also make sense inside of a single app if the access is forwarded between two features of
+the app. In this case an app-op is noted for the forwarding app (proxy) and the app that received
+the data (proxied). As any app can do it is important to track how much the system trusts this
+proxy-access-tracking. For more details see `AppOpService.noteProxyOperation`.
+
+The tracking information can be read from `dumpsys appops` split by feature, proc state and
+proxying information with the syntax
+
+```
+Package THE_PACKAGE_NAME:
+ AN_APP_OP (CURRENT_MODE):
+ FEATURE_ID (or null for default feature)=[
+ ACCESS_OR_REJECT: [PROC_STATE-PROXYING_TAG] TIME proxy[INFO_ABOUT_PROXY IF_PROXY_ACCESS]
+```
+
+Example:
+
+```
+Package com.google.android.gms:
+ READ_CONTACTS (allow):
+ null=[
+ Access: [fgsvc-s] 2020-02-14 14:24:10.559 (-3d23h15m43s642ms)
+ Access: [fgsvc-tp] 2020-02-14 14:23:58.189 (-3d23h15m56s12ms)
+ ]
+ apkappcontext=[
+ Access: [fg-tp] 2020-02-17 14:24:54.721 (-23h14m59s480ms)
+ ]
+ com.google.android.gms.icing=[
+ Access: [fgsvc-tpd] 2020-02-14 14:26:27.018 (-3d23h13m27s183ms) proxy[uid=10070, pkg=com.android.providers.contacts, feature=null]
+ Access: [fg-tpd] 2020-02-18 02:26:08.711 (-11h13m45s490ms) proxy[uid=10070, pkg=com.android.providers.contacts, feature=null]
+ Access: [bg-tpd] 2020-02-14 14:34:55.310 (-3d23h4m58s891ms) proxy[uid=10070, pkg=com.android.providers.contacts, feature=null]
+ ]
+ MANAGE_EXTERNAL_STORAGE (default):
+ null=[
+ Reject: [fg-s]2020-02-18 08:00:04.444 (-5h39m49s757ms)
+ Reject: [bg-s]2020-02-18 08:00:04.427 (-5h39m49s774ms)
+ ]
+```
+
+### Tracking an app's own private data accesses
+
+An app can register an `AppOpsManager.OnOpNotedCallback` to get informed about what accesses the
+system is tracking for it. As each runtime permission has an associated app-op this API is
+particularly useful for an app that want to find unexpected private data accesses.
+
+## Listening to app-op events
+
+System apps (with the appropriate permissions) can listen to most app-op events, such as
+
+`noteOp`
+: `startWatchingNoted`
+
+`startOp`/`finishOp`
+: `startWatchingActive`
+
+mode changes
+: `startWatchingMode`
+
+[foreground](#foreground)-ness changes
+: `startWatchingMode` using the `WATCH_FOREGROUND_CHANGES` flag
+
+Watching such events is only ever as good as the tracked events. E.g. if the audio provider does
+not call `startOp` for a audio-session, the app's activeness for the record-audio app-op is not
+changed. Further there were cases where app-ops were noted even though no data was accessed or
+operation was performed. Hence before relying on the data from app-ops, double check if the data
+is actually reliable.
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 2399e37..fa4aa19 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -27,6 +27,7 @@
import android.annotation.SystemService;
import android.annotation.TestApi;
import android.app.usage.UsageStatsManager;
+import android.compat.Compatibility;
import android.compat.annotation.ChangeId;
import android.compat.annotation.EnabledAfter;
import android.compat.annotation.UnsupportedAppUsage;
@@ -159,10 +160,10 @@
* <p>Some apps are forwarding access to other apps. E.g. an app might get the location from the
* system's location provider and then send the location further to a 3rd app. In this case the
* app passing on the data needs to call {@link #noteProxyOp} to signal the access proxying. This
- * might also make sense inside of a single app if the access is forwarded between two features of
- * the app.
+ * might also make sense inside of a single app if the access is forwarded between two parts of
+ * the tagged with different attribution tags.
*
- * <p>An app can register an {@link AppOpsCollector} to get informed about what accesses the
+ * <p>An app can register an {@link OnOpNotedCallback} to get informed about what accesses the
* system is tracking for it. As each runtime permission has an associated app-op this API is
* particularly useful for an app that want to find unexpected private data accesses.
*/
@@ -206,16 +207,16 @@
private static final Object sLock = new Object();
- /** Current {@link AppOpsCollector}. Change via {@link #setNotedAppOpsCollector} */
+ /** Current {@link OnOpNotedCallback}. Change via {@link #setOnOpNotedCallback} */
@GuardedBy("sLock")
- private static @Nullable AppOpsCollector sNotedAppOpsCollector;
+ private static @Nullable OnOpNotedCallback sOnOpNotedCallback;
/**
* Additional collector that collect accesses and forwards a few of them them via
* {@link IAppOpsService#reportRuntimeAppOpAccessMessageAndGetConfig}.
*/
- private static AppOpsCollector sMessageCollector =
- new AppOpsCollector() {
+ private static OnOpNotedCallback sMessageCollector =
+ new OnOpNotedCallback() {
@Override
public void onNoted(@NonNull SyncNotedAppOp op) {
reportStackTraceIfNeeded(op);
@@ -386,6 +387,22 @@
public static final int WATCH_FOREGROUND_CHANGES = 1 << 0;
/**
+ * Flag for {@link #startWatchingMode} that causes the callback to happen on the switch-op
+ * instead the op the callback was registered. (This simulates pre-R behavior).
+ *
+ * @hide
+ */
+ public static final int CALL_BACK_ON_SWITCHED_OP = 1 << 1;
+
+ /**
+ * Flag to determine whether we should log noteOp/startOp calls to make sure they
+ * are correctly used
+ *
+ * @hide
+ */
+ public static final boolean NOTE_OP_COLLECTION_ENABLED = false;
+
+ /**
* @hide
*/
public static final String[] MODE_NAMES = new String[] {
@@ -679,6 +696,10 @@
public static final int SAMPLING_STRATEGY_RARELY_USED =
FrameworkStatsLog.RUNTIME_APP_OP_ACCESS__SAMPLING_STRATEGY__RARELY_USED;
+ /** @hide */
+ public static final int SAMPLING_STRATEGY_BOOT_TIME_SAMPLING =
+ FrameworkStatsLog.RUNTIME_APP_OP_ACCESS__SAMPLING_STRATEGY__BOOT_TIME_SAMPLING;
+
/**
* Strategies used for message sampling
* @hide
@@ -687,7 +708,8 @@
@IntDef(prefix = {"SAMPLING_STRATEGY_"}, value = {
SAMPLING_STRATEGY_DEFAULT,
SAMPLING_STRATEGY_UNIFORM,
- SAMPLING_STRATEGY_RARELY_USED
+ SAMPLING_STRATEGY_RARELY_USED,
+ SAMPLING_STRATEGY_BOOT_TIME_SAMPLING
})
public @interface SamplingStrategy {}
@@ -1051,9 +1073,20 @@
/** @hide Access telephony call audio */
public static final int OP_ACCESS_CALL_AUDIO = 96;
+ /** @hide Auto-revoke app permissions if app is unused for an extended period */
+ public static final int OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED = 97;
+
+ /**
+ * Whether {@link #OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED} is allowed to be changed by
+ * the installer
+ *
+ * @hide
+ */
+ public static final int OP_AUTO_REVOKE_MANAGED_BY_INSTALLER = 98;
+
/** @hide */
@UnsupportedAppUsage
- public static final int _NUM_OP = 97;
+ public static final int _NUM_OP = 99;
/** Access to coarse location information. */
public static final String OPSTR_COARSE_LOCATION = "android:coarse_location";
@@ -1336,7 +1369,6 @@
@SystemApi
public static final String OPSTR_ACCESS_ACCESSIBILITY = "android:access_accessibility";
/** @hide Read device identifiers */
- @SystemApi
public static final String OPSTR_READ_DEVICE_IDENTIFIERS = "android:read_device_identifiers";
/** @hide Query all packages on device */
public static final String OPSTR_QUERY_ALL_PACKAGES = "android:query_all_packages";
@@ -1348,6 +1380,15 @@
@SystemApi
public static final String OPSTR_ACCESS_CALL_AUDIO = "android:access_call_audio";
+ /** @hide Auto-revoke app permissions if app is unused for an extended period */
+ @SystemApi
+ public static final String OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED =
+ "android:auto_revoke_permissions_if_unused";
+
+ /** @hide Auto-revoke app permissions if app is unused for an extended period */
+ public static final String OPSTR_AUTO_REVOKE_MANAGED_BY_INSTALLER =
+ "android:auto_revoke_managed_by_installer";
+
/** @hide Communicate cross-profile within the same profile group. */
@SystemApi
public static final String OPSTR_INTERACT_ACROSS_PROFILES = "android:interact_across_profiles";
@@ -1437,6 +1478,8 @@
OP_INTERACT_ACROSS_PROFILES,
OP_LOADER_USAGE_STATS,
OP_ACCESS_CALL_AUDIO,
+ OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
+ OP_AUTO_REVOKE_MANAGED_BY_INSTALLER,
};
/**
@@ -1545,6 +1588,8 @@
OP_ACTIVATE_PLATFORM_VPN, // ACTIVATE_PLATFORM_VPN
OP_LOADER_USAGE_STATS, // LOADER_USAGE_STATS
OP_ACCESS_CALL_AUDIO, // ACCESS_CALL_AUDIO
+ OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, //AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ OP_AUTO_REVOKE_MANAGED_BY_INSTALLER, //OP_AUTO_REVOKE_MANAGED_BY_INSTALLER
};
/**
@@ -1648,6 +1693,8 @@
OPSTR_ACTIVATE_PLATFORM_VPN,
OPSTR_LOADER_USAGE_STATS,
OPSTR_ACCESS_CALL_AUDIO,
+ OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
+ OPSTR_AUTO_REVOKE_MANAGED_BY_INSTALLER,
};
/**
@@ -1752,6 +1799,8 @@
"ACTIVATE_PLATFORM_VPN",
"LOADER_USAGE_STATS",
"ACCESS_CALL_AUDIO",
+ "AUTO_REVOKE_PERMISSIONS_IF_UNUSED",
+ "AUTO_REVOKE_MANAGED_BY_INSTALLER",
};
/**
@@ -1857,6 +1906,8 @@
null, // no permission for OP_ACTIVATE_PLATFORM_VPN
android.Manifest.permission.LOADER_USAGE_STATS,
Manifest.permission.ACCESS_CALL_AUDIO,
+ null, // no permission for OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ null, // no permission for OP_AUTO_REVOKE_MANAGED_BY_INSTALLER
};
/**
@@ -1962,110 +2013,114 @@
null, // ACTIVATE_PLATFORM_VPN
null, // LOADER_USAGE_STATS
null, // ACCESS_CALL_AUDIO
+ null, // AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ null, // AUTO_REVOKE_MANAGED_BY_INSTALLER
};
/**
- * This specifies whether each option should allow the system
- * (and system ui) to bypass the user restriction when active.
+ * In which cases should an app be allowed to bypass the {@link #setUserRestriction user
+ * restriction} for a certain app-op.
*/
- private static boolean[] sOpAllowSystemRestrictionBypass = new boolean[] {
- true, //COARSE_LOCATION
- true, //FINE_LOCATION
- false, //GPS
- false, //VIBRATE
- false, //READ_CONTACTS
- false, //WRITE_CONTACTS
- false, //READ_CALL_LOG
- false, //WRITE_CALL_LOG
- false, //READ_CALENDAR
- false, //WRITE_CALENDAR
- true, //WIFI_SCAN
- false, //POST_NOTIFICATION
- false, //NEIGHBORING_CELLS
- false, //CALL_PHONE
- false, //READ_SMS
- false, //WRITE_SMS
- false, //RECEIVE_SMS
- false, //RECEIVE_EMERGECY_SMS
- false, //RECEIVE_MMS
- false, //RECEIVE_WAP_PUSH
- false, //SEND_SMS
- false, //READ_ICC_SMS
- false, //WRITE_ICC_SMS
- false, //WRITE_SETTINGS
- true, //SYSTEM_ALERT_WINDOW
- false, //ACCESS_NOTIFICATIONS
- false, //CAMERA
- false, //RECORD_AUDIO
- false, //PLAY_AUDIO
- false, //READ_CLIPBOARD
- false, //WRITE_CLIPBOARD
- false, //TAKE_MEDIA_BUTTONS
- false, //TAKE_AUDIO_FOCUS
- false, //AUDIO_MASTER_VOLUME
- false, //AUDIO_VOICE_VOLUME
- false, //AUDIO_RING_VOLUME
- false, //AUDIO_MEDIA_VOLUME
- false, //AUDIO_ALARM_VOLUME
- false, //AUDIO_NOTIFICATION_VOLUME
- false, //AUDIO_BLUETOOTH_VOLUME
- false, //WAKE_LOCK
- false, //MONITOR_LOCATION
- false, //MONITOR_HIGH_POWER_LOCATION
- false, //GET_USAGE_STATS
- false, //MUTE_MICROPHONE
- true, //TOAST_WINDOW
- false, //PROJECT_MEDIA
- false, //ACTIVATE_VPN
- false, //WALLPAPER
- false, //ASSIST_STRUCTURE
- false, //ASSIST_SCREENSHOT
- false, //READ_PHONE_STATE
- false, //ADD_VOICEMAIL
- false, // USE_SIP
- false, // PROCESS_OUTGOING_CALLS
- false, // USE_FINGERPRINT
- false, // BODY_SENSORS
- false, // READ_CELL_BROADCASTS
- false, // MOCK_LOCATION
- false, // READ_EXTERNAL_STORAGE
- false, // WRITE_EXTERNAL_STORAGE
- false, // TURN_ON_SCREEN
- false, // GET_ACCOUNTS
- false, // RUN_IN_BACKGROUND
- false, // AUDIO_ACCESSIBILITY_VOLUME
- false, // READ_PHONE_NUMBERS
- false, // REQUEST_INSTALL_PACKAGES
- false, // ENTER_PICTURE_IN_PICTURE_ON_HIDE
- false, // INSTANT_APP_START_FOREGROUND
- false, // ANSWER_PHONE_CALLS
- false, // OP_RUN_ANY_IN_BACKGROUND
- false, // OP_CHANGE_WIFI_STATE
- false, // OP_REQUEST_DELETE_PACKAGES
- false, // OP_BIND_ACCESSIBILITY_SERVICE
- false, // ACCEPT_HANDOVER
- false, // MANAGE_IPSEC_HANDOVERS
- false, // START_FOREGROUND
- true, // BLUETOOTH_SCAN
- false, // USE_BIOMETRIC
- false, // ACTIVITY_RECOGNITION
- false, // SMS_FINANCIAL_TRANSACTIONS
- false, // READ_MEDIA_AUDIO
- false, // WRITE_MEDIA_AUDIO
- false, // READ_MEDIA_VIDEO
- false, // WRITE_MEDIA_VIDEO
- false, // READ_MEDIA_IMAGES
- false, // WRITE_MEDIA_IMAGES
- false, // LEGACY_STORAGE
- false, // ACCESS_ACCESSIBILITY
- false, // READ_DEVICE_IDENTIFIERS
- false, // ACCESS_MEDIA_LOCATION
- false, // QUERY_ALL_PACKAGES
- false, // MANAGE_EXTERNAL_STORAGE
- false, // INTERACT_ACROSS_PROFILES
- false, // ACTIVATE_PLATFORM_VPN
- false, // LOADER_USAGE_STATS
- false, // ACCESS_CALL_AUDIO
+ private static RestrictionBypass[] sOpAllowSystemRestrictionBypass = new RestrictionBypass[] {
+ new RestrictionBypass(true, false), //COARSE_LOCATION
+ new RestrictionBypass(true, false), //FINE_LOCATION
+ null, //GPS
+ null, //VIBRATE
+ null, //READ_CONTACTS
+ null, //WRITE_CONTACTS
+ null, //READ_CALL_LOG
+ null, //WRITE_CALL_LOG
+ null, //READ_CALENDAR
+ null, //WRITE_CALENDAR
+ new RestrictionBypass(true, false), //WIFI_SCAN
+ null, //POST_NOTIFICATION
+ null, //NEIGHBORING_CELLS
+ null, //CALL_PHONE
+ null, //READ_SMS
+ null, //WRITE_SMS
+ null, //RECEIVE_SMS
+ null, //RECEIVE_EMERGECY_SMS
+ null, //RECEIVE_MMS
+ null, //RECEIVE_WAP_PUSH
+ null, //SEND_SMS
+ null, //READ_ICC_SMS
+ null, //WRITE_ICC_SMS
+ null, //WRITE_SETTINGS
+ new RestrictionBypass(true, false), //SYSTEM_ALERT_WINDOW
+ null, //ACCESS_NOTIFICATIONS
+ null, //CAMERA
+ new RestrictionBypass(false, true), //RECORD_AUDIO
+ null, //PLAY_AUDIO
+ null, //READ_CLIPBOARD
+ null, //WRITE_CLIPBOARD
+ null, //TAKE_MEDIA_BUTTONS
+ null, //TAKE_AUDIO_FOCUS
+ null, //AUDIO_MASTER_VOLUME
+ null, //AUDIO_VOICE_VOLUME
+ null, //AUDIO_RING_VOLUME
+ null, //AUDIO_MEDIA_VOLUME
+ null, //AUDIO_ALARM_VOLUME
+ null, //AUDIO_NOTIFICATION_VOLUME
+ null, //AUDIO_BLUETOOTH_VOLUME
+ null, //WAKE_LOCK
+ null, //MONITOR_LOCATION
+ null, //MONITOR_HIGH_POWER_LOCATION
+ null, //GET_USAGE_STATS
+ null, //MUTE_MICROPHONE
+ new RestrictionBypass(true, false), //TOAST_WINDOW
+ null, //PROJECT_MEDIA
+ null, //ACTIVATE_VPN
+ null, //WALLPAPER
+ null, //ASSIST_STRUCTURE
+ null, //ASSIST_SCREENSHOT
+ null, //READ_PHONE_STATE
+ null, //ADD_VOICEMAIL
+ null, // USE_SIP
+ null, // PROCESS_OUTGOING_CALLS
+ null, // USE_FINGERPRINT
+ null, // BODY_SENSORS
+ null, // READ_CELL_BROADCASTS
+ null, // MOCK_LOCATION
+ null, // READ_EXTERNAL_STORAGE
+ null, // WRITE_EXTERNAL_STORAGE
+ null, // TURN_ON_SCREEN
+ null, // GET_ACCOUNTS
+ null, // RUN_IN_BACKGROUND
+ null, // AUDIO_ACCESSIBILITY_VOLUME
+ null, // READ_PHONE_NUMBERS
+ null, // REQUEST_INSTALL_PACKAGES
+ null, // ENTER_PICTURE_IN_PICTURE_ON_HIDE
+ null, // INSTANT_APP_START_FOREGROUND
+ null, // ANSWER_PHONE_CALLS
+ null, // OP_RUN_ANY_IN_BACKGROUND
+ null, // OP_CHANGE_WIFI_STATE
+ null, // OP_REQUEST_DELETE_PACKAGES
+ null, // OP_BIND_ACCESSIBILITY_SERVICE
+ null, // ACCEPT_HANDOVER
+ null, // MANAGE_IPSEC_HANDOVERS
+ null, // START_FOREGROUND
+ new RestrictionBypass(true, false), // BLUETOOTH_SCAN
+ null, // USE_BIOMETRIC
+ null, // ACTIVITY_RECOGNITION
+ null, // SMS_FINANCIAL_TRANSACTIONS
+ null, // READ_MEDIA_AUDIO
+ null, // WRITE_MEDIA_AUDIO
+ null, // READ_MEDIA_VIDEO
+ null, // WRITE_MEDIA_VIDEO
+ null, // READ_MEDIA_IMAGES
+ null, // WRITE_MEDIA_IMAGES
+ null, // LEGACY_STORAGE
+ null, // ACCESS_ACCESSIBILITY
+ null, // READ_DEVICE_IDENTIFIERS
+ null, // ACCESS_MEDIA_LOCATION
+ null, // QUERY_ALL_PACKAGES
+ null, // MANAGE_EXTERNAL_STORAGE
+ null, // INTERACT_ACROSS_PROFILES
+ null, // ACTIVATE_PLATFORM_VPN
+ null, // LOADER_USAGE_STATS
+ null, // ACCESS_CALL_AUDIO
+ null, // AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ null, // AUTO_REVOKE_MANAGED_BY_INSTALLER
};
/**
@@ -2169,6 +2224,8 @@
AppOpsManager.MODE_IGNORED, // ACTIVATE_PLATFORM_VPN
AppOpsManager.MODE_DEFAULT, // LOADER_USAGE_STATS
AppOpsManager.MODE_DEFAULT, // ACCESS_CALL_AUDIO
+ AppOpsManager.MODE_DEFAULT, // OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ AppOpsManager.MODE_ALLOWED, // OP_AUTO_REVOKE_MANAGED_BY_INSTALLER
};
/**
@@ -2276,9 +2333,119 @@
false, // ACTIVATE_PLATFORM_VPN
false, // LOADER_USAGE_STATS
false, // ACCESS_CALL_AUDIO
+ false, // AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ false, // AUTO_REVOKE_MANAGED_BY_INSTALLER
};
/**
+ * This maps each operation to its statsd logging code.
+ */
+ private static int[] sOpToLoggingId = new int[]{
+ AppProtoEnums.APP_OP_COARSE_LOCATION, // OP_COARSE_LOCATION
+ AppProtoEnums.APP_OP_FINE_LOCATION, // OP_FINE_LOCATION
+ AppProtoEnums.APP_OP_GPS, // OP_ID__GPS
+ AppProtoEnums.APP_OP_VIBRATE, // OP_VIBRATE
+ AppProtoEnums.APP_OP_READ_CONTACTS, // OP_READ_CONTACTS
+ AppProtoEnums.APP_OP_WRITE_CONTACTS, // OP_WRITE_CONTACTS
+ AppProtoEnums.APP_OP_READ_CALL_LOG, // OP_READ_CALL_LOG
+ AppProtoEnums.APP_OP_WRITE_CALL_LOG, // OP_WRITE_CALL_LOG
+ AppProtoEnums.APP_OP_READ_CALENDAR, // OP_READ_CALENDAR
+ AppProtoEnums.APP_OP_WRITE_CALENDAR, // OP_WRITE_CALENDAR
+ AppProtoEnums.APP_OP_WIFI_SCAN, // OP_WIFI_SCAN
+ AppProtoEnums.APP_OP_POST_NOTIFICATION, // OP_POST_NOTIFICATION
+ AppProtoEnums.APP_OP_NEIGHBORING_CELLS, // OP_NEIGHBORING_CELLS
+ AppProtoEnums.APP_OP_CALL_PHONE, // OP_CALL_PHONE
+ AppProtoEnums.APP_OP_READ_SMS, // OP_READ_SMS
+ AppProtoEnums.APP_OP_WRITE_SMS, // OP_WRITE_SMS
+ AppProtoEnums.APP_OP_RECEIVE_SMS, // OP_RECEIVE_SMS
+ AppProtoEnums.APP_OP_RECEIVE_EMERGENCY_SMS, // OP_RECEIVE_EMERGENCY_SMS
+ AppProtoEnums.APP_OP_RECEIVE_MMS, // OP_RECEIVE_MMS
+ AppProtoEnums.APP_OP_RECEIVE_WAP_PUSH, // OP_RECEIVE_WAP_PUSH
+ AppProtoEnums.APP_OP_SEND_SMS, // OP_SEND_SMS
+ AppProtoEnums.APP_OP_READ_ICC_SMS, // OP_READ_ICC_SMS
+ AppProtoEnums.APP_OP_WRITE_ICC_SMS, // OP_WRITE_ICC_SMS
+ AppProtoEnums.APP_OP_WRITE_SETTINGS, // OP_WRITE_SETTINGS
+ AppProtoEnums.APP_OP_SYSTEM_ALERT_WINDOW, // OP_SYSTEM_ALERT_WINDOW
+ AppProtoEnums.APP_OP_ACCESS_NOTIFICATIONS, // OP_ACCESS_NOTIFICATIONS
+ AppProtoEnums.APP_OP_CAMERA, // OP_CAMERA
+ AppProtoEnums.APP_OP_RECORD_AUDIO, // OP_RECORD_AUDIO
+ AppProtoEnums.APP_OP_PLAY_AUDIO, // OP_PLAY_AUDIO
+ AppProtoEnums.APP_OP_READ_CLIPBOARD, // OP_READ_CLIPBOARD
+ AppProtoEnums.APP_OP_WRITE_CLIPBOARD, // OP_WRITE_CLIPBOARD
+ AppProtoEnums.APP_OP_TAKE_MEDIA_BUTTONS, // OP_TAKE_MEDIA_BUTTONS
+ AppProtoEnums.APP_OP_TAKE_AUDIO_FOCUS, // OP_TAKE_AUDIO_FOCUS
+ AppProtoEnums.APP_OP_AUDIO_MASTER_VOLUME, // OP_AUDIO_MASTER_VOLUME
+ AppProtoEnums.APP_OP_AUDIO_VOICE_VOLUME, // OP_AUDIO_VOICE_VOLUME
+ AppProtoEnums.APP_OP_AUDIO_RING_VOLUME, // OP_AUDIO_RING_VOLUME
+ AppProtoEnums.APP_OP_AUDIO_MEDIA_VOLUME, // OP_AUDIO_MEDIA_VOLUME
+ AppProtoEnums.APP_OP_AUDIO_ALARM_VOLUME, // OP_AUDIO_ALARM_VOLUME
+ AppProtoEnums.APP_OP_AUDIO_NOTIFICATION_VOLUME, // OP_AUDIO_NOTIFICATION_VOLUME
+ AppProtoEnums.APP_OP_AUDIO_BLUETOOTH_VOLUME, // OP_AUDIO_BLUETOOTH_VOLUME
+ AppProtoEnums.APP_OP_WAKE_LOCK, // OP_WAKE_LOCK
+ AppProtoEnums.APP_OP_MONITOR_LOCATION, // OP_MONITOR_LOCATION
+ AppProtoEnums.APP_OP_MONITOR_HIGH_POWER_LOCATION, // OP_MONITOR_HIGH_POWER_LOCATION
+ AppProtoEnums.APP_OP_GET_USAGE_STATS, // OP_GET_USAGE_STATS
+ AppProtoEnums.APP_OP_MUTE_MICROPHONE, //OP_MUTE_MICROPHONE
+ AppProtoEnums.APP_OP_TOAST_WINDOW, // OP_TOAST_WINDOW
+ AppProtoEnums.APP_OP_PROJECT_MEDIA, // OP_PROJECT_MEDIA
+ AppProtoEnums.APP_OP_ACTIVATE_VPN, // OP_ACTIVATE_VPN
+ AppProtoEnums.APP_OP_WRITE_WALLPAPER, // OP_WRITE_WALLPAPER
+ AppProtoEnums.APP_OP_ASSIST_STRUCTURE, // OP_ASSIST_STRUCTURE
+ AppProtoEnums.APP_OP_ASSIST_SCREENSHOT, // OP_ASSIST_SCREENSHOT
+ AppProtoEnums.APP_OP_READ_PHONE_STATE, // OP_READ_PHONE_STATE
+ AppProtoEnums.APP_OP_ADD_VOICEMAIL, // OP_ADD_VOICEMAIL
+ AppProtoEnums.APP_OP_USE_SIP, // OP_USE_SIP
+ AppProtoEnums.APP_OP_PROCESS_OUTGOING_CALLS, // OP_PROCESS_OUTGOING_CALLS
+ AppProtoEnums.APP_OP_USE_FINGERPRINT, // OP_USE_FINGERPRINT
+ AppProtoEnums.APP_OP_BODY_SENSORS, // OP_BODY_SENSORS
+ AppProtoEnums.APP_OP_READ_CELL_BROADCASTS, // OP_READ_CELL_BROADCASTS
+ AppProtoEnums.APP_OP_MOCK_LOCATION, // OP_MOCK_LOCATION
+ AppProtoEnums.APP_OP_READ_EXTERNAL_STORAGE, // OP_READ_EXTERNAL_STORAGE
+ AppProtoEnums.APP_OP_WRITE_EXTERNAL_STORAGE, // OP_WRITE_EXTERNAL_STORAGE
+ AppProtoEnums.APP_OP_TURN_SCREEN_ON, // OP_TURN_SCREEN_ON
+ AppProtoEnums.APP_OP_GET_ACCOUNTS, // OP_GET_ACCOUNTS
+ AppProtoEnums.APP_OP_RUN_IN_BACKGROUND, // OP_RUN_IN_BACKGROUND
+ AppProtoEnums.APP_OP_AUDIO_ACCESSIBILITY_VOLUME, // OP_AUDIO_ACCESSIBILITY_VOLUME
+ AppProtoEnums.APP_OP_READ_PHONE_NUMBERS, // OP_READ_PHONE_NUMBERS
+ AppProtoEnums.APP_OP_REQUEST_INSTALL_PACKAGES, // OP_REQUEST_INSTALL_PACKAGES
+ AppProtoEnums.APP_OP_PICTURE_IN_PICTURE, // OP_PICTURE_IN_PICTURE
+ AppProtoEnums.APP_OP_INSTANT_APP_START_FOREGROUND, // OP_INSTANT_APP_START_FOREGROUND
+ AppProtoEnums.APP_OP_ANSWER_PHONE_CALLS, // OP_ANSWER_PHONE_CALLS
+ AppProtoEnums.APP_OP_RUN_ANY_IN_BACKGROUND, // OP_RUN_ANY_IN_BACKGROUND
+ AppProtoEnums.APP_OP_CHANGE_WIFI_STATE, // OP_CHANGE_WIFI_STATE
+ AppProtoEnums.APP_OP_REQUEST_DELETE_PACKAGES, // OP_REQUEST_DELETE_PACKAGES
+ AppProtoEnums.APP_OP_BIND_ACCESSIBILITY_SERVICE, // OP_BIND_ACCESSIBILITY_SERVICE
+ AppProtoEnums.APP_OP_ACCEPT_HANDOVER, // OP_ACCEPT_HANDOVER
+ AppProtoEnums.APP_OP_MANAGE_IPSEC_TUNNELS, // OP_MANAGE_IPSEC_TUNNELS
+ AppProtoEnums.APP_OP_START_FOREGROUND, // OP_START_FOREGROUND
+ AppProtoEnums.APP_OP_BLUETOOTH_SCAN, // OP_BLUETOOTH_SCAN
+ AppProtoEnums.APP_OP_USE_BIOMETRIC, // OP_USE_BIOMETRIC
+ AppProtoEnums.APP_OP_ACTIVITY_RECOGNITION, // OP_ACTIVITY_RECOGNITION
+ AppProtoEnums.APP_OP_SMS_FINANCIAL_TRANSACTIONS, // OP_SMS_FINANCIAL_TRANSACTIONS
+ AppProtoEnums.APP_OP_READ_MEDIA_AUDIO, // OP_READ_MEDIA_AUDIO
+ AppProtoEnums.APP_OP_WRITE_MEDIA_AUDIO, // OP_WRITE_MEDIA_AUDIO
+ AppProtoEnums.APP_OP_READ_MEDIA_VIDEO, // OP_READ_MEDIA_VIDEO
+ AppProtoEnums.APP_OP_WRITE_MEDIA_VIDEO, // OP_WRITE_MEDIA_VIDEO
+ AppProtoEnums.APP_OP_READ_MEDIA_IMAGES, // OP_READ_MEDIA_IMAGES
+ AppProtoEnums.APP_OP_WRITE_MEDIA_IMAGES, // OP_WRITE_MEDIA_IMAGES
+ AppProtoEnums.APP_OP_LEGACY_STORAGE, // OP_LEGACY_STORAGE
+ AppProtoEnums.APP_OP_ACCESS_ACCESSIBILITY, // OP_ACCESS_ACCESSIBILITY
+ AppProtoEnums.APP_OP_READ_DEVICE_IDENTIFIERS, // OP_READ_DEVICE_IDENTIFIERS
+ AppProtoEnums.APP_OP_ACCESS_MEDIA_LOCATION, // OP_ACCESS_MEDIA_LOCATION
+ AppProtoEnums.APP_OP_QUERY_ALL_PACKAGES, // OP_QUERY_ALL_PACKAGES
+ AppProtoEnums.APP_OP_MANAGE_EXTERNAL_STORAGE, // OP_MANAGE_EXTERNAL_STORAGE
+ AppProtoEnums.APP_OP_INTERACT_ACROSS_PROFILES, // OP_INTERACT_ACROSS_PROFILES
+ AppProtoEnums.APP_OP_ACTIVATE_PLATFORM_VPN, // OP_ACTIVATE_PLATFORM_VPN
+ AppProtoEnums.APP_OP_LOADER_USAGE_STATS, // OP_LOADER_USAGE_STATS
+ AppProtoEnums.APP_OP_ACCESS_CALL_AUDIO, // OP_ACCESS_CALL_AUDIO
+ AppProtoEnums.APP_OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
+ // OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED
+ AppProtoEnums.APP_OP_AUTO_REVOKE_MANAGED_BY_INSTALLER
+ //OP_AUTO_REVOKE_MANAGED_BY_INSTALLER
+ };
+
+
+ /**
* Mapping from an app op name to the app op code.
*/
private static HashMap<String, Integer> sOpStrToOp = new HashMap<>();
@@ -2319,6 +2486,10 @@
throw new IllegalStateException("sOpToString length " + sOpToString.length
+ " should be " + _NUM_OP);
}
+ if (sOpToLoggingId.length != _NUM_OP) {
+ throw new IllegalStateException("sOpToLoggingId length " + sOpToLoggingId.length
+ + " should be " + _NUM_OP);
+ }
if (sOpNames.length != _NUM_OP) {
throw new IllegalStateException("sOpNames length " + sOpNames.length
+ " should be " + _NUM_OP);
@@ -2403,6 +2574,15 @@
}
/**
+ * Retrieve a logging id for the operation.
+ *
+ * @hide
+ */
+ public static int opToLoggingId(int op) {
+ return sOpToLoggingId[op];
+ }
+
+ /**
* @hide
*/
public static int strDebugOpToOp(String op) {
@@ -2459,11 +2639,11 @@
}
/**
- * Retrieve whether the op allows the system (and system ui) to
- * bypass the user restriction.
+ * Retrieve whether the op allows to bypass the user restriction.
+ *
* @hide
*/
- public static boolean opAllowSystemBypassRestriction(int op) {
+ public static RestrictionBypass opAllowSystemBypassRestriction(int op) {
return sOpAllowSystemRestrictionBypass[op];
}
@@ -2510,6 +2690,29 @@
}
/**
+ * When to not enforce {@link #setUserRestriction restrictions}.
+ *
+ * @hide
+ */
+ public static class RestrictionBypass {
+ /** Does the app need to be privileged to bypass the restriction */
+ public boolean isPrivileged;
+
+ /**
+ * Does the app need to have the EXEMPT_FROM_AUDIO_RESTRICTIONS permission to bypass the
+ * restriction
+ */
+ public boolean isRecordAudioRestrictionExcept;
+
+ public RestrictionBypass(boolean isPrivileged, boolean isRecordAudioRestrictionExcept) {
+ this.isPrivileged = isPrivileged;
+ this.isRecordAudioRestrictionExcept = isRecordAudioRestrictionExcept;
+ }
+
+ public static RestrictionBypass UNRESTRICTED = new RestrictionBypass(true, true);
+ }
+
+ /**
* Class holding all of the operation information associated with an app.
* @hide
*/
@@ -2601,23 +2804,23 @@
private @IntRange(from = 0) int mUid;
/** Package of the proxy that noted the op */
private @Nullable String mPackageName;
- /** ID of the feature of the proxy that noted the op */
- private @Nullable String mFeatureId;
+ /** Attribution tag of the proxy that noted the op */
+ private @Nullable String mAttributionTag;
/**
* Reinit existing object with new state.
*
* @param uid UID of the proxy app that noted the op
* @param packageName Package of the proxy that noted the op
- * @param featureId ID of the feature of the proxy that noted the op
+ * @param attributionTag attribution tag of the proxy that noted the op
*
* @hide
*/
public void reinit(@IntRange(from = 0) int uid, @Nullable String packageName,
- @Nullable String featureId) {
+ @Nullable String attributionTag) {
mUid = Preconditions.checkArgumentNonnegative(uid);
mPackageName = packageName;
- mFeatureId = featureId;
+ mAttributionTag = attributionTag;
}
@@ -2642,21 +2845,21 @@
* UID of the proxy app that noted the op
* @param packageName
* Package of the proxy that noted the op
- * @param featureId
- * ID of the feature of the proxy that noted the op
+ * @param attributionTag
+ * Attribution tag of the proxy that noted the op
* @hide
*/
@DataClass.Generated.Member
public OpEventProxyInfo(
@IntRange(from = 0) int uid,
@Nullable String packageName,
- @Nullable String featureId) {
+ @Nullable String attributionTag) {
this.mUid = uid;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mUid,
"from", 0);
this.mPackageName = packageName;
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
// onConstructed(); // You can define this method to get a callback
}
@@ -2670,7 +2873,7 @@
public OpEventProxyInfo(@NonNull OpEventProxyInfo orig) {
mUid = orig.mUid;
mPackageName = orig.mPackageName;
- mFeatureId = orig.mFeatureId;
+ mAttributionTag = orig.mAttributionTag;
}
/**
@@ -2690,11 +2893,11 @@
}
/**
- * ID of the feature of the proxy that noted the op
+ * Attribution tag of the proxy that noted the op
*/
@DataClass.Generated.Member
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getAttributionTag() {
+ return mAttributionTag;
}
@Override
@@ -2705,11 +2908,11 @@
byte flg = 0;
if (mPackageName != null) flg |= 0x2;
- if (mFeatureId != null) flg |= 0x4;
+ if (mAttributionTag != null) flg |= 0x4;
dest.writeByte(flg);
dest.writeInt(mUid);
if (mPackageName != null) dest.writeString(mPackageName);
- if (mFeatureId != null) dest.writeString(mFeatureId);
+ if (mAttributionTag != null) dest.writeString(mAttributionTag);
}
@Override
@@ -2726,14 +2929,14 @@
byte flg = in.readByte();
int uid = in.readInt();
String packageName = (flg & 0x2) == 0 ? null : in.readString();
- String featureId = (flg & 0x4) == 0 ? null : in.readString();
+ String attributionTag = (flg & 0x4) == 0 ? null : in.readString();
this.mUid = uid;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mUid,
"from", 0);
this.mPackageName = packageName;
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
// onConstructed(); // You can define this method to get a callback
}
@@ -2757,7 +2960,7 @@
time = 1576814974615L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/app/AppOpsManager.java",
- inputSignatures = "private @android.annotation.IntRange(from=0L) int mUid\nprivate @android.annotation.Nullable java.lang.String mPackageName\nprivate @android.annotation.Nullable java.lang.String mFeatureId\npublic void reinit(int,java.lang.String,java.lang.String)\nclass OpEventProxyInfo extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true, genHiddenCopyConstructor=true)")
+ inputSignatures = "private @android.annotation.IntRange(from=0L) int mUid\nprivate @android.annotation.Nullable java.lang.String mPackageName\nprivate @android.annotation.Nullable java.lang.String mAttributionTag\npublic void reinit(int,java.lang.String,java.lang.String)\nclass OpEventProxyInfo extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true, genHiddenCopyConstructor=true)")
@Deprecated
private void __metadata() {}
*/
@@ -2956,7 +3159,7 @@
/**
* Last {@link #noteOp} and {@link #startOp} events performed for a single op and a specific
- * {@link Context#createFeatureContext(String) feature} for all uidModes and opFlags.
+ * {@link Context#createAttributionContext(String) attribution} for all uidModes and opFlags.
*
* @hide
*/
@@ -2965,7 +3168,7 @@
@Immutable
// @DataClass(genHiddenConstructor = true) codegen verifier is broken
@DataClass.Suppress({"getAccessEvents", "getRejectEvents", "getOp"})
- public static final class OpFeatureEntry implements Parcelable {
+ public static final class AttributedOpEntry implements Parcelable {
/** The code of the op */
private final @IntRange(from = 0, to = _NUM_OP - 1) int mOp;
/** Whether the op is running */
@@ -3264,8 +3467,8 @@
}
/**
- * Gets the proxy info of the app that performed the last access on behalf of this feature
- * and as a result blamed the op on this app.
+ * Gets the proxy info of the app that performed the last access on behalf of this
+ * attribution and as a result blamed the op on this attribution.
*
* @param flags The op flags
*
@@ -3282,7 +3485,7 @@
/**
* Gets the proxy info of the app that performed the last foreground access on behalf of
- * this feature and as a result blamed the op on this app.
+ * this attribution and as a result blamed the op on this attribution.
*
* @param flags The op flags
*
@@ -3300,7 +3503,7 @@
/**
* Gets the proxy info of the app that performed the last background access on behalf of
- * this feature and as a result blamed the op on this app.
+ * this attribution and as a result blamed the op on this attribution.
*
* @param flags The op flags
*
@@ -3317,8 +3520,8 @@
}
/**
- * Gets the proxy info of the app that performed the last access on behalf of this feature
- * and as a result blamed the op on this app.
+ * Gets the proxy info of the app that performed the last access on behalf of this
+ * attribution and as a result blamed the op on this attribution.
*
* @param fromUidState The lowest UID state for which to query
* @param toUidState The highest UID state for which to query (inclusive)
@@ -3393,7 +3596,7 @@
/**
- * Creates a new OpFeatureEntry.
+ * Creates a new OpAttributionEntry.
*
* @param op
* The code of the op
@@ -3406,7 +3609,7 @@
* @hide
*/
@DataClass.Generated.Member
- public OpFeatureEntry(
+ public AttributedOpEntry(
@IntRange(from = 0, to = _NUM_OP - 1) int op,
boolean running,
@Nullable LongSparseArray<NoteOpEvent> accessEvents,
@@ -3476,7 +3679,7 @@
/** @hide */
@SuppressWarnings({"unchecked", "RedundantCast"})
@DataClass.Generated.Member
- /* package-private */ OpFeatureEntry(@NonNull Parcel in) {
+ /* package-private */ AttributedOpEntry(@NonNull Parcel in) {
// You can override field unparcelling by defining methods like:
// static FieldType unparcelFieldName(Parcel in) { ... }
@@ -3499,16 +3702,16 @@
}
@DataClass.Generated.Member
- public static final @NonNull Parcelable.Creator<OpFeatureEntry> CREATOR
- = new Parcelable.Creator<OpFeatureEntry>() {
+ public static final @NonNull Parcelable.Creator<AttributedOpEntry> CREATOR
+ = new Parcelable.Creator<AttributedOpEntry>() {
@Override
- public OpFeatureEntry[] newArray(int size) {
- return new OpFeatureEntry[size];
+ public AttributedOpEntry[] newArray(int size) {
+ return new AttributedOpEntry[size];
}
@Override
- public OpFeatureEntry createFromParcel(@NonNull Parcel in) {
- return new OpFeatureEntry(in);
+ public AttributedOpEntry createFromParcel(@NonNull Parcel in) {
+ return new AttributedOpEntry(in);
}
};
@@ -3517,7 +3720,7 @@
time = 1574809856239L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/app/AppOpsManager.java",
- inputSignatures = "private final @android.annotation.IntRange(from=0L, to=_NUM_OP - 1) int mOp\nprivate final boolean mRunning\nprivate final @com.android.internal.util.DataClass.ParcelWith(android.app.OpFeatureEntry.LongSparseArrayParceling.class) @android.annotation.Nullable android.util.LongSparseArray<android.app.NoteOpEvent> mAccessEvents\nprivate final @com.android.internal.util.DataClass.ParcelWith(android.app.OpFeatureEntry.LongSparseArrayParceling.class) @android.annotation.Nullable android.util.LongSparseArray<android.app.NoteOpEvent> mRejectEvents\npublic @android.annotation.NonNull android.util.ArraySet<java.lang.Long> collectKeys()\npublic @android.app.UidState int getLastAccessUidState(int)\npublic @android.app.UidState int getLastForegroundAccessUidState(int)\npublic @android.app.UidState int getLastBackgroundAccessUidState(int)\npublic @android.app.UidState int getLastRejectUidState(int)\npublic @android.app.UidState int getLastForegroundRejectUidState(int)\npublic @android.app.UidState int getLastBackgroundRejectUidState(int)\npublic long getAccessTime(int,int)\npublic long getRejectTime(int,int)\npublic long getDuration(int,int)\npublic int getProxyUid(int,int)\npublic @android.annotation.Nullable java.lang.String getProxyPackageName(int,int)\npublic @android.annotation.Nullable java.lang.String getProxyFeatureId(int,int)\nclass OpFeatureEntry extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true)")
+ inputSignatures = "private final @android.annotation.IntRange(from=0L, to=_NUM_OP - 1) int mOp\nprivate final boolean mRunning\nprivate final @com.android.internal.util.DataClass.ParcelWith(android.app.OpAttributionEntry.LongSparseArrayParceling.class) @android.annotation.Nullable android.util.LongSparseArray<android.app.NoteOpEvent> mAccessEvents\nprivate final @com.android.internal.util.DataClass.ParcelWith(android.app.OpAttributionEntry.LongSparseArrayParceling.class) @android.annotation.Nullable android.util.LongSparseArray<android.app.NoteOpEvent> mRejectEvents\npublic @android.annotation.NonNull android.util.ArraySet<java.lang.Long> collectKeys()\npublic @android.app.UidState int getLastAccessUidState(int)\npublic @android.app.UidState int getLastForegroundAccessUidState(int)\npublic @android.app.UidState int getLastBackgroundAccessUidState(int)\npublic @android.app.UidState int getLastRejectUidState(int)\npublic @android.app.UidState int getLastForegroundRejectUidState(int)\npublic @android.app.UidState int getLastBackgroundRejectUidState(int)\npublic long getAccessTime(int,int)\npublic long getRejectTime(int,int)\npublic long getDuration(int,int)\npublic int getProxyUid(int,int)\npublic @android.annotation.Nullable java.lang.String getProxyPackageName(int,int)\npublic @android.annotation.Nullable java.lang.String getProxyAttributionTag(int,int)\nclass OpAttributionEntry extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true)")
@Deprecated
private void __metadata() {}
*/
@@ -3543,8 +3746,8 @@
private final @IntRange(from = 0, to = _NUM_OP - 1) int mOp;
/** The mode of the op */
private final @Mode int mMode;
- /** The features that have been used when checking the op */
- private final @NonNull Map<String, OpFeatureEntry> mFeatures;
+ /** The attributed entries by attribution tag */
+ private final @NonNull Map<String, AttributedOpEntry> mAttributedOpEntries;
/**
* @hide
@@ -3585,7 +3788,7 @@
* @see #getLastAccessForegroundTime(int)
* @see #getLastAccessBackgroundTime(int)
* @see #getLastAccessTime(int, int, int)
- * @see OpFeatureEntry#getLastAccessTime(int)
+ * @see AttributedOpEntry#getLastAccessTime(int)
*/
public long getLastAccessTime(@OpFlags int flags) {
return getLastAccessTime(MAX_PRIORITY_UID_STATE, MIN_PRIORITY_UID_STATE, flags);
@@ -3602,7 +3805,7 @@
* @see #getLastAccessTime(int)
* @see #getLastAccessBackgroundTime(int)
* @see #getLastAccessTime(int, int, int)
- * @see OpFeatureEntry#getLastAccessForegroundTime(int)
+ * @see AttributedOpEntry#getLastAccessForegroundTime(int)
*/
public long getLastAccessForegroundTime(@OpFlags int flags) {
return getLastAccessTime(MAX_PRIORITY_UID_STATE, resolveFirstUnrestrictedUidState(mOp),
@@ -3620,7 +3823,7 @@
* @see #getLastAccessTime(int)
* @see #getLastAccessForegroundTime(int)
* @see #getLastAccessTime(int, int, int)
- * @see OpFeatureEntry#getLastAccessBackgroundTime(int)
+ * @see AttributedOpEntry#getLastAccessBackgroundTime(int)
*/
public long getLastAccessBackgroundTime(@OpFlags int flags) {
return getLastAccessTime(resolveLastRestrictedUidState(mOp), MIN_PRIORITY_UID_STATE,
@@ -3637,13 +3840,14 @@
private @Nullable NoteOpEvent getLastAccessEvent(@UidState int fromUidState,
@UidState int toUidState, @OpFlags int flags) {
NoteOpEvent lastAccessEvent = null;
- for (OpFeatureEntry featureEntry : mFeatures.values()) {
- NoteOpEvent lastFeatureAccessEvent = featureEntry.getLastAccessEvent(fromUidState,
- toUidState, flags);
+ for (AttributedOpEntry attributionEntry : mAttributedOpEntries.values()) {
+ NoteOpEvent lastAttributionAccessEvent = attributionEntry.getLastAccessEvent(
+ fromUidState, toUidState, flags);
- if (lastAccessEvent == null || (lastFeatureAccessEvent != null
- && lastFeatureAccessEvent.getNoteTime() > lastAccessEvent.getNoteTime())) {
- lastAccessEvent = lastFeatureAccessEvent;
+ if (lastAccessEvent == null || (lastAttributionAccessEvent != null
+ && lastAttributionAccessEvent.getNoteTime()
+ > lastAccessEvent.getNoteTime())) {
+ lastAccessEvent = lastAttributionAccessEvent;
}
}
@@ -3663,7 +3867,7 @@
* @see #getLastAccessTime(int)
* @see #getLastAccessForegroundTime(int)
* @see #getLastAccessBackgroundTime(int)
- * @see OpFeatureEntry#getLastAccessTime(int, int, int)
+ * @see AttributedOpEntry#getLastAccessTime(int, int, int)
*/
public long getLastAccessTime(@UidState int fromUidState, @UidState int toUidState,
@OpFlags int flags) {
@@ -3699,7 +3903,7 @@
* @see #getLastRejectForegroundTime(int)
* @see #getLastRejectBackgroundTime(int)
* @see #getLastRejectTime(int, int, int)
- * @see OpFeatureEntry#getLastRejectTime(int)
+ * @see AttributedOpEntry#getLastRejectTime(int)
*/
public long getLastRejectTime(@OpFlags int flags) {
return getLastRejectTime(MAX_PRIORITY_UID_STATE, MIN_PRIORITY_UID_STATE, flags);
@@ -3716,7 +3920,7 @@
* @see #getLastRejectTime(int)
* @see #getLastRejectBackgroundTime(int)
* @see #getLastRejectTime(int, int, int)
- * @see OpFeatureEntry#getLastRejectForegroundTime(int)
+ * @see AttributedOpEntry#getLastRejectForegroundTime(int)
*/
public long getLastRejectForegroundTime(@OpFlags int flags) {
return getLastRejectTime(MAX_PRIORITY_UID_STATE, resolveFirstUnrestrictedUidState(mOp),
@@ -3734,7 +3938,7 @@
* @see #getLastRejectTime(int)
* @see #getLastRejectForegroundTime(int)
* @see #getLastRejectTime(int, int, int)
- * @see OpFeatureEntry#getLastRejectBackgroundTime(int)
+ * @see AttributedOpEntry#getLastRejectBackgroundTime(int)
*/
public long getLastRejectBackgroundTime(@OpFlags int flags) {
return getLastRejectTime(resolveLastRestrictedUidState(mOp), MIN_PRIORITY_UID_STATE,
@@ -3751,13 +3955,14 @@
private @Nullable NoteOpEvent getLastRejectEvent(@UidState int fromUidState,
@UidState int toUidState, @OpFlags int flags) {
NoteOpEvent lastAccessEvent = null;
- for (OpFeatureEntry featureEntry : mFeatures.values()) {
- NoteOpEvent lastFeatureAccessEvent = featureEntry.getLastRejectEvent(fromUidState,
- toUidState, flags);
+ for (AttributedOpEntry attributionEntry : mAttributedOpEntries.values()) {
+ NoteOpEvent lastAttributionAccessEvent = attributionEntry.getLastRejectEvent(
+ fromUidState, toUidState, flags);
- if (lastAccessEvent == null || (lastFeatureAccessEvent != null
- && lastFeatureAccessEvent.getNoteTime() > lastAccessEvent.getNoteTime())) {
- lastAccessEvent = lastFeatureAccessEvent;
+ if (lastAccessEvent == null || (lastAttributionAccessEvent != null
+ && lastAttributionAccessEvent.getNoteTime()
+ > lastAccessEvent.getNoteTime())) {
+ lastAccessEvent = lastAttributionAccessEvent;
}
}
@@ -3778,7 +3983,7 @@
* @see #getLastRejectForegroundTime(int)
* @see #getLastRejectBackgroundTime(int)
* @see #getLastRejectTime(int, int, int)
- * @see OpFeatureEntry#getLastRejectTime(int, int, int)
+ * @see AttributedOpEntry#getLastRejectTime(int, int, int)
*/
public long getLastRejectTime(@UidState int fromUidState, @UidState int toUidState,
@OpFlags int flags) {
@@ -3794,8 +3999,8 @@
* @return Whether the operation is running.
*/
public boolean isRunning() {
- for (OpFeatureEntry opFeatureEntry : mFeatures.values()) {
- if (opFeatureEntry.isRunning()) {
+ for (AttributedOpEntry opAttributionEntry : mAttributedOpEntries.values()) {
+ if (opAttributionEntry.isRunning()) {
return true;
}
}
@@ -3821,7 +4026,7 @@
* @see #getLastForegroundDuration(int)
* @see #getLastBackgroundDuration(int)
* @see #getLastDuration(int, int, int)
- * @see OpFeatureEntry#getLastDuration(int)
+ * @see AttributedOpEntry#getLastDuration(int)
*/
public long getLastDuration(@OpFlags int flags) {
return getLastDuration(MAX_PRIORITY_UID_STATE, MIN_PRIORITY_UID_STATE, flags);
@@ -3837,7 +4042,7 @@
* @see #getLastDuration(int)
* @see #getLastBackgroundDuration(int)
* @see #getLastDuration(int, int, int)
- * @see OpFeatureEntry#getLastForegroundDuration(int)
+ * @see AttributedOpEntry#getLastForegroundDuration(int)
*/
public long getLastForegroundDuration(@OpFlags int flags) {
return getLastDuration(MAX_PRIORITY_UID_STATE, resolveFirstUnrestrictedUidState(mOp),
@@ -3854,7 +4059,7 @@
* @see #getLastDuration(int)
* @see #getLastForegroundDuration(int)
* @see #getLastDuration(int, int, int)
- * @see OpFeatureEntry#getLastBackgroundDuration(int)
+ * @see AttributedOpEntry#getLastBackgroundDuration(int)
*/
public long getLastBackgroundDuration(@OpFlags int flags) {
return getLastDuration(resolveLastRestrictedUidState(mOp), MIN_PRIORITY_UID_STATE,
@@ -3873,7 +4078,7 @@
* @see #getLastDuration(int)
* @see #getLastForegroundDuration(int)
* @see #getLastBackgroundDuration(int)
- * @see OpFeatureEntry#getLastDuration(int, int, int)
+ * @see AttributedOpEntry#getLastDuration(int, int, int)
*/
public long getLastDuration(@UidState int fromUidState, @UidState int toUidState,
@OpFlags int flags) {
@@ -3948,7 +4153,7 @@
* @see #getLastForegroundProxyInfo(int)
* @see #getLastBackgroundProxyInfo(int)
* @see #getLastProxyInfo(int, int, int)
- * @see OpFeatureEntry#getLastProxyInfo(int)
+ * @see AttributedOpEntry#getLastProxyInfo(int)
*/
public @Nullable OpEventProxyInfo getLastProxyInfo(@OpFlags int flags) {
return getLastProxyInfo(MAX_PRIORITY_UID_STATE, MIN_PRIORITY_UID_STATE, flags);
@@ -3965,7 +4170,7 @@
* @see #getLastProxyInfo(int)
* @see #getLastBackgroundProxyInfo(int)
* @see #getLastProxyInfo(int, int, int)
- * @see OpFeatureEntry#getLastForegroundProxyInfo(int)
+ * @see AttributedOpEntry#getLastForegroundProxyInfo(int)
*/
public @Nullable OpEventProxyInfo getLastForegroundProxyInfo(@OpFlags int flags) {
return getLastProxyInfo(MAX_PRIORITY_UID_STATE, resolveFirstUnrestrictedUidState(mOp),
@@ -3983,7 +4188,7 @@
* @see #getLastProxyInfo(int)
* @see #getLastForegroundProxyInfo(int)
* @see #getLastProxyInfo(int, int, int)
- * @see OpFeatureEntry#getLastBackgroundProxyInfo(int)
+ * @see AttributedOpEntry#getLastBackgroundProxyInfo(int)
*/
public @Nullable OpEventProxyInfo getLastBackgroundProxyInfo(@OpFlags int flags) {
return getLastProxyInfo(resolveLastRestrictedUidState(mOp), MIN_PRIORITY_UID_STATE,
@@ -4003,7 +4208,7 @@
* @see #getLastProxyInfo(int)
* @see #getLastForegroundProxyInfo(int)
* @see #getLastBackgroundProxyInfo(int)
- * @see OpFeatureEntry#getLastProxyInfo(int, int, int)
+ * @see AttributedOpEntry#getLastProxyInfo(int, int, int)
*/
public @Nullable OpEventProxyInfo getLastProxyInfo(@UidState int fromUidState,
@UidState int toUidState, @OpFlags int flags) {
@@ -4037,15 +4242,15 @@
* The code of the op
* @param mode
* The mode of the op
- * @param features
- * The features that have been used when checking the op
+ * @param attributedOpEntries
+ * The attributions that have been used when noting the op
* @hide
*/
@DataClass.Generated.Member
public OpEntry(
@IntRange(from = 0, to = _NUM_OP - 1) int op,
@Mode int mode,
- @NonNull Map<String,OpFeatureEntry> features) {
+ @NonNull Map<String, AttributedOpEntry> attributedOpEntries) {
this.mOp = op;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mOp,
@@ -4054,9 +4259,9 @@
this.mMode = mode;
com.android.internal.util.AnnotationValidations.validate(
Mode.class, null, mMode);
- this.mFeatures = features;
+ this.mAttributedOpEntries = attributedOpEntries;
com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, mFeatures);
+ NonNull.class, null, mAttributedOpEntries);
// onConstructed(); // You can define this method to get a callback
}
@@ -4070,14 +4275,14 @@
}
/**
- * The features that have been used when checking the op keyed by id of the feature.
+ * The attributed entries keyed by attribution tag.
*
- * @see Context#createFeatureContext(String)
+ * @see Context#createAttributionContext(String)
* @see #noteOp(String, int, String, String, String)
*/
@DataClass.Generated.Member
- public @NonNull Map<String,OpFeatureEntry> getFeatures() {
- return mFeatures;
+ public @NonNull Map<String, AttributedOpEntry> getAttributedOpEntries() {
+ return mAttributedOpEntries;
}
@Override
@@ -4088,7 +4293,7 @@
dest.writeInt(mOp);
dest.writeInt(mMode);
- dest.writeMap(mFeatures);
+ dest.writeMap(mAttributedOpEntries);
}
@Override
@@ -4104,8 +4309,8 @@
int op = in.readInt();
int mode = in.readInt();
- Map<String,OpFeatureEntry> features = new java.util.LinkedHashMap<>();
- in.readMap(features, OpFeatureEntry.class.getClassLoader());
+ Map<String, AttributedOpEntry> attributions = new java.util.LinkedHashMap<>();
+ in.readMap(attributions, AttributedOpEntry.class.getClassLoader());
this.mOp = op;
com.android.internal.util.AnnotationValidations.validate(
@@ -4115,9 +4320,9 @@
this.mMode = mode;
com.android.internal.util.AnnotationValidations.validate(
Mode.class, null, mMode);
- this.mFeatures = features;
+ this.mAttributedOpEntries = attributions;
com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, mFeatures);
+ NonNull.class, null, mAttributedOpEntries);
// onConstructed(); // You can define this method to get a callback
}
@@ -4141,7 +4346,7 @@
time = 1574809856259L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/app/AppOpsManager.java",
- inputSignatures = "private final @android.annotation.IntRange(from=0L, to=_NUM_OP - 1) int mOp\nprivate final @android.app.Mode int mMode\nprivate final @android.annotation.NonNull java.util.Map<java.lang.String,android.app.OpFeatureEntry> mFeatures\npublic @android.annotation.UnsupportedAppUsage(maxTargetSdk=Build.VERSION_CODES.Q, publicAlternatives=\"{@code \" + \"#getOpStr()}\") int getOp()\npublic @android.annotation.NonNull java.lang.String getOpStr()\npublic @java.lang.Deprecated @android.annotation.UnsupportedAppUsage(maxTargetSdk=Build.VERSION_CODES.Q, publicAlternatives=\"{@code \" + \"#getAccessTime(int, int)}\") long getTime()\npublic @java.lang.Deprecated long getLastAccessTime(int)\npublic @java.lang.Deprecated long getLastAccessForegroundTime(int)\npublic @java.lang.Deprecated long getLastAccessBackgroundTime(int)\npublic @java.lang.Deprecated long getLastAccessTime(int,int,int)\npublic @java.lang.Deprecated @android.annotation.UnsupportedAppUsage(maxTargetSdk=Build.VERSION_CODES.Q, publicAlternatives=\"{@code \" + \"#getLastRejectTime(int, int, int)}\") long getRejectTime()\npublic @java.lang.Deprecated long getLastRejectTime(int)\npublic @java.lang.Deprecated long getLastRejectForegroundTime(int)\npublic @java.lang.Deprecated long getLastRejectBackgroundTime(int)\npublic @java.lang.Deprecated long getLastRejectTime(int,int,int)\npublic long getAccessTime(int,int)\npublic long getRejectTime(int,int)\npublic boolean isRunning()\nprivate android.app.NoteOpEvent getLastAccessEvent(int,int,int)\npublic @java.lang.Deprecated long getDuration()\npublic @java.lang.Deprecated long getLastForegroundDuration(int)\npublic @java.lang.Deprecated long getLastBackgroundDuration(int)\npublic @java.lang.Deprecated long getLastDuration(int,int,int)\npublic @java.lang.Deprecated int getProxyUid()\npublic @java.lang.Deprecated @android.annotation.Nullable java.lang.String getProxyPackageName()\nprivate @android.app.UidState int getLastAccessUidStateForFlagsInStatesOfAllFeatures(int,int,int)\npublic @android.app.UidState int getLastAccessUidState(int)\npublic @android.app.UidState int getLastForegroundAccessUidState(int)\npublic @android.app.UidState int getLastBackgroundAccessUidState(int)\nprivate @android.app.UidState int getLastRejectUidStateForFlagsInStatesOfAllFeatures(int,int,int)\npublic @android.app.UidState int getLastRejectUidState(int)\npublic @android.app.UidState int getLastForegroundRejectUidState(int)\npublic @android.app.UidState int getLastBackgroundRejectUidState(int)\npublic long getDuration(int,int)\npublic int getProxyUid(int,int)\nprivate int getProxyUid(int,int,int)\npublic @android.annotation.Nullable java.lang.String getProxyPackageName(int,int)\nprivate @android.annotation.Nullable java.lang.String getProxyPackageName(int,int,int)\nclass OpEntry extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true)")
+ inputSignatures = "private final @android.annotation.IntRange(from=0L, to=_NUM_OP - 1) int mOp\nprivate final @android.app.Mode int mMode\nprivate final @android.annotation.NonNull java.util.Map<java.lang.String,android.app.OpAttributionEntry> mAttributions\npublic @android.annotation.UnsupportedAppUsage(maxTargetSdk=Build.VERSION_CODES.Q, publicAlternatives=\"{@code \" + \"#getOpStr()}\") int getOp()\npublic @android.annotation.NonNull java.lang.String getOpStr()\npublic @java.lang.Deprecated @android.annotation.UnsupportedAppUsage(maxTargetSdk=Build.VERSION_CODES.Q, publicAlternatives=\"{@code \" + \"#getAccessTime(int, int)}\") long getTime()\npublic @java.lang.Deprecated long getLastAccessTime(int)\npublic @java.lang.Deprecated long getLastAccessForegroundTime(int)\npublic @java.lang.Deprecated long getLastAccessBackgroundTime(int)\npublic @java.lang.Deprecated long getLastAccessTime(int,int,int)\npublic @java.lang.Deprecated @android.annotation.UnsupportedAppUsage(maxTargetSdk=Build.VERSION_CODES.Q, publicAlternatives=\"{@code \" + \"#getLastRejectTime(int, int, int)}\") long getRejectTime()\npublic @java.lang.Deprecated long getLastRejectTime(int)\npublic @java.lang.Deprecated long getLastRejectForegroundTime(int)\npublic @java.lang.Deprecated long getLastRejectBackgroundTime(int)\npublic @java.lang.Deprecated long getLastRejectTime(int,int,int)\npublic long getAccessTime(int,int)\npublic long getRejectTime(int,int)\npublic boolean isRunning()\nprivate android.app.NoteOpEvent getLastAccessEvent(int,int,int)\npublic @java.lang.Deprecated long getDuration()\npublic @java.lang.Deprecated long getLastForegroundDuration(int)\npublic @java.lang.Deprecated long getLastBackgroundDuration(int)\npublic @java.lang.Deprecated long getLastDuration(int,int,int)\npublic @java.lang.Deprecated int getProxyUid()\npublic @java.lang.Deprecated @android.annotation.Nullable java.lang.String getProxyPackageName()\nprivate @android.app.UidState int getLastAccessUidStateForFlagsInStatesOfAllAttributions(int,int,int)\npublic @android.app.UidState int getLastAccessUidState(int)\npublic @android.app.UidState int getLastForegroundAccessUidState(int)\npublic @android.app.UidState int getLastBackgroundAccessUidState(int)\nprivate @android.app.UidState int getLastRejectUidStateForFlagsInStatesOfAllAttributions(int,int,int)\npublic @android.app.UidState int getLastRejectUidState(int)\npublic @android.app.UidState int getLastForegroundRejectUidState(int)\npublic @android.app.UidState int getLastBackgroundRejectUidState(int)\npublic long getDuration(int,int)\npublic int getProxyUid(int,int)\nprivate int getProxyUid(int,int,int)\npublic @android.annotation.Nullable java.lang.String getProxyPackageName(int,int)\nprivate @android.annotation.Nullable java.lang.String getProxyPackageName(int,int,int)\nclass OpEntry extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true)")
@Deprecated
private void __metadata() {}
*/
@@ -4157,7 +4362,7 @@
void visitHistoricalOps(@NonNull HistoricalOps ops);
void visitHistoricalUidOps(@NonNull HistoricalUidOps ops);
void visitHistoricalPackageOps(@NonNull HistoricalPackageOps ops);
- void visitHistoricalFeatureOps(@NonNull HistoricalFeatureOps ops);
+ void visitHistoricalAttributionOps(@NonNull AttributedHistoricalOps ops);
void visitHistoricalOp(@NonNull HistoricalOp ops);
}
@@ -4170,7 +4375,7 @@
@IntDef(flag = true, prefix = { "FILTER_BY_" }, value = {
FILTER_BY_UID,
FILTER_BY_PACKAGE_NAME,
- FILTER_BY_FEATURE_ID,
+ FILTER_BY_ATTRIBUTION_TAG,
FILTER_BY_OP_NAMES
})
public @interface HistoricalOpsRequestFilter {}
@@ -4190,11 +4395,11 @@
public static final int FILTER_BY_PACKAGE_NAME = 1<<1;
/**
- * Filter historical appop request by feature id.
+ * Filter historical appop request by attribution tag.
*
* @hide
*/
- public static final int FILTER_BY_FEATURE_ID = 1<<2;
+ public static final int FILTER_BY_ATTRIBUTION_TAG = 1<<2;
/**
* Filter historical appop request by op names.
@@ -4215,7 +4420,7 @@
public static final class HistoricalOpsRequest {
private final int mUid;
private final @Nullable String mPackageName;
- private final @Nullable String mFeatureId;
+ private final @Nullable String mAttributionTag;
private final @Nullable List<String> mOpNames;
private final @HistoricalOpsRequestFilter int mFilter;
private final long mBeginTimeMillis;
@@ -4223,12 +4428,12 @@
private final @OpFlags int mFlags;
private HistoricalOpsRequest(int uid, @Nullable String packageName,
- @Nullable String featureId, @Nullable List<String> opNames,
+ @Nullable String attributionTag, @Nullable List<String> opNames,
@HistoricalOpsRequestFilter int filter, long beginTimeMillis,
long endTimeMillis, @OpFlags int flags) {
mUid = uid;
mPackageName = packageName;
- mFeatureId = featureId;
+ mAttributionTag = attributionTag;
mOpNames = opNames;
mFilter = filter;
mBeginTimeMillis = beginTimeMillis;
@@ -4246,7 +4451,7 @@
public static final class Builder {
private int mUid = Process.INVALID_UID;
private @Nullable String mPackageName;
- private @Nullable String mFeatureId;
+ private @Nullable String mAttributionTag;
private @Nullable List<String> mOpNames;
private @HistoricalOpsRequestFilter int mFilter;
private final long mBeginTimeMillis;
@@ -4310,14 +4515,14 @@
}
/**
- * Sets the feature id to query for.
+ * Sets the attribution tag to query for.
*
- * @param featureId The id of the feature.
+ * @param attributionTag attribution tag
* @return This builder.
*/
- public @NonNull Builder setFeatureId(@Nullable String featureId) {
- mFeatureId = featureId;
- mFilter |= FILTER_BY_FEATURE_ID;
+ public @NonNull Builder setAttributionTag(@Nullable String attributionTag) {
+ mAttributionTag = attributionTag;
+ mFilter |= FILTER_BY_ATTRIBUTION_TAG;
return this;
}
@@ -4368,7 +4573,7 @@
* @return a new {@link HistoricalOpsRequest}.
*/
public @NonNull HistoricalOpsRequest build() {
- return new HistoricalOpsRequest(mUid, mPackageName, mFeatureId, mOpNames,
+ return new HistoricalOpsRequest(mUid, mPackageName, mAttributionTag, mOpNames,
mFilter, mBeginTimeMillis, mEndTimeMillis, mFlags);
}
}
@@ -4528,7 +4733,7 @@
*
* @param uid Uid to filter for.
* @param packageName Package to filter for.
- * @param featureId Package to filter for.
+ * @param attributionTag attribution tag to filter for
* @param opNames Ops to filter for.
* @param filter Which parameters to filter on.
* @param beginTimeMillis The begin time to filter for or {@link Long#MIN_VALUE} for all.
@@ -4536,7 +4741,7 @@
*
* @hide
*/
- public void filter(int uid, @Nullable String packageName, @Nullable String featureId,
+ public void filter(int uid, @Nullable String packageName, @Nullable String attributionTag,
@Nullable String[] opNames, @HistoricalOpsRequestFilter int filter,
long beginTimeMillis, long endTimeMillis) {
final long durationMillis = getDurationMillis();
@@ -4550,7 +4755,7 @@
if ((filter & FILTER_BY_UID) != 0 && uid != uidOp.getUid()) {
mHistoricalUidOps.removeAt(i);
} else {
- uidOp.filter(packageName, featureId, opNames, filter, scaleFactor);
+ uidOp.filter(packageName, attributionTag, opNames, filter, scaleFactor);
if (uidOp.getPackageCount() == 0) {
mHistoricalUidOps.removeAt(i);
}
@@ -4581,28 +4786,28 @@
/** @hide */
@TestApi
public void increaseAccessCount(int opCode, int uid, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
getOrCreateHistoricalUidOps(uid).increaseAccessCount(opCode,
- packageName, featureId, uidState, flags, increment);
+ packageName, attributionTag, uidState, flags, increment);
}
/** @hide */
@TestApi
public void increaseRejectCount(int opCode, int uid, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
getOrCreateHistoricalUidOps(uid).increaseRejectCount(opCode,
- packageName, featureId, uidState, flags, increment);
+ packageName, attributionTag, uidState, flags, increment);
}
/** @hide */
@TestApi
public void increaseAccessDuration(int opCode, int uid, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
getOrCreateHistoricalUidOps(uid).increaseAccessDuration(opCode,
- packageName, featureId, uidState, flags, increment);
+ packageName, attributionTag, uidState, flags, increment);
}
/** @hide */
@@ -4882,7 +5087,7 @@
}
}
- private void filter(@Nullable String packageName, @Nullable String featureId,
+ private void filter(@Nullable String packageName, @Nullable String attributionTag,
@Nullable String[] opNames, @HistoricalOpsRequestFilter int filter,
double fractionToRemove) {
final int packageCount = getPackageCount();
@@ -4892,8 +5097,8 @@
packageOps.getPackageName())) {
mHistoricalPackageOps.removeAt(i);
} else {
- packageOps.filter(featureId, opNames, filter, fractionToRemove);
- if (packageOps.getFeatureCount() == 0) {
+ packageOps.filter(attributionTag, opNames, filter, fractionToRemove);
+ if (packageOps.getAttributedOpsCount() == 0) {
mHistoricalPackageOps.removeAt(i);
}
}
@@ -4912,24 +5117,24 @@
}
private void increaseAccessCount(int opCode, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
getOrCreateHistoricalPackageOps(packageName).increaseAccessCount(
- opCode, featureId, uidState, flags, increment);
+ opCode, attributionTag, uidState, flags, increment);
}
private void increaseRejectCount(int opCode, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
getOrCreateHistoricalPackageOps(packageName).increaseRejectCount(
- opCode, featureId, uidState, flags, increment);
+ opCode, attributionTag, uidState, flags, increment);
}
private void increaseAccessDuration(int opCode, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
getOrCreateHistoricalPackageOps(packageName).increaseAccessDuration(
- opCode, featureId, uidState, flags, increment);
+ opCode, attributionTag, uidState, flags, increment);
}
/**
@@ -5074,7 +5279,7 @@
@SystemApi
public static final class HistoricalPackageOps implements Parcelable {
private final @NonNull String mPackageName;
- private @Nullable ArrayMap<String, HistoricalFeatureOps> mHistoricalFeatureOps;
+ private @Nullable ArrayMap<String, AttributedHistoricalOps> mAttributedHistoricalOps;
/** @hide */
public HistoricalPackageOps(@NonNull String packageName) {
@@ -5083,70 +5288,71 @@
private HistoricalPackageOps(@NonNull HistoricalPackageOps other) {
mPackageName = other.mPackageName;
- final int opCount = other.getFeatureCount();
+ final int opCount = other.getAttributedOpsCount();
for (int i = 0; i < opCount; i++) {
- final HistoricalFeatureOps origOps = other.getFeatureOpsAt(i);
- final HistoricalFeatureOps cloneOps = new HistoricalFeatureOps(origOps);
- if (mHistoricalFeatureOps == null) {
- mHistoricalFeatureOps = new ArrayMap<>(opCount);
+ final AttributedHistoricalOps origOps = other.getAttributedOpsAt(i);
+ final AttributedHistoricalOps cloneOps = new AttributedHistoricalOps(origOps);
+ if (mAttributedHistoricalOps == null) {
+ mAttributedHistoricalOps = new ArrayMap<>(opCount);
}
- mHistoricalFeatureOps.put(cloneOps.getFeatureId(), cloneOps);
+ mAttributedHistoricalOps.put(cloneOps.getTag(), cloneOps);
}
}
private HistoricalPackageOps(@NonNull Parcel parcel) {
mPackageName = parcel.readString();
- mHistoricalFeatureOps = parcel.createTypedArrayMap(HistoricalFeatureOps.CREATOR);
+ mAttributedHistoricalOps = parcel.createTypedArrayMap(AttributedHistoricalOps.CREATOR);
}
private @Nullable HistoricalPackageOps splice(double fractionToRemove) {
HistoricalPackageOps splice = null;
- final int featureCount = getFeatureCount();
- for (int i = 0; i < featureCount; i++) {
- final HistoricalFeatureOps origOps = getFeatureOpsAt(i);
- final HistoricalFeatureOps spliceOps = origOps.splice(fractionToRemove);
+ final int attributionCount = getAttributedOpsCount();
+ for (int i = 0; i < attributionCount; i++) {
+ final AttributedHistoricalOps origOps = getAttributedOpsAt(i);
+ final AttributedHistoricalOps spliceOps = origOps.splice(fractionToRemove);
if (spliceOps != null) {
if (splice == null) {
splice = new HistoricalPackageOps(mPackageName);
}
- if (splice.mHistoricalFeatureOps == null) {
- splice.mHistoricalFeatureOps = new ArrayMap<>();
+ if (splice.mAttributedHistoricalOps == null) {
+ splice.mAttributedHistoricalOps = new ArrayMap<>();
}
- splice.mHistoricalFeatureOps.put(spliceOps.getFeatureId(), spliceOps);
+ splice.mAttributedHistoricalOps.put(spliceOps.getTag(), spliceOps);
}
}
return splice;
}
private void merge(@NonNull HistoricalPackageOps other) {
- final int featureCount = other.getFeatureCount();
- for (int i = 0; i < featureCount; i++) {
- final HistoricalFeatureOps otherFeatureOps = other.getFeatureOpsAt(i);
- final HistoricalFeatureOps thisFeatureOps = getFeatureOps(
- otherFeatureOps.getFeatureId());
- if (thisFeatureOps != null) {
- thisFeatureOps.merge(otherFeatureOps);
+ final int attributionCount = other.getAttributedOpsCount();
+ for (int i = 0; i < attributionCount; i++) {
+ final AttributedHistoricalOps otherAttributionOps = other.getAttributedOpsAt(i);
+ final AttributedHistoricalOps thisAttributionOps = getAttributedOps(
+ otherAttributionOps.getTag());
+ if (thisAttributionOps != null) {
+ thisAttributionOps.merge(otherAttributionOps);
} else {
- if (mHistoricalFeatureOps == null) {
- mHistoricalFeatureOps = new ArrayMap<>();
+ if (mAttributedHistoricalOps == null) {
+ mAttributedHistoricalOps = new ArrayMap<>();
}
- mHistoricalFeatureOps.put(otherFeatureOps.getFeatureId(), otherFeatureOps);
+ mAttributedHistoricalOps.put(otherAttributionOps.getTag(),
+ otherAttributionOps);
}
}
}
- private void filter(@Nullable String featureId, @Nullable String[] opNames,
+ private void filter(@Nullable String attributionTag, @Nullable String[] opNames,
@HistoricalOpsRequestFilter int filter, double fractionToRemove) {
- final int featureCount = getFeatureCount();
- for (int i = featureCount - 1; i >= 0; i--) {
- final HistoricalFeatureOps featureOps = getFeatureOpsAt(i);
- if ((filter & FILTER_BY_FEATURE_ID) != 0 && !Objects.equals(featureId,
- featureOps.getFeatureId())) {
- mHistoricalFeatureOps.removeAt(i);
+ final int attributionCount = getAttributedOpsCount();
+ for (int i = attributionCount - 1; i >= 0; i--) {
+ final AttributedHistoricalOps attributionOps = getAttributedOpsAt(i);
+ if ((filter & FILTER_BY_ATTRIBUTION_TAG) != 0 && !Objects.equals(attributionTag,
+ attributionOps.getTag())) {
+ mAttributedHistoricalOps.removeAt(i);
} else {
- featureOps.filter(opNames, filter, fractionToRemove);
- if (featureOps.getOpCount() == 0) {
- mHistoricalFeatureOps.removeAt(i);
+ attributionOps.filter(opNames, filter, fractionToRemove);
+ if (attributionOps.getOpCount() == 0) {
+ mAttributedHistoricalOps.removeAt(i);
}
}
}
@@ -5154,38 +5360,38 @@
private void accept(@NonNull HistoricalOpsVisitor visitor) {
visitor.visitHistoricalPackageOps(this);
- final int featureCount = getFeatureCount();
- for (int i = 0; i < featureCount; i++) {
- getFeatureOpsAt(i).accept(visitor);
+ final int attributionCount = getAttributedOpsCount();
+ for (int i = 0; i < attributionCount; i++) {
+ getAttributedOpsAt(i).accept(visitor);
}
}
private boolean isEmpty() {
- final int featureCount = getFeatureCount();
- for (int i = featureCount - 1; i >= 0; i--) {
- final HistoricalFeatureOps featureOps = mHistoricalFeatureOps.valueAt(i);
- if (!featureOps.isEmpty()) {
+ final int attributionCount = getAttributedOpsCount();
+ for (int i = attributionCount - 1; i >= 0; i--) {
+ final AttributedHistoricalOps attributionOps = mAttributedHistoricalOps.valueAt(i);
+ if (!attributionOps.isEmpty()) {
return false;
}
}
return true;
}
- private void increaseAccessCount(int opCode, @Nullable String featureId,
+ private void increaseAccessCount(int opCode, @Nullable String attributionTag,
@UidState int uidState, @OpFlags int flags, long increment) {
- getOrCreateHistoricalFeatureOps(featureId).increaseAccessCount(
+ getOrCreateAttributedHistoricalOps(attributionTag).increaseAccessCount(
opCode, uidState, flags, increment);
}
- private void increaseRejectCount(int opCode, @Nullable String featureId,
+ private void increaseRejectCount(int opCode, @Nullable String attributionTag,
@UidState int uidState, @OpFlags int flags, long increment) {
- getOrCreateHistoricalFeatureOps(featureId).increaseRejectCount(
+ getOrCreateAttributedHistoricalOps(attributionTag).increaseRejectCount(
opCode, uidState, flags, increment);
}
- private void increaseAccessDuration(int opCode, @Nullable String featureId,
+ private void increaseAccessDuration(int opCode, @Nullable String attributionTag,
@UidState int uidState, @OpFlags int flags, long increment) {
- getOrCreateHistoricalFeatureOps(featureId).increaseAccessDuration(
+ getOrCreateAttributedHistoricalOps(attributionTag).increaseAccessDuration(
opCode, uidState, flags, increment);
}
@@ -5198,17 +5404,18 @@
return mPackageName;
}
- private @NonNull HistoricalFeatureOps getOrCreateHistoricalFeatureOps(
- @Nullable String featureId) {
- if (mHistoricalFeatureOps == null) {
- mHistoricalFeatureOps = new ArrayMap<>();
+ private @NonNull AttributedHistoricalOps getOrCreateAttributedHistoricalOps(
+ @Nullable String attributionTag) {
+ if (mAttributedHistoricalOps == null) {
+ mAttributedHistoricalOps = new ArrayMap<>();
}
- HistoricalFeatureOps historicalFeatureOp = mHistoricalFeatureOps.get(featureId);
- if (historicalFeatureOp == null) {
- historicalFeatureOp = new HistoricalFeatureOps(featureId);
- mHistoricalFeatureOps.put(featureId, historicalFeatureOp);
+ AttributedHistoricalOps historicalAttributionOp = mAttributedHistoricalOps.get(
+ attributionTag);
+ if (historicalAttributionOp == null) {
+ historicalAttributionOp = new AttributedHistoricalOps(attributionTag);
+ mAttributedHistoricalOps.put(attributionTag, historicalAttributionOp);
}
- return historicalFeatureOp;
+ return historicalAttributionOp;
}
/**
@@ -5219,13 +5426,13 @@
*/
public @IntRange(from = 0) int getOpCount() {
int numOps = 0;
- int numFeatures = getFeatureCount();
+ int numAttributions = getAttributedOpsCount();
for (int code = 0; code < _NUM_OP; code++) {
String opName = opToPublicName(code);
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- if (getFeatureOpsAt(featureNum).getOp(opName) != null) {
+ for (int attributionNum = 0; attributionNum < numAttributions; attributionNum++) {
+ if (getAttributedOpsAt(attributionNum).getOp(opName) != null) {
numOps++;
break;
}
@@ -5238,7 +5445,7 @@
/**
* Gets the historical op at a given index.
*
- * <p>This combines the counts from all features.
+ * <p>This combines the counts from all attributions.
*
* @param index The index to lookup.
* @return The op at the given index.
@@ -5246,13 +5453,13 @@
*/
public @NonNull HistoricalOp getOpAt(@IntRange(from = 0) int index) {
int numOpsFound = 0;
- int numFeatures = getFeatureCount();
+ int numAttributions = getAttributedOpsCount();
for (int code = 0; code < _NUM_OP; code++) {
String opName = opToPublicName(code);
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- if (getFeatureOpsAt(featureNum).getOp(opName) != null) {
+ for (int attributionNum = 0; attributionNum < numAttributions; attributionNum++) {
+ if (getAttributedOpsAt(attributionNum).getOp(opName) != null) {
if (numOpsFound == index) {
return getOp(opName);
} else {
@@ -5269,25 +5476,25 @@
/**
* Gets the historical entry for a given op name.
*
- * <p>This combines the counts from all features.
+ * <p>This combines the counts from all attributions.
*
* @param opName The op name.
* @return The historical entry for that op name.
*/
public @Nullable HistoricalOp getOp(@NonNull String opName) {
- if (mHistoricalFeatureOps == null) {
+ if (mAttributedHistoricalOps == null) {
return null;
}
HistoricalOp combinedOp = null;
- int numFeatures = getFeatureCount();
- for (int i = 0; i < numFeatures; i++) {
- HistoricalOp featureOp = getFeatureOpsAt(i).getOp(opName);
- if (featureOp != null) {
+ int numAttributions = getAttributedOpsCount();
+ for (int i = 0; i < numAttributions; i++) {
+ HistoricalOp attributionOp = getAttributedOpsAt(i).getOp(opName);
+ if (attributionOp != null) {
if (combinedOp == null) {
- combinedOp = new HistoricalOp(featureOp);
+ combinedOp = new HistoricalOp(attributionOp);
} else {
- combinedOp.merge(featureOp);
+ combinedOp.merge(attributionOp);
}
}
}
@@ -5303,7 +5510,7 @@
@Override
public void writeToParcel(@NonNull Parcel parcel, int flags) {
parcel.writeString(mPackageName);
- parcel.writeTypedArrayMap(mHistoricalFeatureOps, flags);
+ parcel.writeTypedArrayMap(mAttributedHistoricalOps, flags);
}
public static final @android.annotation.NonNull Creator<HistoricalPackageOps> CREATOR =
@@ -5331,11 +5538,11 @@
if (!mPackageName.equals(other.mPackageName)) {
return false;
}
- if (mHistoricalFeatureOps == null) {
- if (other.mHistoricalFeatureOps != null) {
+ if (mAttributedHistoricalOps == null) {
+ if (other.mAttributedHistoricalOps != null) {
return false;
}
- } else if (!mHistoricalFeatureOps.equals(other.mHistoricalFeatureOps)) {
+ } else if (!mAttributedHistoricalOps.equals(other.mAttributedHistoricalOps)) {
return false;
}
return true;
@@ -5344,58 +5551,58 @@
@Override
public int hashCode() {
int result = mPackageName != null ? mPackageName.hashCode() : 0;
- result = 31 * result + (mHistoricalFeatureOps != null ? mHistoricalFeatureOps.hashCode()
- : 0);
+ result = 31 * result + (mAttributedHistoricalOps != null
+ ? mAttributedHistoricalOps.hashCode() : 0);
return result;
}
/**
- * Gets number of feature with historical ops.
+ * Gets number of attributed historical ops.
*
- * @return The number of feature with historical ops.
+ * @return The number of attribution with historical ops.
*
- * @see #getFeatureOpsAt(int)
+ * @see #getAttributedOpsAt(int)
*/
- public @IntRange(from = 0) int getFeatureCount() {
- if (mHistoricalFeatureOps == null) {
+ public @IntRange(from = 0) int getAttributedOpsCount() {
+ if (mAttributedHistoricalOps == null) {
return 0;
}
- return mHistoricalFeatureOps.size();
+ return mAttributedHistoricalOps.size();
}
/**
- * Gets the historical feature ops at a given index.
+ * Gets the attributed historical ops at a given index.
*
* @param index The index.
*
- * @return The historical feature ops at the given index.
+ * @return The historical attribution ops at the given index.
*
- * @see #getFeatureCount()
+ * @see #getAttributedOpsCount()
*/
- public @NonNull HistoricalFeatureOps getFeatureOpsAt(@IntRange(from = 0) int index) {
- if (mHistoricalFeatureOps == null) {
+ public @NonNull AttributedHistoricalOps getAttributedOpsAt(@IntRange(from = 0) int index) {
+ if (mAttributedHistoricalOps == null) {
throw new IndexOutOfBoundsException();
}
- return mHistoricalFeatureOps.valueAt(index);
+ return mAttributedHistoricalOps.valueAt(index);
}
/**
- * Gets the historical feature ops for a given feature.
+ * Gets the attributed historical ops for a given attribution tag.
*
- * @param featureId The feature id.
+ * @param attributionTag The attribution tag.
*
- * @return The historical ops for the feature.
+ * @return The historical ops for the attribution.
*/
- public @Nullable HistoricalFeatureOps getFeatureOps(@NonNull String featureId) {
- if (mHistoricalFeatureOps == null) {
+ public @Nullable AttributedHistoricalOps getAttributedOps(@NonNull String attributionTag) {
+ if (mAttributedHistoricalOps == null) {
return null;
}
- return mHistoricalFeatureOps.get(featureId);
+ return mAttributedHistoricalOps.get(attributionTag);
}
}
/**
- * This class represents historical app op information about a feature in a package.
+ * This class represents historical app op information about a attribution in a package.
*
* @hide
*/
@@ -5405,20 +5612,20 @@
@DataClass(genHiddenConstructor = true,
genEqualsHashCode = true, genHiddenCopyConstructor = true) */
@DataClass.Suppress("getHistoricalOps")
- public static final class HistoricalFeatureOps implements Parcelable {
- /** Id of the {@link Context#createFeatureContext feature} in the package */
- private final @Nullable String mFeatureId;
+ public static final class AttributedHistoricalOps implements Parcelable {
+ /** {@link Context#createAttributionContext attribution} tag */
+ private final @Nullable String mTag;
- /** Ops for this feature */
+ /** Ops for this attribution */
private @Nullable ArrayMap<String, HistoricalOp> mHistoricalOps;
/** @hide */
- public HistoricalFeatureOps(@NonNull String featureId) {
- mFeatureId = featureId;
+ public AttributedHistoricalOps(@NonNull String tag) {
+ mTag = tag;
}
- private HistoricalFeatureOps(@NonNull HistoricalFeatureOps other) {
- mFeatureId = other.mFeatureId;
+ private AttributedHistoricalOps(@NonNull AttributedHistoricalOps other) {
+ mTag = other.mTag;
final int opCount = other.getOpCount();
for (int i = 0; i < opCount; i++) {
final HistoricalOp origOp = other.getOpAt(i);
@@ -5430,15 +5637,15 @@
}
}
- private @Nullable HistoricalFeatureOps splice(double fractionToRemove) {
- HistoricalFeatureOps splice = null;
+ private @Nullable AttributedHistoricalOps splice(double fractionToRemove) {
+ AttributedHistoricalOps splice = null;
final int opCount = getOpCount();
for (int i = 0; i < opCount; i++) {
final HistoricalOp origOps = getOpAt(i);
final HistoricalOp spliceOps = origOps.splice(fractionToRemove);
if (spliceOps != null) {
if (splice == null) {
- splice = new HistoricalFeatureOps(mFeatureId, null);
+ splice = new AttributedHistoricalOps(mTag, null);
}
if (splice.mHistoricalOps == null) {
splice.mHistoricalOps = new ArrayMap<>();
@@ -5449,7 +5656,7 @@
return splice;
}
- private void merge(@NonNull HistoricalFeatureOps other) {
+ private void merge(@NonNull AttributedHistoricalOps other) {
final int opCount = other.getOpCount();
for (int i = 0; i < opCount; i++) {
final HistoricalOp otherOp = other.getOpAt(i);
@@ -5546,7 +5753,7 @@
}
private void accept(@NonNull HistoricalOpsVisitor visitor) {
- visitor.visitHistoricalFeatureOps(this);
+ visitor.visitHistoricalAttributionOps(this);
final int opCount = getOpCount();
for (int i = 0; i < opCount; i++) {
getOpAt(i).accept(visitor);
@@ -5582,46 +5789,46 @@
/**
- * Creates a new HistoricalFeatureOps.
+ * Creates a new HistoricalAttributionOps.
*
- * @param featureId
- * Id of the {@link Context#createFeatureContext feature} in the package
+ * @param tag
+ * {@link Context#createAttributionContext attribution} tag
* @param historicalOps
- * Ops for this feature
+ * Ops for this attribution
* @hide
*/
@DataClass.Generated.Member
- public HistoricalFeatureOps(
- @Nullable String featureId,
+ public AttributedHistoricalOps(
+ @Nullable String tag,
@Nullable ArrayMap<String,HistoricalOp> historicalOps) {
- this.mFeatureId = featureId;
+ this.mTag = tag;
this.mHistoricalOps = historicalOps;
// onConstructed(); // You can define this method to get a callback
}
/**
- * Id of the {@link Context#createFeatureContext feature} in the package
+ * {@link Context#createAttributionContext attribution} tag
*/
@DataClass.Generated.Member
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getTag() {
+ return mTag;
}
@Override
@DataClass.Generated.Member
public boolean equals(@Nullable Object o) {
// You can override field equality logic by defining either of the methods like:
- // boolean fieldNameEquals(HistoricalFeatureOps other) { ... }
+ // boolean fieldNameEquals(HistoricalAttributionOps other) { ... }
// boolean fieldNameEquals(FieldType otherValue) { ... }
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@SuppressWarnings("unchecked")
- HistoricalFeatureOps that = (HistoricalFeatureOps) o;
+ AttributedHistoricalOps that = (AttributedHistoricalOps) o;
//noinspection PointlessBooleanExpression
return true
- && Objects.equals(mFeatureId, that.mFeatureId)
+ && Objects.equals(mTag, that.mTag)
&& Objects.equals(mHistoricalOps, that.mHistoricalOps);
}
@@ -5632,7 +5839,7 @@
// int fieldNameHashCode() { ... }
int _hash = 1;
- _hash = 31 * _hash + Objects.hashCode(mFeatureId);
+ _hash = 31 * _hash + Objects.hashCode(mTag);
_hash = 31 * _hash + Objects.hashCode(mHistoricalOps);
return _hash;
}
@@ -5644,10 +5851,10 @@
// void parcelFieldName(Parcel dest, int flags) { ... }
byte flg = 0;
- if (mFeatureId != null) flg |= 0x1;
+ if (mTag != null) flg |= 0x1;
if (mHistoricalOps != null) flg |= 0x2;
dest.writeByte(flg);
- if (mFeatureId != null) dest.writeString(mFeatureId);
+ if (mTag != null) dest.writeString(mTag);
if (mHistoricalOps != null) dest.writeMap(mHistoricalOps);
}
@@ -5658,35 +5865,35 @@
/** @hide */
@SuppressWarnings({"unchecked", "RedundantCast"})
@DataClass.Generated.Member
- /* package-private */ HistoricalFeatureOps(@NonNull Parcel in) {
+ /* package-private */ AttributedHistoricalOps(@NonNull Parcel in) {
// You can override field unparcelling by defining methods like:
// static FieldType unparcelFieldName(Parcel in) { ... }
byte flg = in.readByte();
- String featureId = (flg & 0x1) == 0 ? null : in.readString();
+ String attributionTag = (flg & 0x1) == 0 ? null : in.readString();
ArrayMap<String,HistoricalOp> historicalOps = null;
if ((flg & 0x2) != 0) {
historicalOps = new ArrayMap();
in.readMap(historicalOps, HistoricalOp.class.getClassLoader());
}
- this.mFeatureId = featureId;
+ this.mTag = attributionTag;
this.mHistoricalOps = historicalOps;
// onConstructed(); // You can define this method to get a callback
}
@DataClass.Generated.Member
- public static final @NonNull Parcelable.Creator<HistoricalFeatureOps> CREATOR
- = new Parcelable.Creator<HistoricalFeatureOps>() {
+ public static final @NonNull Parcelable.Creator<AttributedHistoricalOps> CREATOR
+ = new Parcelable.Creator<AttributedHistoricalOps>() {
@Override
- public HistoricalFeatureOps[] newArray(int size) {
- return new HistoricalFeatureOps[size];
+ public AttributedHistoricalOps[] newArray(int size) {
+ return new AttributedHistoricalOps[size];
}
@Override
- public HistoricalFeatureOps createFromParcel(@NonNull Parcel in) {
- return new HistoricalFeatureOps(in);
+ public AttributedHistoricalOps createFromParcel(@NonNull Parcel in) {
+ return new AttributedHistoricalOps(in);
}
};
@@ -5695,7 +5902,7 @@
time = 1578113234821L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/app/AppOpsManager.java",
- inputSignatures = "private final @android.annotation.Nullable java.lang.String mFeatureId\nprivate @android.annotation.Nullable android.util.ArrayMap<java.lang.String,android.app.HistoricalOp> mHistoricalOps\nprivate @android.annotation.Nullable android.app.HistoricalFeatureOps splice(double)\nprivate void merge(android.app.HistoricalFeatureOps)\nprivate void filter(java.lang.String[],int,double)\nprivate boolean isEmpty()\nprivate void increaseAccessCount(int,int,int,long)\nprivate void increaseRejectCount(int,int,int,long)\nprivate void increaseAccessDuration(int,int,int,long)\npublic @android.annotation.IntRange(from=0L) int getOpCount()\npublic @android.annotation.NonNull android.app.HistoricalOp getOpAt(int)\npublic @android.annotation.Nullable android.app.HistoricalOp getOp(java.lang.String)\nprivate void accept(android.app.HistoricalOpsVisitor)\nprivate @android.annotation.NonNull android.app.HistoricalOp getOrCreateHistoricalOp(int)\nclass HistoricalFeatureOps extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true, genEqualsHashCode=true, genHiddenCopyConstructor=true)")
+ inputSignatures = "private final @android.annotation.Nullable java.lang.String mAttributionTag\nprivate @android.annotation.Nullable android.util.ArrayMap<java.lang.String,android.app.HistoricalOp> mHistoricalOps\nprivate @android.annotation.Nullable android.app.HistoricalAttributionOps splice(double)\nprivate void merge(android.app.HistoricalAttributionOps)\nprivate void filter(java.lang.String[],int,double)\nprivate boolean isEmpty()\nprivate void increaseAccessCount(int,int,int,long)\nprivate void increaseRejectCount(int,int,int,long)\nprivate void increaseAccessDuration(int,int,int,long)\npublic @android.annotation.IntRange(from=0L) int getOpCount()\npublic @android.annotation.NonNull android.app.HistoricalOp getOpAt(int)\npublic @android.annotation.Nullable android.app.HistoricalOp getOp(java.lang.String)\nprivate void accept(android.app.HistoricalOpsVisitor)\nprivate @android.annotation.NonNull android.app.HistoricalOp getOrCreateHistoricalOp(int)\nclass HistoricalAttributionOps extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genHiddenConstructor=true, genEqualsHashCode=true, genHiddenCopyConstructor=true)")
@Deprecated
private void __metadata() {}
*/
@@ -5829,6 +6036,11 @@
return mOp;
}
+ /** @hide */
+ public int getLoggingOpCode() {
+ return AppOpsManager.opToLoggingId(mOp);
+ }
+
/**
* Gets the number times the op was accessed (performed) in the foreground.
*
@@ -6371,7 +6583,7 @@
Objects.requireNonNull(executor, "executor cannot be null");
Objects.requireNonNull(callback, "callback cannot be null");
try {
- mService.getHistoricalOps(request.mUid, request.mPackageName, request.mFeatureId,
+ mService.getHistoricalOps(request.mUid, request.mPackageName, request.mAttributionTag,
request.mOpNames, request.mFilter, request.mBeginTimeMillis,
request.mEndTimeMillis, request.mFlags, new RemoteCallback((result) -> {
final HistoricalOps ops = result.getParcelable(KEY_HISTORICAL_OPS);
@@ -6411,8 +6623,9 @@
Objects.requireNonNull(callback, "callback cannot be null");
try {
mService.getHistoricalOpsFromDiskRaw(request.mUid, request.mPackageName,
- request.mFeatureId, request.mOpNames, request.mFilter, request.mBeginTimeMillis,
- request.mEndTimeMillis, request.mFlags, new RemoteCallback((result) -> {
+ request.mAttributionTag, request.mOpNames, request.mFilter,
+ request.mBeginTimeMillis, request.mEndTimeMillis, request.mFlags,
+ new RemoteCallback((result) -> {
final HistoricalOps ops = result.getParcelable(KEY_HISTORICAL_OPS);
final long identity = Binder.clearCallingIdentity();
try {
@@ -6663,6 +6876,13 @@
};
mModeWatchers.put(callback, cb);
}
+
+ // See CALL_BACK_ON_CHANGED_LISTENER_WITH_SWITCHED_OP_CHANGE
+ if (!Compatibility.isChangeEnabled(
+ CALL_BACK_ON_CHANGED_LISTENER_WITH_SWITCHED_OP_CHANGE)) {
+ flags |= CALL_BACK_ON_SWITCHED_OP;
+ }
+
try {
mService.startWatchingModeWithFlags(op, packageName, flags, cb);
} catch (RemoteException e) {
@@ -6995,8 +7215,8 @@
* @param op The operation to note. One of the OPSTR_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The {@link Context#createFeatureContext feature} in the package or {@code
- * null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or {@code
+ * null} for default attribution
* @param message A message describing the reason the op was noted
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
@@ -7006,8 +7226,8 @@
* @throws SecurityException If the app has been configured to crash on this op.
*/
public int noteOp(@NonNull String op, int uid, @Nullable String packageName,
- @Nullable String featureId, @Nullable String message) {
- return noteOp(strOpToOp(op), uid, packageName, featureId, message);
+ @Nullable String attributionTag, @Nullable String message) {
+ return noteOp(strOpToOp(op), uid, packageName, attributionTag, message);
}
/**
@@ -7023,7 +7243,8 @@
* @param op The operation to note. One of the OP_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The feature in the app or {@code null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or {@code
+ * null} for default attribution
* @param message A message describing the reason the op was noted
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
@@ -7034,9 +7255,9 @@
*
* @hide
*/
- public int noteOp(int op, int uid, @Nullable String packageName, @Nullable String featureId,
- @Nullable String message) {
- final int mode = noteOpNoThrow(op, uid, packageName, featureId, message);
+ public int noteOp(int op, int uid, @Nullable String packageName,
+ @Nullable String attributionTag, @Nullable String message) {
+ final int mode = noteOpNoThrow(op, uid, packageName, attributionTag, message);
if (mode == MODE_ERRORED) {
throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
}
@@ -7071,8 +7292,8 @@
* @param op The operation to note. One of the OPSTR_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The {@link Context#createFeatureContext feature} in the package or {@code
- * null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or {@code
+ * null} for default attribution
* @param message A message describing the reason the op was noted
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
@@ -7080,8 +7301,8 @@
* causing the app to crash).
*/
public int noteOpNoThrow(@NonNull String op, int uid, @NonNull String packageName,
- @Nullable String featureId, @Nullable String message) {
- return noteOpNoThrow(strOpToOp(op), uid, packageName, featureId, message);
+ @Nullable String attributionTag, @Nullable String message) {
+ return noteOpNoThrow(strOpToOp(op), uid, packageName, attributionTag, message);
}
/**
@@ -7091,7 +7312,8 @@
* @param op The operation to note. One of the OP_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The feature in the app or {@code null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or {@code
+ * null} for default attribution
* @param message A message describing the reason the op was noted
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
@@ -7101,8 +7323,9 @@
* @hide
*/
public int noteOpNoThrow(int op, int uid, @Nullable String packageName,
- @Nullable String featureId, @Nullable String message) {
+ @Nullable String attributionTag, @Nullable String message) {
try {
+ collectNoteOpCallsForValidation(op);
int collectionMode = getNotedOpCollectionMode(uid, packageName, op);
if (collectionMode == COLLECT_ASYNC) {
if (message == null) {
@@ -7111,14 +7334,14 @@
}
}
- int mode = mService.noteOperation(op, uid, packageName, featureId,
+ int mode = mService.noteOperation(op, uid, packageName, attributionTag,
collectionMode == COLLECT_ASYNC, message);
if (mode == MODE_ALLOWED) {
if (collectionMode == COLLECT_SELF) {
- collectNotedOpForSelf(op, featureId);
+ collectNotedOpForSelf(op, attributionTag);
} else if (collectionMode == COLLECT_SYNC) {
- collectNotedOpSync(op, featureId);
+ collectNotedOpSync(op, attributionTag);
}
}
@@ -7158,8 +7381,8 @@
* @param op The operation to note. One of the OP_* constants.
* @param proxiedPackageName The name of the application calling into the proxy application.
* @param proxiedUid The uid of the proxied application
- * @param proxiedFeatureId The feature in the proxied app or {@code null} for default
- * feature
+ * @param proxiedAttributionTag The proxied {@link Context#createAttributionContext
+ * attribution tag} or {@code null} for default attribution
* @param message A message describing the reason the op was noted
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or {@link #MODE_IGNORED}
@@ -7171,8 +7394,8 @@
* @hide
*/
public int noteProxyOp(int op, @Nullable String proxiedPackageName, int proxiedUid,
- @Nullable String proxiedFeatureId, @Nullable String message) {
- int mode = noteProxyOpNoThrow(op, proxiedPackageName, proxiedUid, proxiedFeatureId,
+ @Nullable String proxiedAttributionTag, @Nullable String message) {
+ int mode = noteProxyOpNoThrow(op, proxiedPackageName, proxiedUid, proxiedAttributionTag,
message);
if (mode == MODE_ERRORED) {
throw new SecurityException("Proxy package " + mContext.getOpPackageName()
@@ -7191,8 +7414,8 @@
* @param op The operation to note. One of the OPSTR_* constants.
* @param proxiedPackageName The name of the application calling into the proxy application.
* @param proxiedUid The uid of the proxied application
- * @param proxiedFeatureId The feature in the proxied app or {@code null} for default
- * feature
+ * @param proxiedAttributionTag The proxied {@link Context#createAttributionContext
+ * attribution tag} or {@code null} for default attribution
* @param message A message describing the reason the op was noted
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or {@link #MODE_IGNORED}
@@ -7202,8 +7425,8 @@
* op.
*/
public int noteProxyOp(@NonNull String op, @Nullable String proxiedPackageName, int proxiedUid,
- @Nullable String proxiedFeatureId, @Nullable String message) {
- return noteProxyOp(strOpToOp(op), proxiedPackageName, proxiedUid, proxiedFeatureId,
+ @Nullable String proxiedAttributionTag, @Nullable String message) {
+ return noteProxyOp(strOpToOp(op), proxiedPackageName, proxiedUid, proxiedAttributionTag,
message);
}
@@ -7234,14 +7457,14 @@
* @param op The op to note
* @param proxiedPackageName The package to note the op for
* @param proxiedUid The uid the package belongs to
- * @param proxiedFeatureId The feature in the proxied app or {@code null} for default
- * feature
+ * @param proxiedAttributionTag The proxied {@link Context#createAttributionContext
+ * attribution tag} or {@code null} for default attribution
* @param message A message describing the reason the op was noted
*/
public int noteProxyOpNoThrow(@NonNull String op, @Nullable String proxiedPackageName,
- int proxiedUid, @Nullable String proxiedFeatureId, @Nullable String message) {
+ int proxiedUid, @Nullable String proxiedAttributionTag, @Nullable String message) {
return noteProxyOpNoThrow(strOpToOp(op), proxiedPackageName, proxiedUid,
- proxiedFeatureId, message);
+ proxiedAttributionTag, message);
}
/**
@@ -7252,17 +7475,18 @@
* @param proxiedPackageName The package to note the op for or {@code null} if the op should be
* noted for the "android" package
* @param proxiedUid The uid the package belongs to
- * @param proxiedFeatureId The feature in the proxied app or {@code null} for default
- * feature
+ * @param proxiedAttributionTag The proxied {@link Context#createAttributionContext
+ * attribution tag} or {@code null} for default attribution
* @param message A message describing the reason the op was noted
*
* @hide
*/
public int noteProxyOpNoThrow(int op, @Nullable String proxiedPackageName, int proxiedUid,
- @Nullable String proxiedFeatureId, @Nullable String message) {
+ @Nullable String proxiedAttributionTag, @Nullable String message) {
int myUid = Process.myUid();
try {
+ collectNoteOpCallsForValidation(op);
int collectionMode = getNotedOpCollectionMode(proxiedUid, proxiedPackageName, op);
if (collectionMode == COLLECT_ASYNC) {
if (message == null) {
@@ -7272,17 +7496,17 @@
}
int mode = mService.noteProxyOperation(op, proxiedUid, proxiedPackageName,
- proxiedFeatureId, myUid, mContext.getOpPackageName(),
- mContext.getFeatureId(), collectionMode == COLLECT_ASYNC, message);
+ proxiedAttributionTag, myUid, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), collectionMode == COLLECT_ASYNC, message);
if (mode == MODE_ALLOWED) {
if (collectionMode == COLLECT_SELF) {
- collectNotedOpForSelf(op, proxiedFeatureId);
+ collectNotedOpForSelf(op, proxiedAttributionTag);
} else if (collectionMode == COLLECT_SYNC
// Only collect app-ops when the proxy is trusted
&& mContext.checkPermission(Manifest.permission.UPDATE_APP_OPS_STATS, -1,
myUid) == PackageManager.PERMISSION_GRANTED) {
- collectNotedOpSync(op, proxiedFeatureId);
+ collectNotedOpSync(op, proxiedAttributionTag);
}
}
@@ -7471,8 +7695,8 @@
* @param op The operation to start. One of the OPSTR_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The {@link Context#createFeatureContext feature} in the package or {@code
- * null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or
+ * {@code null} for default attribution
* @param message Description why op was started
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
@@ -7483,8 +7707,8 @@
* the package is not in the passed in UID.
*/
public int startOp(@NonNull String op, int uid, @Nullable String packageName,
- @Nullable String featureId, @Nullable String message) {
- return startOp(strOpToOp(op), uid, packageName, false, featureId, message);
+ @Nullable String attributionTag, @Nullable String message) {
+ return startOp(strOpToOp(op), uid, packageName, false, attributionTag, message);
}
/**
@@ -7493,7 +7717,8 @@
* @param op The operation to start. One of the OP_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The feature in the app or {@code null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or
+ * {@code null} for default attribution
* @param startIfModeDefault Whether to start if mode is {@link #MODE_DEFAULT}.
* @param message Description why op was started
*
@@ -7507,8 +7732,8 @@
* @hide
*/
public int startOp(int op, int uid, @Nullable String packageName, boolean startIfModeDefault,
- @Nullable String featureId, @Nullable String message) {
- final int mode = startOpNoThrow(op, uid, packageName, startIfModeDefault, featureId,
+ @Nullable String attributionTag, @Nullable String message) {
+ final int mode = startOpNoThrow(op, uid, packageName, startIfModeDefault, attributionTag,
message);
if (mode == MODE_ERRORED) {
throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
@@ -7551,7 +7776,8 @@
* @param op The operation to start. One of the OP_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The feature in the app or {@code null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or
+ * {@code null} for default attribution
* @param message Description why op was started
*
* @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
@@ -7559,8 +7785,8 @@
* causing the app to crash).
*/
public int startOpNoThrow(@NonNull String op, int uid, @NonNull String packageName,
- @NonNull String featureId, @Nullable String message) {
- return startOpNoThrow(strOpToOp(op), uid, packageName, false, featureId, message);
+ @NonNull String attributionTag, @Nullable String message) {
+ return startOpNoThrow(strOpToOp(op), uid, packageName, false, attributionTag, message);
}
/**
@@ -7570,7 +7796,8 @@
* @param op The operation to start. One of the OP_* constants.
* @param uid The user id of the application attempting to perform the operation.
* @param packageName The name of the application attempting to perform the operation.
- * @param featureId The feature in the app or {@code null} for default feature
+ * @param attributionTag The {@link Context#createAttributionContext attribution tag} or
+ * {@code null} for default attribution
* @param startIfModeDefault Whether to start if mode is {@link #MODE_DEFAULT}.
* @param message Description why op was started
*
@@ -7581,8 +7808,9 @@
* @hide
*/
public int startOpNoThrow(int op, int uid, @NonNull String packageName,
- boolean startIfModeDefault, @Nullable String featureId, @Nullable String message) {
+ boolean startIfModeDefault, @Nullable String attributionTag, @Nullable String message) {
try {
+ collectNoteOpCallsForValidation(op);
int collectionMode = getNotedOpCollectionMode(uid, packageName, op);
if (collectionMode == COLLECT_ASYNC) {
if (message == null) {
@@ -7592,13 +7820,13 @@
}
int mode = mService.startOperation(getClientId(), op, uid, packageName,
- featureId, startIfModeDefault, collectionMode == COLLECT_ASYNC, message);
+ attributionTag, startIfModeDefault, collectionMode == COLLECT_ASYNC, message);
if (mode == MODE_ALLOWED) {
if (collectionMode == COLLECT_SELF) {
- collectNotedOpForSelf(op, featureId);
+ collectNotedOpForSelf(op, attributionTag);
} else if (collectionMode == COLLECT_SYNC) {
- collectNotedOpSync(op, featureId);
+ collectNotedOpSync(op, attributionTag);
}
}
@@ -7632,8 +7860,8 @@
* previously passed in when starting the operation.
*/
public void finishOp(@NonNull String op, int uid, @NonNull String packageName,
- @Nullable String featureId) {
- finishOp(strOpToOp(op), uid, packageName, featureId);
+ @Nullable String attributionTag) {
+ finishOp(strOpToOp(op), uid, packageName, attributionTag);
}
/**
@@ -7654,9 +7882,9 @@
* @hide
*/
public void finishOp(int op, int uid, @NonNull String packageName,
- @Nullable String featureId) {
+ @Nullable String attributionTag) {
try {
- mService.finishOperation(getClientId(), op, uid, packageName, featureId);
+ mService.finishOperation(getClientId(), op, uid, packageName, attributionTag);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -7767,15 +7995,15 @@
* Collect a noted op for the current process.
*
* @param op The noted op
- * @param featureId The feature the op is noted for
+ * @param attributionTag The attribution tag the op is noted for
*/
- private void collectNotedOpForSelf(int op, @Nullable String featureId) {
+ private void collectNotedOpForSelf(int op, @Nullable String attributionTag) {
synchronized (sLock) {
- if (sNotedAppOpsCollector != null) {
- sNotedAppOpsCollector.onSelfNoted(new SyncNotedAppOp(op, featureId));
+ if (sOnOpNotedCallback != null) {
+ sOnOpNotedCallback.onSelfNoted(new SyncNotedAppOp(op, attributionTag));
}
}
- sMessageCollector.onSelfNoted(new SyncNotedAppOp(op, featureId));
+ sMessageCollector.onSelfNoted(new SyncNotedAppOp(op, attributionTag));
}
/**
@@ -7784,9 +8012,9 @@
* <p> Delivered to caller via {@link #prefixParcelWithAppOpsIfNeeded}
*
* @param op The noted op
- * @param featureId The feature the op is noted for
+ * @param attributionTag The attribution tag the op is noted for
*/
- private void collectNotedOpSync(int op, @Nullable String featureId) {
+ private void collectNotedOpSync(int op, @Nullable String attributionTag) {
// If this is inside of a two-way binder call:
// We are inside of a two-way binder call. Delivered to caller via
// {@link #prefixParcelWithAppOpsIfNeeded}
@@ -7796,16 +8024,16 @@
sAppOpsNotedInThisBinderTransaction.set(appOpsNoted);
}
- long[] appOpsNotedForFeature = appOpsNoted.get(featureId);
- if (appOpsNotedForFeature == null) {
- appOpsNotedForFeature = new long[2];
- appOpsNoted.put(featureId, appOpsNotedForFeature);
+ long[] appOpsNotedForAttribution = appOpsNoted.get(attributionTag);
+ if (appOpsNotedForAttribution == null) {
+ appOpsNotedForAttribution = new long[2];
+ appOpsNoted.put(attributionTag, appOpsNotedForAttribution);
}
if (op < 64) {
- appOpsNotedForFeature[0] |= 1L << op;
+ appOpsNotedForAttribution[0] |= 1L << op;
} else {
- appOpsNotedForFeature[1] |= 1L << (op - 64);
+ appOpsNotedForAttribution[1] |= 1L << (op - 64);
}
}
@@ -7886,10 +8114,10 @@
p.writeInt(Parcel.EX_HAS_NOTED_APPOPS_REPLY_HEADER);
- int numFeatureWithNotesAppOps = notedAppOps.size();
- p.writeInt(numFeatureWithNotesAppOps);
+ int numAttributionWithNotesAppOps = notedAppOps.size();
+ p.writeInt(numAttributionWithNotesAppOps);
- for (int i = 0; i < numFeatureWithNotesAppOps; i++) {
+ for (int i = 0; i < numAttributionWithNotesAppOps; i++) {
p.writeString(notedAppOps.keyAt(i));
p.writeLong(notedAppOps.valueAt(i)[0]);
p.writeLong(notedAppOps.valueAt(i)[1]);
@@ -7907,10 +8135,10 @@
* @hide
*/
public static void readAndLogNotedAppops(@NonNull Parcel p) {
- int numFeaturesWithNotedAppOps = p.readInt();
+ int numAttributionsWithNotedAppOps = p.readInt();
- for (int i = 0; i < numFeaturesWithNotedAppOps; i++) {
- String featureId = p.readString();
+ for (int i = 0; i < numAttributionsWithNotedAppOps; i++) {
+ String attributionTag = p.readString();
long[] rawNotedAppOps = new long[2];
rawNotedAppOps[0] = p.readLong();
rawNotedAppOps[1] = p.readLong();
@@ -7921,47 +8149,59 @@
synchronized (sLock) {
for (int code = notedAppOps.nextSetBit(0); code != -1;
code = notedAppOps.nextSetBit(code + 1)) {
- if (sNotedAppOpsCollector != null) {
- sNotedAppOpsCollector.onNoted(new SyncNotedAppOp(code, featureId));
+ if (sOnOpNotedCallback != null) {
+ sOnOpNotedCallback.onNoted(new SyncNotedAppOp(code, attributionTag));
}
}
}
for (int code = notedAppOps.nextSetBit(0); code != -1;
code = notedAppOps.nextSetBit(code + 1)) {
- sMessageCollector.onNoted(new SyncNotedAppOp(code, featureId));
+ sMessageCollector.onNoted(new SyncNotedAppOp(code, attributionTag));
}
}
}
}
/**
- * Register a new {@link AppOpsCollector}.
+ * Set a new {@link OnOpNotedCallback}.
*
- * <p>There can only ever be one collector per process. If there currently is a collector
- * registered, it will be unregistered.
+ * <p>There can only ever be one collector per process. If there currently is another callback
+ * set, this will fail.
*
- * <p><b>Only appops related to dangerous permissions are collected.</b>
+ * @param asyncExecutor executor to execute {@link OnOpNotedCallback#onAsyncNoted} on, {@code
+ * null} to unset
+ * @param callback listener to set, {@code null} to unset
*
- * @param collector The collector to set or {@code null} to unregister.
+ * @throws IllegalStateException If another callback is already registered
*/
- public void setNotedAppOpsCollector(@Nullable AppOpsCollector collector) {
+ public void setOnOpNotedCallback(@Nullable @CallbackExecutor Executor asyncExecutor,
+ @Nullable OnOpNotedCallback callback) {
+ Preconditions.checkState((callback == null) == (asyncExecutor == null));
+
synchronized (sLock) {
- if (sNotedAppOpsCollector != null) {
+ if (callback == null) {
+ Preconditions.checkState(sOnOpNotedCallback != null,
+ "No callback is currently registered");
+
try {
mService.stopWatchingAsyncNoted(mContext.getPackageName(),
- sNotedAppOpsCollector.mAsyncCb);
+ sOnOpNotedCallback.mAsyncCb);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
- }
- sNotedAppOpsCollector = collector;
+ sOnOpNotedCallback = null;
+ } else {
+ Preconditions.checkState(sOnOpNotedCallback == null,
+ "Another callback is already registered");
- if (sNotedAppOpsCollector != null) {
+ callback.mAsyncExecutor = asyncExecutor;
+ sOnOpNotedCallback = callback;
+
List<AsyncNotedAppOp> missedAsyncOps = null;
try {
mService.startWatchingAsyncNoted(mContext.getPackageName(),
- sNotedAppOpsCollector.mAsyncCb);
+ sOnOpNotedCallback.mAsyncCb);
missedAsyncOps = mService.extractAsyncOps(mContext.getPackageName());
} catch (RemoteException e) {
e.rethrowFromSystemServer();
@@ -7971,10 +8211,9 @@
int numMissedAsyncOps = missedAsyncOps.size();
for (int i = 0; i < numMissedAsyncOps; i++) {
final AsyncNotedAppOp asyncNotedAppOp = missedAsyncOps.get(i);
- if (sNotedAppOpsCollector != null) {
- sNotedAppOpsCollector.getAsyncNotedExecutor().execute(
- () -> sNotedAppOpsCollector.onAsyncNoted(
- asyncNotedAppOp));
+ if (sOnOpNotedCallback != null) {
+ sOnOpNotedCallback.getAsyncNotedExecutor().execute(
+ () -> sOnOpNotedCallback.onAsyncNoted(asyncNotedAppOp));
}
}
}
@@ -7982,27 +8221,50 @@
}
}
+ // TODO moltmann: Remove
/**
- * @return {@code true} iff the process currently is currently collecting noted appops.
+ * Will be removed before R ships, leave it just to not break apps immediately.
*
- * @see #setNotedAppOpsCollector(AppOpsCollector)
+ * @removed
*
* @hide
*/
- public static boolean isCollectingNotedAppOps() {
- return sNotedAppOpsCollector != null;
+ @SystemApi
+ @Deprecated
+ public void setNotedAppOpsCollector(@Nullable AppOpsCollector collector) {
+ synchronized (sLock) {
+ if (collector != null) {
+ if (isListeningForOpNoted()) {
+ setOnOpNotedCallback(null, null);
+ }
+ setOnOpNotedCallback(new HandlerExecutor(Handler.getMain()), collector);
+ } else if (sOnOpNotedCallback != null) {
+ setOnOpNotedCallback(null, null);
+ }
+ }
}
/**
- * Callback an app can {@link #setNotedAppOpsCollector register} to monitor the app-ops the
- * system has tracked for it. I.e. each time any app calls {@link #noteOp} or {@link #startOp}
- * one of the callback methods of this object is called.
+ * @return {@code true} iff the process currently is currently collecting noted appops.
*
- * <p><b>There will be a callback for all app-ops related to runtime permissions, but not
+ * @see #setOnOpNotedCallback
+ *
+ * @hide
+ */
+ public static boolean isListeningForOpNoted() {
+ return sOnOpNotedCallback != null;
+ }
+
+ /**
+ * Callback an app can {@link #setOnOpNotedCallback set} to monitor the app-ops the
+ * system has tracked for it. I.e. each time any app calls {@link #noteOp} or {@link #startOp}
+ * one of a method of this object is called.
+ *
+ * <p><b>There will be a call for all app-ops related to runtime permissions, but not
* necessarily for all other app-ops.
*
* <pre>
- * setNotedAppOpsCollector(new AppOpsCollector() {
+ * setOnOpNotedCallback(getMainExecutor(), new OnOpNotedCallback() {
* ArraySet<Pair<String, String>> opsNotedForThisProcess = new ArraySet<>();
*
* private synchronized void addAccess(String op, String accessLocation) {
@@ -8027,24 +8289,36 @@
* });
* </pre>
*
- * @see #setNotedAppOpsCollector
+ * @see #setOnOpNotedCallback
*/
- public abstract static class AppOpsCollector {
+ public abstract static class OnOpNotedCallback {
+ private @NonNull Executor mAsyncExecutor;
+
/** Callback registered with the system. This will receive the async notes ops */
private final IAppOpsAsyncNotedCallback mAsyncCb = new IAppOpsAsyncNotedCallback.Stub() {
@Override
public void opNoted(AsyncNotedAppOp op) {
Objects.requireNonNull(op);
- getAsyncNotedExecutor().execute(() -> onAsyncNoted(op));
+ long token = Binder.clearCallingIdentity();
+ try {
+ getAsyncNotedExecutor().execute(() -> onAsyncNoted(op));
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
};
+ // TODO moltmann: Remove
/**
+ * Will be removed before R ships.
+ *
* @return The executor for the system to use when calling {@link #onAsyncNoted}.
+ *
+ * @hide
*/
- public @NonNull Executor getAsyncNotedExecutor() {
- return new HandlerExecutor(Handler.getMain());
+ protected @NonNull Executor getAsyncNotedExecutor() {
+ return mAsyncExecutor;
}
/**
@@ -8054,7 +8328,7 @@
* <p>Called on the calling thread before the API returns. This allows the app to e.g.
* collect stack traces to figure out where the access came from.
*
- * @param op The op noted
+ * @param op op noted
*/
public abstract void onNoted(@NonNull SyncNotedAppOp op);
@@ -8064,7 +8338,7 @@
* <p>This is very similar to {@link #onNoted} only that the tracking was not caused by the
* API provider in a separate process, but by one in the app's own process.
*
- * @param op The op noted
+ * @param op op noted
*/
public abstract void onSelfNoted(@NonNull SyncNotedAppOp op);
@@ -8076,14 +8350,30 @@
* guaranteed. Due to how async calls work in Android this might even be delivered slightly
* before the private data is delivered to the app.
*
- * <p>If the app is not running or no {@link AppOpsCollector} is registered a small amount
- * of noted app-ops are buffered and then delivered as soon as a collector is registered.
+ * <p>If the app is not running or no {@link OnOpNotedCallback} is registered a small amount
+ * of noted app-ops are buffered and then delivered as soon as a listener is registered.
*
- * @param asyncOp The op noted
+ * @param asyncOp op noted
*/
public abstract void onAsyncNoted(@NonNull AsyncNotedAppOp asyncOp);
}
+ // TODO moltmann: Remove
+ /**
+ * Will be removed before R ships, leave it just to not break apps immediately.
+ *
+ * @removed
+ *
+ * @hide
+ */
+ @SystemApi
+ @Deprecated
+ public abstract static class AppOpsCollector extends OnOpNotedCallback {
+ public @NonNull Executor getAsyncNotedExecutor() {
+ return new HandlerExecutor(Handler.getMain());
+ }
+ };
+
/**
* Generate a stack trace used for noted app-ops logging.
*
@@ -8492,4 +8782,24 @@
public static int leftCircularDistance(int from, int to, int size) {
return (to + size - from) % size;
}
+
+ /**
+ * Helper method for noteOp, startOp and noteProxyOp to call AppOpsService to collect/log
+ * stack traces
+ *
+ * <p> For each call, the stacktrace op code, package name and long version code will be
+ * passed along where it will be logged/collected
+ *
+ * @param op The operation to note
+ */
+ private void collectNoteOpCallsForValidation(int op) {
+ if (NOTE_OP_COLLECTION_ENABLED) {
+ try {
+ mService.collectNoteOpCallsForValidation(getFormattedStackTrace(),
+ op, mContext.getOpPackageName(), mContext.getApplicationInfo().longVersionCode);
+ } catch (RemoteException e) {
+ // Swallow error, only meant for logging ops, should not affect flow of the code
+ }
+ }
+ }
}
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 87d33a9..18df401 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -840,6 +840,27 @@
}
@Override
+ public boolean setAutoRevokeWhitelisted(
+ @NonNull String packageName, boolean whitelisted) {
+ try {
+ final int userId = getUserId();
+ return mPermissionManager.setAutoRevokeWhitelisted(packageName, whitelisted, userId);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
+ public boolean isAutoRevokeWhitelisted(@NonNull String packageName) {
+ try {
+ final int userId = getUserId();
+ return mPermissionManager.isAutoRevokeWhitelisted(packageName, userId);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ @Override
public boolean removeWhitelistedRestrictedPermission(@NonNull String packageName,
@NonNull String permName, @PermissionWhitelistFlags int flags) {
try {
@@ -3337,6 +3358,15 @@
}
}
+ @Override
+ public boolean isAutoRevokeWhitelisted() {
+ try {
+ return mPM.isAutoRevokeWhitelisted(mContext.getPackageName());
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
public void setMimeGroup(String mimeGroup, Set<String> mimeTypes) {
try {
mPM.setMimeGroup(mContext.getPackageName(), mimeGroup,
diff --git a/core/java/android/app/AsyncNotedAppOp.java b/core/java/android/app/AsyncNotedAppOp.java
index 6b1afda..b0c2762c 100644
--- a/core/java/android/app/AsyncNotedAppOp.java
+++ b/core/java/android/app/AsyncNotedAppOp.java
@@ -16,6 +16,7 @@
package android.app;
+import android.annotation.CurrentTimeMillisLong;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -23,13 +24,15 @@
import com.android.internal.annotations.Immutable;
import com.android.internal.util.DataClass;
+import com.android.internal.util.Preconditions;
/**
* When an {@link AppOpsManager#noteOp(String, int, String, String, String) app-op is noted} and the
- * app the app-op is noted for has a {@link AppOpsManager.AppOpsCollector} registered the note-event
- * needs to be delivered to the collector. Usually this is done via an {@link SyncNotedAppOp}, but
- * in some cases this is not possible. In this case an {@link AsyncNotedAppOp} is send to the system
- * server and then forwarded to the {@link AppOpsManager.AppOpsCollector} in the app.
+ * app the app-op is noted for has a {@link AppOpsManager.OnOpNotedCallback} registered the
+ * note-event needs to be delivered to the callback. Usually this is done via an
+ * {@link SyncNotedAppOp}, but in some cases this is not possible. In this case an
+ * {@link AsyncNotedAppOp} is send to the system server and then forwarded to the
+ * {@link AppOpsManager.OnOpNotedCallback} in the app.
*/
@Immutable
@DataClass(genEqualsHashCode = true,
@@ -40,19 +43,19 @@
@DataClass.Suppress({"getOpCode"})
public final class AsyncNotedAppOp implements Parcelable {
/** Op that was noted */
- private final @IntRange(from = 0, to = AppOpsManager._NUM_OP - 1) int mOpCode;
+ private final @IntRange(from = 0) int mOpCode;
/** Uid that noted the op */
private final @IntRange(from = 0) int mNotingUid;
- /** {@link android.content.Context#createFeatureContext Feature} in the app */
- private final @Nullable String mFeatureId;
+ /** {@link android.content.Context#createAttributionContext attribution tag} */
+ private final @Nullable String mAttributionTag;
/** Message associated with the noteOp. This message is set by the app noting the op */
private final @NonNull String mMessage;
/** Milliseconds since epoch when the op was noted */
- private final @IntRange(from = 0) long mTime;
+ private final @CurrentTimeMillisLong long mTime;
/**
* @return Op that was noted.
@@ -61,9 +64,15 @@
return AppOpsManager.opToPublicName(mOpCode);
}
+ //TODO eugenesusla: support inlinable expressions in annotation params of @DataClass members to
+ // allow validating via @IntRange(from = 0, to = AppOpsManager._NUM_OP - 1)
+ private void onConstructed() {
+ Preconditions.checkArgumentInRange(mOpCode, 0, AppOpsManager._NUM_OP - 1, "opCode");
+ }
- // Code below generated by codegen v1.0.14.
+
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -83,8 +92,8 @@
* Op that was noted
* @param notingUid
* Uid that noted the op
- * @param featureId
- * {@link android.content.Context#createFeatureContext Feature} in the app
+ * @param attributionTag
+ * {@link android.content.Context#createAttributionContext attribution tag}
* @param message
* Message associated with the noteOp. This message is set by the app noting the op
* @param time
@@ -93,30 +102,28 @@
*/
@DataClass.Generated.Member
public AsyncNotedAppOp(
- @IntRange(from = 0, to = AppOpsManager._NUM_OP - 1) int opCode,
+ @IntRange(from = 0) int opCode,
@IntRange(from = 0) int notingUid,
- @Nullable String featureId,
+ @Nullable String attributionTag,
@NonNull String message,
- @IntRange(from = 0) long time) {
+ @CurrentTimeMillisLong long time) {
this.mOpCode = opCode;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mOpCode,
- "from", 0,
- "to", AppOpsManager._NUM_OP - 1);
+ "from", 0);
this.mNotingUid = notingUid;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mNotingUid,
"from", 0);
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
this.mMessage = message;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mMessage);
this.mTime = time;
com.android.internal.util.AnnotationValidations.validate(
- IntRange.class, null, mTime,
- "from", 0);
+ CurrentTimeMillisLong.class, null, mTime);
- // onConstructed(); // You can define this method to get a callback
+ onConstructed();
}
/**
@@ -128,11 +135,11 @@
}
/**
- * {@link android.content.Context#createFeatureContext Feature} in the app
+ * {@link android.content.Context#createAttributionContext attribution tag}
*/
@DataClass.Generated.Member
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getAttributionTag() {
+ return mAttributionTag;
}
/**
@@ -147,7 +154,7 @@
* Milliseconds since epoch when the op was noted
*/
@DataClass.Generated.Member
- public @IntRange(from = 0) long getTime() {
+ public @CurrentTimeMillisLong long getTime() {
return mTime;
}
@@ -166,7 +173,7 @@
return true
&& mOpCode == that.mOpCode
&& mNotingUid == that.mNotingUid
- && java.util.Objects.equals(mFeatureId, that.mFeatureId)
+ && java.util.Objects.equals(mAttributionTag, that.mAttributionTag)
&& java.util.Objects.equals(mMessage, that.mMessage)
&& mTime == that.mTime;
}
@@ -180,7 +187,7 @@
int _hash = 1;
_hash = 31 * _hash + mOpCode;
_hash = 31 * _hash + mNotingUid;
- _hash = 31 * _hash + java.util.Objects.hashCode(mFeatureId);
+ _hash = 31 * _hash + java.util.Objects.hashCode(mAttributionTag);
_hash = 31 * _hash + java.util.Objects.hashCode(mMessage);
_hash = 31 * _hash + Long.hashCode(mTime);
return _hash;
@@ -193,11 +200,11 @@
// void parcelFieldName(Parcel dest, int flags) { ... }
byte flg = 0;
- if (mFeatureId != null) flg |= 0x4;
+ if (mAttributionTag != null) flg |= 0x4;
dest.writeByte(flg);
dest.writeInt(mOpCode);
dest.writeInt(mNotingUid);
- if (mFeatureId != null) dest.writeString(mFeatureId);
+ if (mAttributionTag != null) dest.writeString(mAttributionTag);
dest.writeString(mMessage);
dest.writeLong(mTime);
}
@@ -216,29 +223,27 @@
byte flg = in.readByte();
int opCode = in.readInt();
int notingUid = in.readInt();
- String featureId = (flg & 0x4) == 0 ? null : in.readString();
+ String attributionTag = (flg & 0x4) == 0 ? null : in.readString();
String message = in.readString();
long time = in.readLong();
this.mOpCode = opCode;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mOpCode,
- "from", 0,
- "to", AppOpsManager._NUM_OP - 1);
+ "from", 0);
this.mNotingUid = notingUid;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mNotingUid,
"from", 0);
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
this.mMessage = message;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mMessage);
this.mTime = time;
com.android.internal.util.AnnotationValidations.validate(
- IntRange.class, null, mTime,
- "from", 0);
+ CurrentTimeMillisLong.class, null, mTime);
- // onConstructed(); // You can define this method to get a callback
+ onConstructed();
}
@DataClass.Generated.Member
@@ -256,10 +261,10 @@
};
@DataClass.Generated(
- time = 1581728574427L,
- codegenVersion = "1.0.14",
+ time = 1583866239013L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/core/java/android/app/AsyncNotedAppOp.java",
- inputSignatures = "private final @android.annotation.IntRange(from=0L, to=96L) int mOpCode\nprivate final @android.annotation.IntRange(from=0L) int mNotingUid\nprivate final @android.annotation.Nullable java.lang.String mFeatureId\nprivate final @android.annotation.NonNull java.lang.String mMessage\nprivate final @android.annotation.IntRange(from=0L) long mTime\npublic @android.annotation.NonNull java.lang.String getOp()\nclass AsyncNotedAppOp extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genAidl=true, genHiddenConstructor=true)")
+ inputSignatures = "private final @android.annotation.IntRange(from=0L) int mOpCode\nprivate final @android.annotation.IntRange(from=0L) int mNotingUid\nprivate final @android.annotation.Nullable java.lang.String mAttributionTag\nprivate final @android.annotation.NonNull java.lang.String mMessage\nprivate final @android.annotation.CurrentTimeMillisLong long mTime\npublic @android.annotation.NonNull java.lang.String getOp()\nprivate void onConstructed()\nclass AsyncNotedAppOp extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genAidl=true, genHiddenConstructor=true)")
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 2873b10..9ccfe8d 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -219,8 +219,8 @@
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private final String mOpPackageName;
- /** If of feature this context is for */
- private final @Nullable String mFeatureId;
+ /** Attribution tag of this context */
+ private final @Nullable String mAttributionTag;
private final @NonNull ResourcesManager mResourcesManager;
@UnsupportedAppUsage
@@ -421,8 +421,8 @@
/** @hide */
@Override
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getAttributionTag() {
+ return mAttributionTag;
}
@Override
@@ -1026,10 +1026,10 @@
public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
try {
ActivityTaskManager.getService().startActivityAsUser(
- mMainThread.getApplicationThread(), getBasePackageName(), getFeatureId(), intent,
- intent.resolveTypeIfNeeded(getContentResolver()),
- null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
- user.getIdentifier());
+ mMainThread.getApplicationThread(), getBasePackageName(), getAttributionTag(),
+ intent, intent.resolveTypeIfNeeded(getContentResolver()),
+ null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
+ user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1109,9 +1109,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false,
- getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false,
+ false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1126,9 +1126,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
- null, false, false, getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions,
+ AppOpsManager.OP_NONE, null, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1141,9 +1141,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
- null, false, false, getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions,
+ AppOpsManager.OP_NONE, null, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1156,9 +1156,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
- null, false, false, user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions,
+ AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1173,9 +1173,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
- options, false, false, getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions,
+ AppOpsManager.OP_NONE, options, false, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1190,9 +1190,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false,
- getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false,
+ false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1207,9 +1207,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
- null, true, false, getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions,
+ AppOpsManager.OP_NONE, null, true, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1270,8 +1270,8 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, rd,
- initialCode, initialData, initialExtras, receiverPermissions, appOp,
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ rd, initialCode, initialData, initialExtras, receiverPermissions, appOp,
options, true, false, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1284,9 +1284,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false,
- user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false,
+ false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1307,9 +1307,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
- options, false, false, user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions,
+ AppOpsManager.OP_NONE, options, false, false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1324,9 +1324,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false,
- user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false,
+ false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1375,9 +1375,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, rd,
- initialCode, initialData, initialExtras, receiverPermissions,
- appOp, options, true, false, user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ rd, initialCode, initialData, initialExtras, receiverPermissions, appOp,
+ options, true, false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1416,9 +1416,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true,
- getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false,
+ true, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1452,9 +1452,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, rd,
- initialCode, initialData, initialExtras, null,
- AppOpsManager.OP_NONE, null, true, true, getUserId());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ rd, initialCode, initialData, initialExtras, null, AppOpsManager.OP_NONE, null,
+ true, true, getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1484,9 +1484,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true,
- user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false,
+ true, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1499,9 +1499,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, null,
- Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, options, false, true,
- user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ null, Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, options,
+ false, true, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1534,9 +1534,9 @@
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntentWithFeature(
- mMainThread.getApplicationThread(), getFeatureId(), intent, resolvedType, rd,
- initialCode, initialData, initialExtras, null,
- AppOpsManager.OP_NONE, null, true, true, user.getIdentifier());
+ mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
+ rd, initialCode, initialData, initialExtras, null, AppOpsManager.OP_NONE, null,
+ true, true, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1620,7 +1620,7 @@
}
try {
final Intent intent = ActivityManager.getService().registerReceiverWithFeature(
- mMainThread.getApplicationThread(), mBasePackageName, getFeatureId(), rd,
+ mMainThread.getApplicationThread(), mBasePackageName, getAttributionTag(), rd,
filter, broadcastPermission, userId, flags);
if (intent != null) {
intent.setExtrasClassLoader(getClassLoader());
@@ -1696,7 +1696,7 @@
ComponentName cn = ActivityManager.getService().startService(
mMainThread.getApplicationThread(), service,
service.resolveTypeIfNeeded(getContentResolver()), requireForeground,
- getOpPackageName(), getFeatureId(), user.getIdentifier());
+ getOpPackageName(), getAttributionTag(), user.getIdentifier());
if (cn != null) {
if (cn.getPackageName().equals("!")) {
throw new SecurityException(
@@ -1899,8 +1899,9 @@
public Object getSystemService(String name) {
// Check incorrect Context usage.
if (isUiComponent(name) && !isUiContext() && vmIncorrectContextUseEnabled()) {
- final String errorMessage = "Tried to access visual service " + name
- + " from a non-visual Context.";
+ final String errorMessage = "Tried to access visual service "
+ + SystemServiceRegistry.getSystemServiceClassName(name)
+ + " from a non-visual Context. ";
final String message = "Visual services, such as WindowManager, WallpaperService or "
+ "LayoutInflater should be accessed from Activity or other visual Context. "
+ "Use an Activity or a Context created with "
@@ -2285,14 +2286,14 @@
if (packageName.equals("system") || packageName.equals("android")) {
// The system resources are loaded in every application, so we can safely copy
// the context without reloading Resources.
- return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, null,
+ return new ContextImpl(this, mMainThread, mPackageInfo, mAttributionTag, null,
mToken, user, flags, null, null);
}
LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
if (pi != null) {
- ContextImpl c = new ContextImpl(this, mMainThread, pi, mFeatureId, null,
+ ContextImpl c = new ContextImpl(this, mMainThread, pi, mAttributionTag, null,
mToken, user, flags, null, null);
final int displayId = getDisplayId();
@@ -2329,7 +2330,7 @@
final String[] paths = mPackageInfo.getSplitPaths(splitName);
final ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo,
- mFeatureId, splitName, mToken, mUser, mFlags, classLoader, null);
+ mAttributionTag, splitName, mToken, mUser, mFlags, classLoader, null);
final int displayId = getDisplayId();
@@ -2353,7 +2354,7 @@
throw new IllegalArgumentException("overrideConfiguration must not be null");
}
- ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
+ ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mAttributionTag,
mSplitName, mToken, mUser, mFlags, mClassLoader, null);
final int displayId = getDisplayId();
@@ -2370,7 +2371,7 @@
throw new IllegalArgumentException("display must not be null");
}
- ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
+ ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mAttributionTag,
mSplitName, mToken, mUser, mFlags, mClassLoader, null);
final int displayId = display.getDisplayId();
@@ -2394,7 +2395,7 @@
}
ContextImpl createBaseWindowContext(IBinder token) {
- ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
+ ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mAttributionTag,
mSplitName, token, mUser, mFlags, mClassLoader, null);
context.mIsUiContext = true;
@@ -2420,8 +2421,8 @@
}
@Override
- public @NonNull Context createFeatureContext(@Nullable String featureId) {
- return new ContextImpl(this, mMainThread, mPackageInfo, featureId, mSplitName,
+ public @NonNull Context createAttributionContext(@Nullable String attributionTag) {
+ return new ContextImpl(this, mMainThread, mPackageInfo, attributionTag, mSplitName,
mToken, mUser, mFlags, mClassLoader, null);
}
@@ -2429,7 +2430,7 @@
public Context createDeviceProtectedStorageContext() {
final int flags = (mFlags & ~Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE)
| Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
- return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, mSplitName,
+ return new ContextImpl(this, mMainThread, mPackageInfo, mAttributionTag, mSplitName,
mToken, mUser, flags, mClassLoader, null);
}
@@ -2437,7 +2438,7 @@
public Context createCredentialProtectedStorageContext() {
final int flags = (mFlags & ~Context.CONTEXT_DEVICE_PROTECTED_STORAGE)
| Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
- return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, mSplitName,
+ return new ContextImpl(this, mMainThread, mPackageInfo, mAttributionTag, mSplitName,
mToken, mUser, flags, mClassLoader, null);
}
@@ -2700,7 +2701,7 @@
}
private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
- @NonNull LoadedApk packageInfo, @Nullable String featureId,
+ @NonNull LoadedApk packageInfo, @Nullable String attributionTag,
@Nullable String splitName, @Nullable IBinder activityToken, @Nullable UserHandle user,
int flags, @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName) {
mOuterContext = this;
@@ -2754,7 +2755,7 @@
}
mOpPackageName = overrideOpPackageName != null ? overrideOpPackageName : opPackageName;
- mFeatureId = featureId;
+ mAttributionTag = attributionTag;
mContentResolver = new ApplicationContentResolver(this, mainThread);
}
diff --git a/core/java/android/app/ITaskStackListener.aidl b/core/java/android/app/ITaskStackListener.aidl
index 28b28da..145d513 100644
--- a/core/java/android/app/ITaskStackListener.aidl
+++ b/core/java/android/app/ITaskStackListener.aidl
@@ -37,13 +37,15 @@
/**
* Called whenever IActivityManager.startActivity is called on an activity that is already
- * running in the pinned stack and the activity is not actually started, but the task is either
- * brought to the front or a new Intent is delivered to it.
+ * running, but the task is either brought to the front or a new Intent is delivered to it.
*
+ * @param task information about the task the activity was relaunched into
+ * @param homeVisible whether or not the home task is visible
* @param clearedTask whether or not the launch activity also cleared the task as a part of
* starting
*/
- void onPinnedActivityRestartAttempt(boolean clearedTask);
+ void onActivityRestartAttempt(in ActivityManager.RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask);
/**
* Called when we launched an activity that we forced to be resizable.
diff --git a/core/java/android/app/IWallpaperManager.aidl b/core/java/android/app/IWallpaperManager.aidl
index 34684c4..4cb8d93 100644
--- a/core/java/android/app/IWallpaperManager.aidl
+++ b/core/java/android/app/IWallpaperManager.aidl
@@ -175,11 +175,4 @@
* Called from SystemUI when it shows the AoD UI.
*/
oneway void setInAmbientMode(boolean inAmbientMode, long animationDuration);
-
- /**
- * Called when the wallpaper needs to zoom out.
- * The zoom value goes from 0 to 1 (inclusive) where 1 means fully zoomed out,
- * 0 means fully zoomed in
- */
- oneway void setWallpaperZoomOut(float zoom, String callingPackage, int displayId);
}
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index 18932c6..818a121 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -1720,11 +1720,10 @@
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
- int result = ActivityTaskManager.getService()
- .startActivity(whoThread, who.getBasePackageName(), who.getFeatureId(), intent,
- intent.resolveTypeIfNeeded(who.getContentResolver()),
- token, target != null ? target.mEmbeddedID : null,
- requestCode, 0, null, options);
+ int result = ActivityTaskManager.getService().startActivity(whoThread,
+ who.getBasePackageName(), who.getAttributionTag(), intent,
+ intent.resolveTypeIfNeeded(who.getContentResolver()), token,
+ target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
@@ -1793,9 +1792,9 @@
intents[i].prepareToLeaveProcess(who);
resolvedTypes[i] = intents[i].resolveTypeIfNeeded(who.getContentResolver());
}
- int result = ActivityTaskManager.getService()
- .startActivities(whoThread, who.getBasePackageName(), who.getFeatureId(), intents,
- resolvedTypes, token, options, userId);
+ int result = ActivityTaskManager.getService().startActivities(whoThread,
+ who.getBasePackageName(), who.getAttributionTag(), intents, resolvedTypes,
+ token, options, userId);
checkStartActivityResult(result, intents[0]);
return result;
} catch (RemoteException e) {
@@ -1860,10 +1859,10 @@
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
- int result = ActivityTaskManager.getService()
- .startActivity(whoThread, who.getBasePackageName(), who.getFeatureId(), intent,
- intent.resolveTypeIfNeeded(who.getContentResolver()),
- token, target, requestCode, 0, null, options);
+ int result = ActivityTaskManager.getService().startActivity(whoThread,
+ who.getBasePackageName(), who.getAttributionTag(), intent,
+ intent.resolveTypeIfNeeded(who.getContentResolver()), token, target,
+ requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
@@ -1927,11 +1926,10 @@
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
- int result = ActivityTaskManager.getService()
- .startActivityAsUser(whoThread, who.getBasePackageName(), who.getFeatureId(),
- intent, intent.resolveTypeIfNeeded(who.getContentResolver()),
- token, resultWho,
- requestCode, 0, null, options, user.getIdentifier());
+ int result = ActivityTaskManager.getService().startActivityAsUser(whoThread,
+ who.getBasePackageName(), who.getAttributionTag(), intent,
+ intent.resolveTypeIfNeeded(who.getContentResolver()), token, resultWho,
+ requestCode, 0, null, options, user.getIdentifier());
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
@@ -2022,7 +2020,7 @@
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = appTask.startActivity(whoThread.asBinder(), who.getBasePackageName(),
- who.getFeatureId(), intent,
+ who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 32e7d84..864af3d 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -21,6 +21,7 @@
import static android.graphics.drawable.Icon.TYPE_URI_ADAPTIVE_BITMAP;
import static com.android.internal.util.ContrastColorUtil.satisfiesTextContrast;
+import static com.android.internal.widget.ConversationLayout.CONVERSATION_LAYOUT_ENABLED;
import android.annotation.ColorInt;
import android.annotation.DimenRes;
@@ -389,6 +390,7 @@
STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_text);
STANDARD_LAYOUTS.add(R.layout.notification_template_material_inbox);
STANDARD_LAYOUTS.add(R.layout.notification_template_material_messaging);
+ STANDARD_LAYOUTS.add(R.layout.notification_template_material_conversation);
STANDARD_LAYOUTS.add(R.layout.notification_template_material_media);
STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_media);
STANDARD_LAYOUTS.add(R.layout.notification_template_header);
@@ -5138,7 +5140,7 @@
int color = isColorized(p) ? getPrimaryTextColor(p) : getSecondaryTextColor(p);
contentView.setDrawableTint(R.id.expand_button, false, color,
PorterDuff.Mode.SRC_ATOP);
- contentView.setInt(R.id.notification_header, "setOriginalNotificationColor",
+ contentView.setInt(R.id.expand_button, "setOriginalNotificationColor",
color);
}
@@ -6116,7 +6118,9 @@
}
private int getMessagingLayoutResource() {
- return R.layout.notification_template_material_messaging;
+ return CONVERSATION_LAYOUT_ENABLED
+ ? R.layout.notification_template_material_conversation
+ : R.layout.notification_template_material_messaging;
}
private int getActionLayoutResource() {
@@ -6221,6 +6225,17 @@
}
return loadHeaderAppName();
}
+
+ /**
+ * @return if this builder uses a template
+ *
+ * @hide
+ */
+ public boolean usesTemplate() {
+ return (mN.contentView == null && mN.headsUpContentView == null
+ && mN.bigContentView == null)
+ || (mStyle != null && mStyle.displayCustomViewInline());
+ }
}
/**
@@ -7379,7 +7394,7 @@
public RemoteViews makeContentView(boolean increasedHeight) {
mBuilder.mOriginalActions = mBuilder.mActions;
mBuilder.mActions = new ArrayList<>();
- RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */,
+ RemoteViews remoteViews = makeMessagingView(true /* isCollapsed */,
false /* hideLargeIcon */);
mBuilder.mActions = mBuilder.mOriginalActions;
mBuilder.mOriginalActions = null;
@@ -7469,19 +7484,18 @@
*/
@Override
public RemoteViews makeBigContentView() {
- return makeMessagingView(false /* displayImagesAtEnd */, true /* hideLargeIcon */);
+ return makeMessagingView(false /* isCollapsed */, true /* hideLargeIcon */);
}
/**
* Create a messaging layout.
*
- * @param displayImagesAtEnd should images be displayed at the end of the content instead
- * of inline.
+ * @param isCollapsed Should this use the collapsed layout
* @param hideRightIcons Should the reply affordance be shown at the end of the notification
* @return the created remoteView.
*/
@NonNull
- private RemoteViews makeMessagingView(boolean displayImagesAtEnd, boolean hideRightIcons) {
+ private RemoteViews makeMessagingView(boolean isCollapsed, boolean hideRightIcons) {
CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle)
? super.mBigContentTitle
: mConversationTitle;
@@ -7512,9 +7526,11 @@
p,
bindResult);
addExtras(mBuilder.mN.extras);
- // also update the end margin if there is an image
- contentView.setViewLayoutMarginEnd(R.id.notification_messaging,
- bindResult.getIconMarginEnd());
+ if (!CONVERSATION_LAYOUT_ENABLED) {
+ // also update the end margin if there is an image
+ contentView.setViewLayoutMarginEnd(R.id.notification_messaging,
+ bindResult.getIconMarginEnd());
+ }
contentView.setInt(R.id.status_bar_latest_event_content, "setLayoutColor",
mBuilder.isColorized(p) ? mBuilder.getPrimaryTextColor(p)
: mBuilder.resolveContrastColor(p));
@@ -7522,14 +7538,21 @@
mBuilder.getPrimaryTextColor(p));
contentView.setInt(R.id.status_bar_latest_event_content, "setMessageTextColor",
mBuilder.getSecondaryTextColor(p));
- contentView.setBoolean(R.id.status_bar_latest_event_content, "setDisplayImagesAtEnd",
- displayImagesAtEnd);
+ contentView.setInt(R.id.status_bar_latest_event_content,
+ "setNotificationBackgroundColor",
+ mBuilder.resolveBackgroundColor(p));
+ contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsCollapsed",
+ isCollapsed);
contentView.setIcon(R.id.status_bar_latest_event_content, "setAvatarReplacement",
avatarReplacement);
contentView.setCharSequence(R.id.status_bar_latest_event_content, "setNameReplacement",
nameReplacement);
contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsOneToOne",
isOneToOne);
+ contentView.setCharSequence(R.id.status_bar_latest_event_content,
+ "setConversationTitle", conversationTitle);
+ contentView.setIcon(R.id.status_bar_latest_event_content, "setLargeIcon",
+ mBuilder.mN.mLargeIcon);
contentView.setBundle(R.id.status_bar_latest_event_content, "setData",
mBuilder.mN.extras);
return contentView;
@@ -7590,9 +7613,11 @@
*/
@Override
public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
- RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */,
+ RemoteViews remoteViews = makeMessagingView(true /* isCollapsed */,
true /* hideLargeIcon */);
- remoteViews.setInt(R.id.notification_messaging, "setMaxDisplayedLines", 1);
+ if (!CONVERSATION_LAYOUT_ENABLED) {
+ remoteViews.setInt(R.id.notification_messaging, "setMaxDisplayedLines", 1);
+ }
return remoteViews;
}
diff --git a/core/java/android/app/NotificationChannel.java b/core/java/android/app/NotificationChannel.java
index 3f2ec44..94b237c 100644
--- a/core/java/android/app/NotificationChannel.java
+++ b/core/java/android/app/NotificationChannel.java
@@ -134,6 +134,7 @@
* @hide
*/
@SystemApi
+ @TestApi
public static final int USER_LOCKED_SOUND = 0x00000020;
/**
@@ -331,6 +332,7 @@
/**
* @hide
*/
+ @TestApi
public void lockFields(int field) {
mUserLockedFields |= field;
}
diff --git a/core/java/android/app/NotificationHistory.java b/core/java/android/app/NotificationHistory.java
index 8c2cc94..59dc999 100644
--- a/core/java/android/app/NotificationHistory.java
+++ b/core/java/android/app/NotificationHistory.java
@@ -22,6 +22,7 @@
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
+import android.util.Slog;
import java.util.ArrayList;
import java.util.Arrays;
@@ -107,9 +108,11 @@
", mChannelName='" + mChannelName + '\'' +
", mChannelId='" + mChannelId + '\'' +
", mUserId=" + mUserId +
+ ", mUid=" + mUid +
", mTitle='" + mTitle + '\'' +
", mText='" + mText + '\'' +
", mIcon=" + mIcon +
+ ", mPostedTimeMs=" + mPostedTimeMs +
", mConversationId=" + mConversationId +
'}';
}
@@ -285,9 +288,7 @@
if (!hasNextNotification()) {
return null;
}
-
HistoricalNotification n = readNotificationFromParcel(mParcel);
-
mIndex++;
if (!hasNextNotification()) {
mParcel.recycle();
diff --git a/core/java/android/app/PendingIntent.java b/core/java/android/app/PendingIntent.java
index f68c929..792f840 100644
--- a/core/java/android/app/PendingIntent.java
+++ b/core/java/android/app/PendingIntent.java
@@ -355,8 +355,8 @@
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManager.getService().getIntentSenderWithFeature(
- ActivityManager.INTENT_SENDER_ACTIVITY, packageName, context.getFeatureId(),
- null, null, requestCode, new Intent[] { intent },
+ ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
+ context.getAttributionTag(), null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, options, context.getUserId());
return target != null ? new PendingIntent(target) : null;
@@ -381,8 +381,8 @@
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManager.getService().getIntentSenderWithFeature(
- ActivityManager.INTENT_SENDER_ACTIVITY, packageName, context.getFeatureId(),
- null, null, requestCode, new Intent[] { intent },
+ ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
+ context.getAttributionTag(), null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, options, user.getIdentifier());
return target != null ? new PendingIntent(target) : null;
@@ -498,9 +498,9 @@
try {
IIntentSender target =
ActivityManager.getService().getIntentSenderWithFeature(
- ActivityManager.INTENT_SENDER_ACTIVITY, packageName, context.getFeatureId(),
- null, null, requestCode, intents, resolvedTypes, flags, options,
- context.getUserId());
+ ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
+ context.getAttributionTag(), null, null, requestCode, intents, resolvedTypes,
+ flags, options, context.getUserId());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -524,8 +524,8 @@
try {
IIntentSender target =
ActivityManager.getService().getIntentSenderWithFeature(
- ActivityManager.INTENT_SENDER_ACTIVITY, packageName, context.getFeatureId(),
- null, null, requestCode, intents, resolvedTypes,
+ ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
+ context.getAttributionTag(), null, null, requestCode, intents, resolvedTypes,
flags, options, user.getIdentifier());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
@@ -576,8 +576,8 @@
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManager.getService().getIntentSenderWithFeature(
- ActivityManager.INTENT_SENDER_BROADCAST, packageName, context.getFeatureId(),
- null, null, requestCode, new Intent[] { intent },
+ ActivityManager.INTENT_SENDER_BROADCAST, packageName,
+ context.getAttributionTag(), null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, null, userHandle.getIdentifier());
return target != null ? new PendingIntent(target) : null;
@@ -655,7 +655,7 @@
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManager.getService().getIntentSenderWithFeature(
- serviceKind, packageName, context.getFeatureId(),
+ serviceKind, packageName, context.getAttributionTag(),
null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, null, context.getUserId());
diff --git a/core/java/android/app/RuntimeAppOpAccessMessage.java b/core/java/android/app/RuntimeAppOpAccessMessage.java
index a81b8e7..a19f815 100644
--- a/core/java/android/app/RuntimeAppOpAccessMessage.java
+++ b/core/java/android/app/RuntimeAppOpAccessMessage.java
@@ -44,7 +44,7 @@
/** Name of package for which runtime app op access message was collected */
private final @NonNull String mPackageName;
/** Feature of package for which runtime app op access message was collected */
- private final @Nullable String mFeatureId;
+ private final @Nullable String mAttributionTag;
/** Message collected (including stacktrace for synchronous ops) */
private final @NonNull String mMessage;
/** Sampling strategy used to collect this message. */
@@ -63,8 +63,8 @@
* Op code of operation access which was collected
* @param packageName
* Name of package for which runtime app op access message was collected
- * @param featureId
- * Feature of package for which runtime app op access message was collected
+ * @param attributionTag
+ * Attribution tag for which runtime app op access message was collected
* @param message
* Message collected (including stacktrace for synchronous ops)
* @param samplingStrategy
@@ -75,7 +75,7 @@
@IntRange(from = 0L) int uid,
@IntRange(from = 0L) int opCode,
@NonNull String packageName,
- @Nullable String featureId,
+ @Nullable String attributionTag,
@NonNull String message,
@AppOpsManager.SamplingStrategy int samplingStrategy) {
this.mUid = uid;
@@ -90,7 +90,7 @@
this.mPackageName = packageName;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mPackageName);
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
this.mMessage = message;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mMessage);
@@ -134,11 +134,11 @@
}
/**
- * Feature of package for which runtime app op access message was collected
+ * Attribution tag for which runtime app op access message was collected
*/
@DataClass.Generated.Member
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getAttributionTag() {
+ return mAttributionTag;
}
/**
@@ -164,12 +164,12 @@
// void parcelFieldName(Parcel dest, int flags) { ... }
byte flg = 0;
- if (mFeatureId != null) flg |= 0x8;
+ if (mAttributionTag != null) flg |= 0x8;
dest.writeByte(flg);
dest.writeInt(mUid);
dest.writeInt(mOpCode);
dest.writeString(mPackageName);
- if (mFeatureId != null) dest.writeString(mFeatureId);
+ if (mAttributionTag != null) dest.writeString(mAttributionTag);
dest.writeString(mMessage);
dest.writeInt(mSamplingStrategy);
}
@@ -189,7 +189,7 @@
int uid = in.readInt();
int opCode = in.readInt();
String packageName = in.readString();
- String featureId = (flg & 0x8) == 0 ? null : in.readString();
+ String attributionTag = (flg & 0x8) == 0 ? null : in.readString();
String message = in.readString();
int samplingStrategy = in.readInt();
@@ -205,7 +205,7 @@
this.mPackageName = packageName;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mPackageName);
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
this.mMessage = message;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mMessage);
@@ -234,7 +234,7 @@
time = 1581517099127L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/app/RuntimeAppOpAccessMessage.java",
- inputSignatures = "private final @android.annotation.IntRange(from=0L) int mUid\nprivate final @android.annotation.IntRange(from=0L, to=AppOpsManager._NUM_OP - 1) int mOpCode\nprivate final @android.annotation.NonNull java.lang.String mPackageName\nprivate final @android.annotation.Nullable java.lang.String mFeatureId\nprivate final @android.annotation.NonNull java.lang.String mMessage\nprivate final @android.app.AppOpsManager.SamplingStrategy int mSamplingStrategy\npublic @android.annotation.NonNull java.lang.String getOp()\nclass RuntimeAppOpAccessMessage extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genConstructor=false)")*/
+ inputSignatures = "private final @android.annotation.IntRange(from=0L) int mUid\nprivate final @android.annotation.IntRange(from=0L, to=AppOpsManager._NUM_OP - 1) int mOpCode\nprivate final @android.annotation.NonNull java.lang.String mPackageName\nprivate final @android.annotation.Nullable java.lang.String mAttributionTag\nprivate final @android.annotation.NonNull java.lang.String mMessage\nprivate final @android.app.AppOpsManager.SamplingStrategy int mSamplingStrategy\npublic @android.annotation.NonNull java.lang.String getOp()\nclass RuntimeAppOpAccessMessage extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genConstructor=false)")*/
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index dc8269f..81396fe 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -34,6 +34,7 @@
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
+import android.view.contentcapture.ContentCaptureManager;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -306,7 +307,8 @@
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.java
* bind}
*/
-public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
+public abstract class Service extends ContextWrapper implements ComponentCallbacks2,
+ ContentCaptureManager.ContentCaptureClient {
private static final String TAG = "Service";
/**
@@ -817,8 +819,16 @@
writer.println("nothing to dump");
}
+ @Override
+ protected void attachBaseContext(Context newBase) {
+ super.attachBaseContext(newBase);
+ if (newBase != null) {
+ newBase.setContentCaptureOptions(getContentCaptureOptions());
+ }
+ }
+
// ------------------ Internal API ------------------
-
+
/**
* @hide
*/
@@ -835,6 +845,7 @@
mActivityManager = (IActivityManager)activityManager;
mStartCompatibility = getApplicationInfo().targetSdkVersion
< Build.VERSION_CODES.ECLAIR;
+ setContentCaptureOptions(application.getContentCaptureOptions());
}
/**
@@ -849,6 +860,18 @@
return mClassName;
}
+ /** @hide */
+ @Override
+ public final ContentCaptureManager.ContentCaptureClient getContentCaptureClient() {
+ return this;
+ }
+
+ /** @hide */
+ @Override
+ public final ComponentName contentCaptureClientGetComponentName() {
+ return new ComponentName(this, mClassName);
+ }
+
// set by the thread after the constructor and before onCreate(Bundle icicle) is called.
@UnsupportedAppUsage
private ActivityThread mThread = null;
diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java
index 42563b5..1329fa4 100644
--- a/core/java/android/app/StatusBarManager.java
+++ b/core/java/android/app/StatusBarManager.java
@@ -399,7 +399,6 @@
* {@code false}, re-enables expansion of the status bar.
* @hide
*/
- @SystemApi
@TestApi
@RequiresPermission(android.Manifest.permission.STATUS_BAR)
public void setDisabledForSimNetworkLock(boolean disabled) {
diff --git a/core/java/android/app/SyncNotedAppOp.java b/core/java/android/app/SyncNotedAppOp.java
index aa11b95..0a880dc 100644
--- a/core/java/android/app/SyncNotedAppOp.java
+++ b/core/java/android/app/SyncNotedAppOp.java
@@ -28,9 +28,9 @@
* Description of an app-op that was noted for the current process.
*
* <p>This is either delivered after a
- * {@link AppOpsManager.AppOpsCollector#onNoted(SyncNotedAppOp) two way binder call} or
+ * {@link AppOpsManager.OnOpNotedCallback#onNoted(SyncNotedAppOp) two way binder call} or
* when the app
- * {@link AppOpsManager.AppOpsCollector#onSelfNoted(SyncNotedAppOp) notes an app-op for
+ * {@link AppOpsManager.OnOpNotedCallback#onSelfNoted(SyncNotedAppOp) notes an app-op for
* itself}.
*/
@Immutable
@@ -43,24 +43,24 @@
/** op code of synchronous appop noted */
private final @IntRange(from = 0L, to = AppOpsManager._NUM_OP - 1) int mOpCode;
- /** featureId of synchronous appop noted */
- private final @Nullable String mFeatureId;
+ /** attributionTag of synchronous appop noted */
+ private final @Nullable String mAttributionTag;
/**
* Creates a new SyncNotedAppOp.
*
* @param opCode
* op code of synchronous appop noted
- * @param featureId
- * featureId of synchronous appop noted
+ * @param attributionTag
+ * attributionTag of synchronous appop noted
*/
- public SyncNotedAppOp(@IntRange(from = 0L) int opCode, @Nullable String featureId) {
+ public SyncNotedAppOp(@IntRange(from = 0L) int opCode, @Nullable String attributionTag) {
this.mOpCode = opCode;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mOpCode,
"from", 0,
"to", AppOpsManager._NUM_OP - 1);
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
}
/**
@@ -84,11 +84,11 @@
/**
- * featureId of synchronous appop noted
+ * attributionTag of synchronous appop noted
*/
@DataClass.Generated.Member
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getAttributionTag() {
+ return mAttributionTag;
}
@Override
@@ -105,7 +105,7 @@
//noinspection PointlessBooleanExpression
return true
&& mOpCode == that.mOpCode
- && java.util.Objects.equals(mFeatureId, that.mFeatureId);
+ && java.util.Objects.equals(mAttributionTag, that.mAttributionTag);
}
@Override
@@ -116,7 +116,7 @@
int _hash = 1;
_hash = 31 * _hash + mOpCode;
- _hash = 31 * _hash + java.util.Objects.hashCode(mFeatureId);
+ _hash = 31 * _hash + java.util.Objects.hashCode(mAttributionTag);
return _hash;
}
@@ -127,10 +127,10 @@
// void parcelFieldName(Parcel dest, int flags) { ... }
byte flg = 0;
- if (mFeatureId != null) flg |= 0x2;
+ if (mAttributionTag != null) flg |= 0x2;
dest.writeByte(flg);
dest.writeInt(mOpCode);
- if (mFeatureId != null) dest.writeString(mFeatureId);
+ if (mAttributionTag != null) dest.writeString(mAttributionTag);
}
@Override
@@ -146,14 +146,14 @@
byte flg = in.readByte();
int opCode = in.readInt();
- String featureId = (flg & 0x2) == 0 ? null : in.readString();
+ String attributionTag = (flg & 0x2) == 0 ? null : in.readString();
this.mOpCode = opCode;
com.android.internal.util.AnnotationValidations.validate(
IntRange.class, null, mOpCode,
"from", 0,
"to", AppOpsManager._NUM_OP - 1);
- this.mFeatureId = featureId;
+ this.mAttributionTag = attributionTag;
// onConstructed(); // You can define this method to get a callback
}
@@ -176,7 +176,7 @@
time = 1579188889960L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/app/SyncNotedAppOp.java",
- inputSignatures = "private final @android.annotation.IntRange(from=0L, to=AppOpsManager._NUM_OP - 1) int mOpCode\nprivate final @android.annotation.Nullable java.lang.String mFeatureId\npublic @android.annotation.NonNull java.lang.String getOp()\npublic @android.annotation.SystemApi int getOpCode()\nclass SyncNotedAppOp extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genConstructor=false)")*/
+ inputSignatures = "private final @android.annotation.IntRange(from=0L, to=AppOpsManager._NUM_OP - 1) int mOpCode\nprivate final @android.annotation.Nullable java.lang.String mAttributionTag\npublic @android.annotation.NonNull java.lang.String getOp()\npublic @android.annotation.SystemApi int getOpCode()\nclass SyncNotedAppOp extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genConstructor=false)")*/
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index a3bcc9c..e8f30df 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -19,6 +19,7 @@
import android.accounts.AccountManager;
import android.accounts.IAccountManager;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.app.ContextImpl.ServiceInitializationState;
import android.app.admin.DevicePolicyManager;
@@ -227,6 +228,8 @@
new ArrayMap<Class<?>, String>();
private static final Map<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
new ArrayMap<String, ServiceFetcher<?>>();
+ private static final Map<String, String> SYSTEM_SERVICE_CLASS_NAMES = new ArrayMap<>();
+
private static int sServiceCacheSize;
private static volatile boolean sInitializing;
@@ -1389,6 +1392,19 @@
@NonNull Class<T> serviceClass, @NonNull ServiceFetcher<T> serviceFetcher) {
SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
+ SYSTEM_SERVICE_CLASS_NAMES.put(serviceName, serviceClass.getSimpleName());
+ }
+
+ /**
+ * Returns system service class name by system service name. This method is mostly an inverse of
+ * {@link #getSystemServiceName(Class)}
+ *
+ * @return system service class name. {@code null} if service name is invalid.
+ * @hide
+ */
+ @Nullable
+ public static String getSystemServiceClassName(@NonNull String name) {
+ return SYSTEM_SERVICE_CLASS_NAMES.get(name);
}
/**
diff --git a/core/java/android/app/TaskInfo.java b/core/java/android/app/TaskInfo.java
index 1a84547..b2dd0ef 100644
--- a/core/java/android/app/TaskInfo.java
+++ b/core/java/android/app/TaskInfo.java
@@ -23,6 +23,7 @@
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Intent;
+import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Parcel;
import android.os.RemoteException;
@@ -161,6 +162,13 @@
*/
public @WindowConfiguration.ActivityType int topActivityType;
+ /**
+ * The {@link ActivityInfo} of the top activity in this task.
+ * @hide
+ */
+ @Nullable
+ public ActivityInfo topActivityInfo;
+
TaskInfo() {
// Do nothing
}
@@ -217,8 +225,11 @@
token = IWindowContainer.Stub.asInterface(source.readStrongBinder());
topActivityType = source.readInt();
pictureInPictureParams = source.readInt() != 0
- ? PictureInPictureParams.CREATOR.createFromParcel(source)
- : null;
+ ? PictureInPictureParams.CREATOR.createFromParcel(source)
+ : null;
+ topActivityInfo = source.readInt() != 0
+ ? ActivityInfo.CREATOR.createFromParcel(source)
+ : null;
}
/**
@@ -262,6 +273,12 @@
dest.writeInt(1);
pictureInPictureParams.writeToParcel(dest, flags);
}
+ if (topActivityInfo == null) {
+ dest.writeInt(0);
+ } else {
+ dest.writeInt(1);
+ topActivityInfo.writeToParcel(dest, flags);
+ }
}
@Override
@@ -278,6 +295,7 @@
+ " resizeMode=" + resizeMode
+ " token=" + token
+ " topActivityType=" + topActivityType
- + " pictureInPictureParams=" + pictureInPictureParams;
+ + " pictureInPictureParams=" + pictureInPictureParams
+ + " topActivityInfo=" + topActivityInfo;
}
}
diff --git a/core/java/android/app/TaskStackListener.java b/core/java/android/app/TaskStackListener.java
index b892b8e..93772de 100644
--- a/core/java/android/app/TaskStackListener.java
+++ b/core/java/android/app/TaskStackListener.java
@@ -16,6 +16,7 @@
package android.app;
+import android.app.ActivityManager.RunningTaskInfo;
import android.app.ActivityManager.TaskSnapshot;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
@@ -53,7 +54,8 @@
@Override
@UnsupportedAppUsage
- public void onPinnedActivityRestartAttempt(boolean clearedTask) throws RemoteException {
+ public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask) throws RemoteException {
}
@Override
@@ -68,14 +70,14 @@
}
@Override
- public void onActivityLaunchOnSecondaryDisplayFailed(ActivityManager.RunningTaskInfo taskInfo,
+ public void onActivityLaunchOnSecondaryDisplayFailed(RunningTaskInfo taskInfo,
int requestedDisplayId) throws RemoteException {
onActivityLaunchOnSecondaryDisplayFailed();
}
/**
* @deprecated see {@link
- * #onActivityLaunchOnSecondaryDisplayFailed(ActivityManager.RunningTaskInfo, int)}
+ * #onActivityLaunchOnSecondaryDisplayFailed(RunningTaskInfo, int)}
*/
@Deprecated
@UnsupportedAppUsage
@@ -84,7 +86,7 @@
@Override
@UnsupportedAppUsage
- public void onActivityLaunchOnSecondaryDisplayRerouted(ActivityManager.RunningTaskInfo taskInfo,
+ public void onActivityLaunchOnSecondaryDisplayRerouted(RunningTaskInfo taskInfo,
int requestedDisplayId) throws RemoteException {
}
@@ -98,13 +100,13 @@
}
@Override
- public void onTaskMovedToFront(ActivityManager.RunningTaskInfo taskInfo)
+ public void onTaskMovedToFront(RunningTaskInfo taskInfo)
throws RemoteException {
onTaskMovedToFront(taskInfo.taskId);
}
/**
- * @deprecated see {@link #onTaskMovedToFront(ActivityManager.RunningTaskInfo)}
+ * @deprecated see {@link #onTaskMovedToFront(RunningTaskInfo)}
*/
@Deprecated
@UnsupportedAppUsage
@@ -112,26 +114,26 @@
}
@Override
- public void onTaskRemovalStarted(ActivityManager.RunningTaskInfo taskInfo)
+ public void onTaskRemovalStarted(RunningTaskInfo taskInfo)
throws RemoteException {
onTaskRemovalStarted(taskInfo.taskId);
}
/**
- * @deprecated see {@link #onTaskRemovalStarted(ActivityManager.RunningTaskInfo)}
+ * @deprecated see {@link #onTaskRemovalStarted(RunningTaskInfo)}
*/
@Deprecated
public void onTaskRemovalStarted(int taskId) throws RemoteException {
}
@Override
- public void onTaskDescriptionChanged(ActivityManager.RunningTaskInfo taskInfo)
+ public void onTaskDescriptionChanged(RunningTaskInfo taskInfo)
throws RemoteException {
onTaskDescriptionChanged(taskInfo.taskId, taskInfo.taskDescription);
}
/**
- * @deprecated see {@link #onTaskDescriptionChanged(ActivityManager.RunningTaskInfo)}
+ * @deprecated see {@link #onTaskDescriptionChanged(RunningTaskInfo)}
*/
@Deprecated
public void onTaskDescriptionChanged(int taskId, ActivityManager.TaskDescription td)
@@ -166,7 +168,7 @@
}
@Override
- public void onBackPressedOnTaskRoot(ActivityManager.RunningTaskInfo taskInfo)
+ public void onBackPressedOnTaskRoot(RunningTaskInfo taskInfo)
throws RemoteException {
}
diff --git a/core/java/android/app/WallpaperManager.java b/core/java/android/app/WallpaperManager.java
index d9405e1..1b1568a 100644
--- a/core/java/android/app/WallpaperManager.java
+++ b/core/java/android/app/WallpaperManager.java
@@ -478,7 +478,7 @@
try {
Bundle params = new Bundle();
ParcelFileDescriptor pfd = mService.getWallpaperWithFeature(
- context.getOpPackageName(), context.getFeatureId(), this, FLAG_SYSTEM,
+ context.getOpPackageName(), context.getAttributionTag(), this, FLAG_SYSTEM,
params, userId);
if (pfd != null) {
@@ -1069,7 +1069,7 @@
try {
Bundle outParams = new Bundle();
return sGlobals.mService.getWallpaperWithFeature(mContext.getOpPackageName(),
- mContext.getFeatureId(), null, which, outParams, userId);
+ mContext.getAttributionTag(), null, which, outParams, userId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
} catch (SecurityException e) {
@@ -1858,13 +1858,12 @@
*
* @hide
*/
- public void setWallpaperZoomOut(float zoom) {
+ public void setWallpaperZoomOut(IBinder windowToken, float zoom) {
if (zoom < 0 || zoom > 1f) {
throw new IllegalArgumentException("zoom must be between 0 and one: " + zoom);
}
try {
- sGlobals.mService.setWallpaperZoomOut(zoom, mContext.getOpPackageName(),
- mContext.getDisplayId());
+ WindowManagerGlobal.getWindowSession().setWallpaperZoomOut(windowToken, zoom);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/core/java/android/app/WindowContext.java b/core/java/android/app/WindowContext.java
index 5684562..878993e 100644
--- a/core/java/android/app/WindowContext.java
+++ b/core/java/android/app/WindowContext.java
@@ -60,7 +60,6 @@
mWms = WindowManagerGlobal.getWindowManagerService();
mToken = new WindowTokenClient();
-
final ContextImpl contextImpl = createBaseWindowContext(base, mToken);
attachBaseContext(contextImpl);
contextImpl.setOuterContext(this);
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index b219394..5b8ee71 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -5215,6 +5215,10 @@
* <p>Because this method might take several seconds to complete, it should only be called from
* a worker thread. This method returns {@code null} when called from the main thread.
*
+ * <p>This method is not thread-safe, calling it from multiple threads at the same time will
+ * result in undefined behavior. If the calling thread is interrupted while the invocation is
+ * in-flight, it will eventually terminate and return {@code null}.
+ *
* <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
* have been given to access the key and certificates associated with this alias will be
* revoked.
@@ -5732,6 +5736,10 @@
throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
if (mService != null) {
try {
+ // Starting from Android R, the caller can pass the permission check in
+ // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
+ // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
+ // which is used by the NetworkStack mainline module.
return mService.isAlwaysOnVpnLockdownEnabled(admin);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -6001,7 +6009,7 @@
* @param admin Which {@link DeviceAdminReceiver} this request is associated with.
* @param required Whether auto time is set required or not.
* @throws SecurityException if {@code admin} is not a device owner.
- * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTime}
+ * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
* to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
* to prevent the user from changing this setting.
*/
@@ -6019,7 +6027,7 @@
/**
* @return true if auto time is required.
- * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTime}
+ * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
*/
@Deprecated
public boolean getAutoTimeRequired() {
@@ -6049,10 +6057,10 @@
* @throws SecurityException if caller is not a device owner, a profile owner for the
* primary user, or a profile owner of an organization-owned managed profile.
*/
- public void setAutoTime(@NonNull ComponentName admin, boolean enabled) {
+ public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
if (mService != null) {
try {
- mService.setAutoTime(admin, enabled);
+ mService.setAutoTimeEnabled(admin, enabled);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -6064,10 +6072,10 @@
* @throws SecurityException if caller is not a device owner, a profile owner for the
* primary user, or a profile owner of an organization-owned managed profile.
*/
- public boolean getAutoTime(@NonNull ComponentName admin) {
+ public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
if (mService != null) {
try {
- return mService.getAutoTime(admin);
+ return mService.getAutoTimeEnabled(admin);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -6090,11 +6098,11 @@
* @throws SecurityException if caller is not a device owner, a profile owner for the
* primary user, or a profile owner of an organization-owned managed profile.
*/
- public void setAutoTimeZone(@NonNull ComponentName admin, boolean enabled) {
+ public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
throwIfParentInstance("setAutoTimeZone");
if (mService != null) {
try {
- mService.setAutoTimeZone(admin, enabled);
+ mService.setAutoTimeZoneEnabled(admin, enabled);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -6106,11 +6114,11 @@
* @throws SecurityException if caller is not a device owner, a profile owner for the
* primary user, or a profile owner of an organization-owned managed profile.
*/
- public boolean getAutoTimeZone(@NonNull ComponentName admin) {
+ public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
throwIfParentInstance("getAutoTimeZone");
if (mService != null) {
try {
- return mService.getAutoTimeZone(admin);
+ return mService.getAutoTimeZoneEnabled(admin);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -8781,18 +8789,20 @@
}
/**
+ * This method is mostly deprecated.
+ * Most of the settings that still have an effect have dedicated setter methods or user
+ * restrictions. See individual settings for details.
+ * <p>
* Called by device owner to update {@link android.provider.Settings.Global} settings.
* Validation that the value of the setting is in the correct form for the setting type should
* be performed by the caller.
* <p>
* The settings that can be updated with this method are:
* <ul>
- * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
- * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
- * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
- * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
+ * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
+ * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
+ * debugging features and this setting to turn adb on.</li>
* <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
- * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
* <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
* available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
* {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
@@ -8800,6 +8810,17 @@
* setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
* </ul>
* <p>
+ * The following settings used to be supported, but can be controlled in other ways:
+ * <ul>
+ * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
+ * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
+ * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
+ * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
+ * instead.</li>
+ * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
+ * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
+ * </ul>
+ * <p>
* Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
* <ul>
* <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
@@ -8811,6 +8832,7 @@
* <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
* <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
* {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
+ * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
* </ul>
*
* @param admin Which {@link DeviceAdminReceiver} this request is associated with.
@@ -8989,6 +9011,11 @@
}
/**
+ * This method is mostly deprecated.
+ * Most of the settings that still have an effect have dedicated setter methods
+ * (e.g. {@link #setLocationEnabled}) or user restrictions.
+ * <p>
+ *
* Called by profile or device owners to update {@link android.provider.Settings.Secure}
* settings. Validation that the value of the setting is in the correct form for the setting
* type should be performed by the caller.
@@ -9001,7 +9028,7 @@
* <p>
* A device owner can additionally update the following settings:
* <ul>
- * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
+ * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
* </ul>
*
* <strong>Note: Starting from Android O, apps should no longer call this method with the
@@ -10355,19 +10382,23 @@
}
/**
- * Indicates the entity that controls the device or profile owner. Two users/profiles are
- * affiliated if the set of ids set by their device or profile owners intersect.
+ * Indicates the entity that controls the device. Two users are
+ * affiliated if the set of ids set by the device owner and the admin of the secondary user.
*
- * <p>A user/profile that is affiliated with the device owner user is considered to be
+ * <p>A user that is affiliated with the device owner user is considered to be
* affiliated with the device.
*
* <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
- * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
+ * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
* is created, until it becomes affiliated. Therefore it is recommended that the appropriate
- * affiliation ids are set by its profile owner as soon as possible after the user/profile is
+ * affiliation ids are set by its owner as soon as possible after the user is
* created.
+ * <p>
+ * Note: This method used to be available for affiliating device owner and profile
+ * owner. However, since Android 11, this combination is not possible. This method is now
+ * only useful for affiliating the primary user with managed secondary users.
*
- * @param admin Which profile or device owner this request is associated with.
+ * @param admin Which device owner, or owner of secondary user, this request is associated with.
* @param ids A set of opaque non-empty affiliation ids.
*
* @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
@@ -10399,10 +10430,10 @@
}
/**
- * Returns whether this user/profile is affiliated with the device.
+ * Returns whether this user is affiliated with the device.
* <p>
* By definition, the user that the device owner runs on is always affiliated with the device.
- * Any other user/profile is considered affiliated with the device if the set specified by its
+ * Any other user is considered affiliated with the device if the set specified by its
* profile owner via {@link #setAffiliationIds} intersects with the device owner's.
* @see #setAffiliationIds
*/
@@ -10706,14 +10737,18 @@
}
/**
- * Called by a device owner to bind to a service from a profile owner or vice versa.
- * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
- * device/profile owners are allowed to bind to services of another profile/device owner.
+ * Called by a device owner to bind to a service from a secondary managed user or vice versa.
+ * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
+ * device owner to bind to services of another managed user.
* <p>
* The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
* Note that the {@link Context} used to obtain this
* {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
* to bind to the {@link android.app.Service}.
+ * <p>
+ * Note: This method used to be available for communication between device owner and profile
+ * owner. However, since Android 11, this combination is not possible. This method is now
+ * only useful for communication between device owner and managed secondary users.
*
* @param admin Which {@link DeviceAdminReceiver} this request is associated with.
* @param serviceIntent Identifies the service to connect to. The Intent must specify either an
@@ -10751,14 +10786,11 @@
}
/**
- * Returns the list of target users that the calling device or profile owner can use when
- * calling {@link #bindDeviceAdminServiceAsUser}.
+ * Returns the list of target users that the calling device owner or owner of secondary user
+ * can use when calling {@link #bindDeviceAdminServiceAsUser}.
* <p>
- * A device owner can bind to a service from a profile owner and vice versa, provided that:
- * <ul>
- * <li>Both belong to the same package name.
- * <li>Both users are affiliated. See {@link #setAffiliationIds}.
- * </ul>
+ * A device owner can bind to a service from a secondary managed user and vice versa, provided
+ * that both users are affiliated. See {@link #setAffiliationIds}.
*/
public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
throwIfParentInstance("getBindDeviceAdminTargetUsers");
@@ -11824,18 +11856,19 @@
}
/**
- * Called by Device owner to set packages as protected. User will not be able to clear app
- * data or force-stop protected packages.
+ * Called by Device owner to disable user control over apps. User will not be able to clear
+ * app data or force-stop packages.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
- * @param packages The package names to protect.
+ * @param packages The package names for the apps.
* @throws SecurityException if {@code admin} is not a device owner.
*/
- public void setProtectedPackages(@NonNull ComponentName admin, @NonNull List<String> packages) {
- throwIfParentInstance("setProtectedPackages");
+ public void setUserControlDisabledPackages(@NonNull ComponentName admin,
+ @NonNull List<String> packages) {
+ throwIfParentInstance("setUserControlDisabledPackages");
if (mService != null) {
try {
- mService.setProtectedPackages(admin, packages);
+ mService.setUserControlDisabledPackages(admin, packages);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
@@ -11843,16 +11876,16 @@
}
/**
- * Returns the list of packages protected by the device owner.
+ * Returns the list of packages over which user control is disabled by the device owner.
*
* @param admin which {@link DeviceAdminReceiver} this request is associated with
* @throws SecurityException if {@code admin} is not a device owner.
*/
- public @NonNull List<String> getProtectedPackages(@NonNull ComponentName admin) {
- throwIfParentInstance("getProtectedPackages");
+ public @NonNull List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
+ throwIfParentInstance("getUserControlDisabledPackages");
if (mService != null) {
try {
- return mService.getProtectedPackages(admin);
+ return mService.getUserControlDisabledPackages(admin);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
@@ -11961,17 +11994,18 @@
* must handle this intent.
*
* @param admin Which {@link DeviceAdminReceiver} this request is associated with
- * @param timeoutMs Maximum time the profile is allowed to be off in milliseconds or 0 if
- * not limited.
+ * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
+ * not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
+ * smaller non-zero vaulue, 72 hours will be set instead.
* @throws IllegalStateException if the profile owner doesn't have an activity that handles
* {@link #ACTION_CHECK_POLICY_COMPLIANCE}
* @see #setPersonalAppsSuspended
*/
- public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMs) {
+ public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
throwIfParentInstance("setManagedProfileMaximumTimeOff");
if (mService != null) {
try {
- mService.setManagedProfileMaximumTimeOff(admin, timeoutMs);
+ mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index da48663..514677e 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -308,11 +308,11 @@
void setAutoTimeRequired(in ComponentName who, boolean required);
boolean getAutoTimeRequired();
- void setAutoTime(in ComponentName who, boolean enabled);
- boolean getAutoTime(in ComponentName who);
+ void setAutoTimeEnabled(in ComponentName who, boolean enabled);
+ boolean getAutoTimeEnabled(in ComponentName who);
- void setAutoTimeZone(in ComponentName who, boolean enabled);
- boolean getAutoTimeZone(in ComponentName who);
+ void setAutoTimeZoneEnabled(in ComponentName who, boolean enabled);
+ boolean getAutoTimeZoneEnabled(in ComponentName who);
void setForceEphemeralUsers(in ComponentName who, boolean forceEpehemeralUsers);
boolean getForceEphemeralUsers(in ComponentName who);
@@ -467,9 +467,9 @@
boolean setKeyGrantForApp(in ComponentName admin, String callerPackage, String alias, String packageName, boolean hasGrant);
- void setProtectedPackages(in ComponentName admin, in List<String> packages);
+ void setUserControlDisabledPackages(in ComponentName admin, in List<String> packages);
- List<String> getProtectedPackages(in ComponentName admin);
+ List<String> getUserControlDisabledPackages(in ComponentName admin);
void setCommonCriteriaModeEnabled(in ComponentName admin, boolean enabled);
boolean isCommonCriteriaModeEnabled(in ComponentName admin);
diff --git a/core/java/android/app/role/RoleManager.java b/core/java/android/app/role/RoleManager.java
index db4f1de..917eeb8 100644
--- a/core/java/android/app/role/RoleManager.java
+++ b/core/java/android/app/role/RoleManager.java
@@ -636,7 +636,6 @@
* @hide
*/
@Nullable
- @SystemApi
public String getDefaultSmsPackage(@UserIdInt int userId) {
try {
return mService.getDefaultSmsPackage(userId);
diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java
index 2c701b4..0d66198 100644
--- a/core/java/android/app/usage/UsageStatsManager.java
+++ b/core/java/android/app/usage/UsageStatsManager.java
@@ -288,25 +288,25 @@
*/
public static final int REASON_SUB_PREDICTED_RESTORED = 0x0001;
/**
- * The reason for restricting the app is unknown or undefined.
+ * The reason the system forced the app into the bucket is unknown or undefined.
* @hide
*/
- public static final int REASON_SUB_RESTRICT_UNDEFINED = 0x0000;
+ public static final int REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED = 0;
/**
* The app was unnecessarily using system resources (battery, memory, etc) in the background.
* @hide
*/
- public static final int REASON_SUB_RESTRICT_BACKGROUND_RESOURCE_USAGE = 0x0001;
+ public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE = 1 << 0;
/**
* The app was deemed to be intentionally abusive.
* @hide
*/
- public static final int REASON_SUB_RESTRICT_ABUSE = 0x0002;
+ public static final int REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE = 1 << 1;
/**
* The app was displaying buggy behavior.
* @hide
*/
- public static final int REASON_SUB_RESTRICT_BUGGY = 0x0003;
+ public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY = 1 << 2;
/** @hide */
@@ -322,6 +322,17 @@
@Retention(RetentionPolicy.SOURCE)
public @interface StandbyBuckets {}
+ /** @hide */
+ @IntDef(flag = true, prefix = {"REASON_SUB_FORCED_SYSTEM_FLAG_FLAG_"}, value = {
+ REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED,
+ REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE,
+ REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE,
+ REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface SystemForcedReasons {
+ }
+
/**
* Observer id of the registered observer for the group of packages that reached the usage
* time limit. Included as an extra in the PendingIntent that was registered.
@@ -1053,6 +1064,7 @@
/** @hide */
public static String reasonToString(int standbyReason) {
+ final int subReason = standbyReason & REASON_SUB_MASK;
StringBuilder sb = new StringBuilder();
switch (standbyReason & REASON_MAIN_MASK) {
case REASON_MAIN_DEFAULT:
@@ -1060,19 +1072,8 @@
break;
case REASON_MAIN_FORCED_BY_SYSTEM:
sb.append("s");
- switch (standbyReason & REASON_SUB_MASK) {
- case REASON_SUB_RESTRICT_ABUSE:
- sb.append("-ra");
- break;
- case REASON_SUB_RESTRICT_BACKGROUND_RESOURCE_USAGE:
- sb.append("-rbru");
- break;
- case REASON_SUB_RESTRICT_BUGGY:
- sb.append("-rb");
- break;
- case REASON_SUB_RESTRICT_UNDEFINED:
- sb.append("-r");
- break;
+ if (subReason > 0) {
+ sb.append("-").append(Integer.toBinaryString(subReason));
}
break;
case REASON_MAIN_FORCED_BY_USER:
@@ -1080,7 +1081,7 @@
break;
case REASON_MAIN_PREDICTED:
sb.append("p");
- switch (standbyReason & REASON_SUB_MASK) {
+ switch (subReason) {
case REASON_SUB_PREDICTED_RESTORED:
sb.append("-r");
break;
@@ -1091,7 +1092,7 @@
break;
case REASON_MAIN_USAGE:
sb.append("u");
- switch (standbyReason & REASON_SUB_MASK) {
+ switch (subReason) {
case REASON_SUB_USAGE_SYSTEM_INTERACTION:
sb.append("-si");
break;
diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java
index ccd8199..0d461f5 100644
--- a/core/java/android/appwidget/AppWidgetManager.java
+++ b/core/java/android/appwidget/AppWidgetManager.java
@@ -174,7 +174,7 @@
public static final String ACTION_APPWIDGET_CONFIGURE = "android.appwidget.action.APPWIDGET_CONFIGURE";
/**
- * An intent extra that contains one appWidgetId.
+ * An intent extra (int) that contains one appWidgetId.
* <p>
* The value will be an int that can be retrieved like this:
* {@sample frameworks/base/tests/appwidgets/AppWidgetHostTest/src/com/android/tests/appwidgethost/AppWidgetHostActivity.java getExtra_EXTRA_APPWIDGET_ID}
@@ -182,7 +182,7 @@
public static final String EXTRA_APPWIDGET_ID = "appWidgetId";
/**
- * A bundle extra that contains whether or not an app has finished restoring a widget.
+ * A bundle extra (boolean) that contains whether or not an app has finished restoring a widget.
* <p> After restore, the app should set OPTION_APPWIDGET_RESTORE_COMPLETED to true on its
* widgets followed by calling {@link #updateAppWidget} to update the views.
*
@@ -192,22 +192,26 @@
/**
- * A bundle extra that contains the lower bound on the current width, in dips, of a widget instance.
+ * A bundle extra (int) that contains the lower bound on the current width, in dips, of a
+ * widget instance.
*/
public static final String OPTION_APPWIDGET_MIN_WIDTH = "appWidgetMinWidth";
/**
- * A bundle extra that contains the lower bound on the current height, in dips, of a widget instance.
+ * A bundle extra (int) that contains the lower bound on the current height, in dips, of a
+ * widget instance.
*/
public static final String OPTION_APPWIDGET_MIN_HEIGHT = "appWidgetMinHeight";
/**
- * A bundle extra that contains the upper bound on the current width, in dips, of a widget instance.
+ * A bundle extra (int) that contains the upper bound on the current width, in dips, of a
+ * widget instance.
*/
public static final String OPTION_APPWIDGET_MAX_WIDTH = "appWidgetMaxWidth";
/**
- * A bundle extra that contains the upper bound on the current width, in dips, of a widget instance.
+ * A bundle extra (int) that contains the upper bound on the current width, in dips, of a
+ * widget instance.
*/
public static final String OPTION_APPWIDGET_MAX_HEIGHT = "appWidgetMaxHeight";
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index 66bfcbd..608b563 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -849,7 +849,7 @@
synchronized (mLock) {
if (sBluetoothLeScanner == null) {
sBluetoothLeScanner = new BluetoothLeScanner(mManagerService, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
}
}
return sBluetoothLeScanner;
@@ -1229,10 +1229,11 @@
public boolean factoryReset() {
try {
mServiceLock.readLock().lock();
- if (mService != null) {
- return mService.factoryReset();
+ if (mService != null && mService.factoryReset()
+ && mManagerService != null && mManagerService.onFactoryReset()) {
+ return true;
}
- Log.e(TAG, "factoryReset(): IBluetooth Service is null");
+ Log.e(TAG, "factoryReset(): Setting persist.bluetooth.factoryreset to retry later");
SystemProperties.set("persist.bluetooth.factoryreset", "true");
} catch (RemoteException e) {
Log.e(TAG, "", e);
@@ -1662,11 +1663,11 @@
return ActivityThread.currentOpPackageName();
}
- private String getFeatureId() {
+ private String getAttributionTag() {
// Workaround for legacy API for getting a BluetoothAdapter not
// passing a context
if (mContext != null) {
- return mContext.getFeatureId();
+ return mContext.getAttributionTag();
}
return null;
}
@@ -1708,7 +1709,7 @@
try {
mServiceLock.readLock().lock();
if (mService != null) {
- return mService.startDiscovery(getOpPackageName(), getFeatureId());
+ return mService.startDiscovery(getOpPackageName(), getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "", e);
diff --git a/core/java/android/bluetooth/BluetoothManager.java b/core/java/android/bluetooth/BluetoothManager.java
index 7ff6466..3b4fe0a 100644
--- a/core/java/android/bluetooth/BluetoothManager.java
+++ b/core/java/android/bluetooth/BluetoothManager.java
@@ -62,7 +62,7 @@
* @hide
*/
public BluetoothManager(Context context) {
- if (context.getFeatureId() == null) {
+ if (context.getAttributionTag() == null) {
context = context.getApplicationContext();
if (context == null) {
throw new IllegalArgumentException(
diff --git a/core/java/android/companion/WifiDeviceFilter.java b/core/java/android/companion/WifiDeviceFilter.java
index 58bf874..8b48f4c 100644
--- a/core/java/android/companion/WifiDeviceFilter.java
+++ b/core/java/android/companion/WifiDeviceFilter.java
@@ -51,6 +51,7 @@
* expression will be shown
*/
@DataClass.ParcelWith(Parcelling.BuiltIn.ForPattern.class)
+ @DataClass.MaySetToNull
private @Nullable Pattern mNamePattern = null;
/**
@@ -86,7 +87,7 @@
- // Code below generated by codegen v1.0.11.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -273,7 +274,7 @@
* If set, only devices with BSSID matching the given one will be shown
*/
@DataClass.Generated.Member
- public @NonNull Builder setBssid(@Nullable MacAddress value) {
+ public @NonNull Builder setBssid(@NonNull MacAddress value) {
checkNotUsed();
mBuilderFieldsSet |= 0x2;
mBssid = value;
@@ -322,11 +323,15 @@
}
@DataClass.Generated(
- time = 1571960300742L,
- codegenVersion = "1.0.11",
+ time = 1582688421965L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/core/java/android/companion/WifiDeviceFilter.java",
- inputSignatures = "private @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForPattern.class) @android.annotation.Nullable java.util.regex.Pattern mNamePattern\nprivate @android.annotation.Nullable android.net.MacAddress mBssid\nprivate @android.annotation.NonNull android.net.MacAddress mBssidMask\npublic @java.lang.Override boolean matches(android.net.wifi.ScanResult)\npublic @java.lang.Override java.lang.String getDeviceDisplayName(android.net.wifi.ScanResult)\npublic @java.lang.Override int getMediumType()\nclass WifiDeviceFilter extends java.lang.Object implements [android.companion.DeviceFilter<android.net.wifi.ScanResult>]\n@com.android.internal.util.DataClass(genParcelable=true, genAidl=false, genBuilder=true, genEqualsHashCode=true, genHiddenGetters=true)")
+ inputSignatures = "private @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForPattern.class) @com.android.internal.util.DataClass.MaySetToNull @android.annotation.Nullable java.util.regex.Pattern mNamePattern\nprivate @android.annotation.Nullable android.net.MacAddress mBssid\nprivate @android.annotation.NonNull android.net.MacAddress mBssidMask\npublic @java.lang.Override boolean matches(android.net.wifi.ScanResult)\npublic @java.lang.Override java.lang.String getDeviceDisplayName(android.net.wifi.ScanResult)\npublic @java.lang.Override int getMediumType()\nclass WifiDeviceFilter extends java.lang.Object implements [android.companion.DeviceFilter<android.net.wifi.ScanResult>]\n@com.android.internal.util.DataClass(genParcelable=true, genAidl=false, genBuilder=true, genEqualsHashCode=true, genHiddenGetters=true)")
@Deprecated
private void __metadata() {}
+
+ //@formatter:on
+ // End of generated code
+
}
diff --git a/core/java/android/content/ApexContext.java b/core/java/android/content/ApexEnvironment.java
similarity index 80%
rename from core/java/android/content/ApexContext.java
rename to core/java/android/content/ApexEnvironment.java
index fe5cedc..b4cc3c2 100644
--- a/core/java/android/content/ApexContext.java
+++ b/core/java/android/content/ApexEnvironment.java
@@ -30,29 +30,29 @@
* @hide
*/
@SystemApi
-public class ApexContext {
+public class ApexEnvironment {
private static final String APEX_DATA = "apexdata";
/**
- * Returns an ApexContext instance for the APEX with the provided {@code apexModuleName}.
+ * Returns an ApexEnvironment instance for the APEX with the provided {@code apexModuleName}.
*
- * <p>To preserve the safety and integrity of APEX modules, you must only obtain the ApexContext
- * for your specific APEX, and you <em>must never</em> attempt to obtain an ApexContext for
- * another APEX. Any coordination between APEXs must be performed through well-defined
- * interfaces; attempting to directly read or write raw files belonging to another APEX will
- * violate the hermetic storage requirements placed upon each module.
+ * <p>To preserve the safety and integrity of APEX modules, you must only obtain the
+ * ApexEnvironment for your specific APEX, and you <em>must never</em> attempt to obtain an
+ * ApexEnvironment for another APEX. Any coordination between APEXs must be performed through
+ * well-defined interfaces; attempting to directly read or write raw files belonging to another
+ * APEX will violate the hermetic storage requirements placed upon each module.
*/
@NonNull
- public static ApexContext getApexContext(@NonNull String apexModuleName) {
+ public static ApexEnvironment getApexEnvironment(@NonNull String apexModuleName) {
Objects.requireNonNull(apexModuleName, "apexModuleName cannot be null");
//TODO(b/141148175): Check that apexModuleName is an actual APEX name
- return new ApexContext(apexModuleName);
+ return new ApexEnvironment(apexModuleName);
}
private final String mApexModuleName;
- private ApexContext(String apexModuleName) {
+ private ApexEnvironment(String apexModuleName) {
mApexModuleName = apexModuleName;
}
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index bd3298c..d8e8b27 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -230,12 +230,12 @@
}
@Override
- public Cursor query(String callingPkg, @Nullable String featureId, Uri uri,
+ public Cursor query(String callingPkg, @Nullable String attributionTag, Uri uri,
@Nullable String[] projection, @Nullable Bundle queryArgs,
@Nullable ICancellationSignal cancellationSignal) {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- if (enforceReadPermission(callingPkg, featureId, uri, null)
+ if (enforceReadPermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
// The caller has no access to the data, so return an empty cursor with
// the columns in the requested order. The caller may ask for an invalid
@@ -253,7 +253,7 @@
// columns. We then use the column names to return an empty cursor.
Cursor cursor;
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
cursor = mInterface.query(
uri, projection, queryArgs,
@@ -272,7 +272,7 @@
}
Trace.traceBegin(TRACE_TAG_DATABASE, "query");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.query(
uri, projection, queryArgs,
@@ -308,15 +308,15 @@
}
@Override
- public Uri insert(String callingPkg, @Nullable String featureId, Uri uri,
+ public Uri insert(String callingPkg, @Nullable String attributionTag, Uri uri,
ContentValues initialValues, Bundle extras) {
uri = validateIncomingUri(uri);
int userId = getUserIdFromUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- if (enforceWritePermission(callingPkg, featureId, uri, null)
+ if (enforceWritePermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return rejectInsert(uri, initialValues);
} finally {
@@ -325,7 +325,7 @@
}
Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return maybeAddUserId(mInterface.insert(uri, initialValues, extras), userId);
} catch (RemoteException e) {
@@ -337,17 +337,17 @@
}
@Override
- public int bulkInsert(String callingPkg, @Nullable String featureId, Uri uri,
+ public int bulkInsert(String callingPkg, @Nullable String attributionTag, Uri uri,
ContentValues[] initialValues) {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- if (enforceWritePermission(callingPkg, featureId, uri, null)
+ if (enforceWritePermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
return 0;
}
Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.bulkInsert(uri, initialValues);
} catch (RemoteException e) {
@@ -359,8 +359,9 @@
}
@Override
- public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String featureId,
- String authority, ArrayList<ContentProviderOperation> operations)
+ public ContentProviderResult[] applyBatch(String callingPkg,
+ @Nullable String attributionTag, String authority,
+ ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
validateIncomingAuthority(authority);
int numOperations = operations.size();
@@ -377,13 +378,13 @@
operations.set(i, operation);
}
if (operation.isReadOperation()) {
- if (enforceReadPermission(callingPkg, featureId, uri, null)
+ if (enforceReadPermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
throw new OperationApplicationException("App op not allowed", 0);
}
}
if (operation.isWriteOperation()) {
- if (enforceWritePermission(callingPkg, featureId, uri, null)
+ if (enforceWritePermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
throw new OperationApplicationException("App op not allowed", 0);
}
@@ -391,7 +392,7 @@
}
Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
ContentProviderResult[] results = mInterface.applyBatch(authority,
operations);
@@ -413,16 +414,17 @@
}
@Override
- public int delete(String callingPkg, @Nullable String featureId, Uri uri, Bundle extras) {
+ public int delete(String callingPkg, @Nullable String attributionTag, Uri uri,
+ Bundle extras) {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- if (enforceWritePermission(callingPkg, featureId, uri, null)
+ if (enforceWritePermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
return 0;
}
Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.delete(uri, extras);
} catch (RemoteException e) {
@@ -434,17 +436,17 @@
}
@Override
- public int update(String callingPkg, @Nullable String featureId, Uri uri,
+ public int update(String callingPkg, @Nullable String attributionTag, Uri uri,
ContentValues values, Bundle extras) {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- if (enforceWritePermission(callingPkg, featureId, uri, null)
+ if (enforceWritePermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
return 0;
}
Trace.traceBegin(TRACE_TAG_DATABASE, "update");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.update(uri, values, extras);
} catch (RemoteException e) {
@@ -456,15 +458,15 @@
}
@Override
- public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId,
+ public ParcelFileDescriptor openFile(String callingPkg, @Nullable String attributionTag,
Uri uri, String mode, ICancellationSignal cancellationSignal, IBinder callerToken)
throws FileNotFoundException {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- enforceFilePermission(callingPkg, featureId, uri, mode, callerToken);
+ enforceFilePermission(callingPkg, attributionTag, uri, mode, callerToken);
Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.openFile(
uri, mode, CancellationSignal.fromTransport(cancellationSignal));
@@ -477,15 +479,15 @@
}
@Override
- public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
+ public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String attributionTag,
Uri uri, String mode, ICancellationSignal cancellationSignal)
throws FileNotFoundException {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- enforceFilePermission(callingPkg, featureId, uri, mode, null);
+ enforceFilePermission(callingPkg, attributionTag, uri, mode, null);
Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.openAssetFile(
uri, mode, CancellationSignal.fromTransport(cancellationSignal));
@@ -498,13 +500,13 @@
}
@Override
- public Bundle call(String callingPkg, @Nullable String featureId, String authority,
+ public Bundle call(String callingPkg, @Nullable String attributionTag, String authority,
String method, @Nullable String arg, @Nullable Bundle extras) {
validateIncomingAuthority(authority);
Bundle.setDefusable(extras, true);
Trace.traceBegin(TRACE_TAG_DATABASE, "call");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.call(authority, method, arg, extras);
} catch (RemoteException e) {
@@ -532,15 +534,15 @@
@Override
public AssetFileDescriptor openTypedAssetFile(String callingPkg,
- @Nullable String featureId, Uri uri, String mimeType, Bundle opts,
+ @Nullable String attributionTag, Uri uri, String mimeType, Bundle opts,
ICancellationSignal cancellationSignal) throws FileNotFoundException {
Bundle.setDefusable(opts, true);
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
- enforceFilePermission(callingPkg, featureId, uri, "r", null);
+ enforceFilePermission(callingPkg, attributionTag, uri, "r", null);
Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.openTypedAssetFile(
uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
@@ -558,17 +560,17 @@
}
@Override
- public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri) {
+ public Uri canonicalize(String callingPkg, @Nullable String attributionTag, Uri uri) {
uri = validateIncomingUri(uri);
int userId = getUserIdFromUri(uri);
uri = getUriWithoutUserId(uri);
- if (enforceReadPermission(callingPkg, featureId, uri, null)
+ if (enforceReadPermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
return null;
}
Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return maybeAddUserId(mInterface.canonicalize(uri), userId);
} catch (RemoteException e) {
@@ -580,26 +582,26 @@
}
@Override
- public void canonicalizeAsync(String callingPkg, @Nullable String featureId, Uri uri,
+ public void canonicalizeAsync(String callingPkg, @Nullable String attributionTag, Uri uri,
RemoteCallback callback) {
final Bundle result = new Bundle();
result.putParcelable(ContentResolver.REMOTE_CALLBACK_RESULT,
- canonicalize(callingPkg, featureId, uri));
+ canonicalize(callingPkg, attributionTag, uri));
callback.sendResult(result);
}
@Override
- public Uri uncanonicalize(String callingPkg, String featureId, Uri uri) {
+ public Uri uncanonicalize(String callingPkg, String attributionTag, Uri uri) {
uri = validateIncomingUri(uri);
int userId = getUserIdFromUri(uri);
uri = getUriWithoutUserId(uri);
- if (enforceReadPermission(callingPkg, featureId, uri, null)
+ if (enforceReadPermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
return null;
}
Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
} catch (RemoteException e) {
@@ -611,17 +613,17 @@
}
@Override
- public boolean refresh(String callingPkg, String featureId, Uri uri, Bundle extras,
+ public boolean refresh(String callingPkg, String attributionTag, Uri uri, Bundle extras,
ICancellationSignal cancellationSignal) throws RemoteException {
uri = validateIncomingUri(uri);
uri = getUriWithoutUserId(uri);
- if (enforceReadPermission(callingPkg, featureId, uri, null)
+ if (enforceReadPermission(callingPkg, attributionTag, uri, null)
!= AppOpsManager.MODE_ALLOWED) {
return false;
}
Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.refresh(uri, extras,
CancellationSignal.fromTransport(cancellationSignal));
@@ -632,13 +634,13 @@
}
@Override
- public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri,
+ public int checkUriPermission(String callingPkg, @Nullable String attributionTag, Uri uri,
int uid, int modeFlags) {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
final Pair<String, String> original = setCallingPackage(
- new Pair<>(callingPkg, featureId));
+ new Pair<>(callingPkg, attributionTag));
try {
return mInterface.checkUriPermission(uri, uid, modeFlags);
} catch (RemoteException e) {
@@ -649,47 +651,50 @@
}
}
- private void enforceFilePermission(String callingPkg, @Nullable String featureId, Uri uri,
- String mode, IBinder callerToken) throws FileNotFoundException, SecurityException {
+ private void enforceFilePermission(String callingPkg, @Nullable String attributionTag,
+ Uri uri, String mode, IBinder callerToken)
+ throws FileNotFoundException, SecurityException {
if (mode != null && mode.indexOf('w') != -1) {
- if (enforceWritePermission(callingPkg, featureId, uri, callerToken)
+ if (enforceWritePermission(callingPkg, attributionTag, uri, callerToken)
!= AppOpsManager.MODE_ALLOWED) {
throw new FileNotFoundException("App op not allowed");
}
} else {
- if (enforceReadPermission(callingPkg, featureId, uri, callerToken)
+ if (enforceReadPermission(callingPkg, attributionTag, uri, callerToken)
!= AppOpsManager.MODE_ALLOWED) {
throw new FileNotFoundException("App op not allowed");
}
}
}
- private int enforceReadPermission(String callingPkg, @Nullable String featureId, Uri uri,
- IBinder callerToken)
+ private int enforceReadPermission(String callingPkg, @Nullable String attributionTag,
+ Uri uri, IBinder callerToken)
throws SecurityException {
- final int mode = enforceReadPermissionInner(uri, callingPkg, featureId, callerToken);
+ final int mode = enforceReadPermissionInner(uri, callingPkg, attributionTag,
+ callerToken);
if (mode != MODE_ALLOWED) {
return mode;
}
- return noteProxyOp(callingPkg, featureId, mReadOp);
+ return noteProxyOp(callingPkg, attributionTag, mReadOp);
}
- private int enforceWritePermission(String callingPkg, String featureId, Uri uri,
+ private int enforceWritePermission(String callingPkg, String attributionTag, Uri uri,
IBinder callerToken)
throws SecurityException {
- final int mode = enforceWritePermissionInner(uri, callingPkg, featureId, callerToken);
+ final int mode = enforceWritePermissionInner(uri, callingPkg, attributionTag,
+ callerToken);
if (mode != MODE_ALLOWED) {
return mode;
}
- return noteProxyOp(callingPkg, featureId, mWriteOp);
+ return noteProxyOp(callingPkg, attributionTag, mWriteOp);
}
- private int noteProxyOp(String callingPkg, String featureId, int op) {
+ private int noteProxyOp(String callingPkg, String attributionTag, int op) {
if (op != AppOpsManager.OP_NONE) {
int mode = mAppOpsManager.noteProxyOp(op, callingPkg, Binder.getCallingUid(),
- featureId, null);
+ attributionTag, null);
return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
}
@@ -711,19 +716,19 @@
* associated with that permission.
*/
private int checkPermissionAndAppOp(String permission, String callingPkg,
- @Nullable String featureId, IBinder callerToken) {
+ @Nullable String attributionTag, IBinder callerToken) {
if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
callerToken) != PERMISSION_GRANTED) {
return MODE_ERRORED;
}
- return mTransport.noteProxyOp(callingPkg, featureId,
+ return mTransport.noteProxyOp(callingPkg, attributionTag,
AppOpsManager.permissionToOpCode(permission));
}
/** {@hide} */
protected int enforceReadPermissionInner(Uri uri, String callingPkg,
- @Nullable String featureId, IBinder callerToken) throws SecurityException {
+ @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
final Context context = getContext();
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
@@ -737,7 +742,7 @@
if (mExported && checkUser(pid, uid, context)) {
final String componentPerm = getReadPermission();
if (componentPerm != null) {
- final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
+ final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, attributionTag,
callerToken);
if (mode == MODE_ALLOWED) {
return MODE_ALLOWED;
@@ -757,8 +762,8 @@
for (PathPermission pp : pps) {
final String pathPerm = pp.getReadPermission();
if (pathPerm != null && pp.match(path)) {
- final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
- callerToken);
+ final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
+ attributionTag, callerToken);
if (mode == MODE_ALLOWED) {
return MODE_ALLOWED;
} else {
@@ -807,7 +812,7 @@
/** {@hide} */
protected int enforceWritePermissionInner(Uri uri, String callingPkg,
- @Nullable String featureId, IBinder callerToken) throws SecurityException {
+ @Nullable String attributionTag, IBinder callerToken) throws SecurityException {
final Context context = getContext();
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
@@ -821,8 +826,8 @@
if (mExported && checkUser(pid, uid, context)) {
final String componentPerm = getWritePermission();
if (componentPerm != null) {
- final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, featureId,
- callerToken);
+ final int mode = checkPermissionAndAppOp(componentPerm, callingPkg,
+ attributionTag, callerToken);
if (mode == MODE_ALLOWED) {
return MODE_ALLOWED;
} else {
@@ -841,8 +846,8 @@
for (PathPermission pp : pps) {
final String pathPerm = pp.getWritePermission();
if (pathPerm != null && pp.match(path)) {
- final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, featureId,
- callerToken);
+ final int mode = checkPermissionAndAppOp(pathPerm, callingPkg,
+ attributionTag, callerToken);
if (mode == MODE_ALLOWED) {
return MODE_ALLOWED;
} else {
@@ -943,16 +948,16 @@
}
/**
- * Return the feature in the package of the caller that initiated the request being
+ * Return the attribution tag of the caller that initiated the request being
* processed on the current thread. Returns {@code null} if not currently processing
- * a request of the request is for the default feature.
+ * a request of the request is for the default attribution.
* <p>
* This will always return {@code null} when processing
* {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
*
* @see #getCallingPackage
*/
- public final @Nullable String getCallingFeatureId() {
+ public final @Nullable String getCallingAttributionTag() {
final Pair<String, String> pkg = mCallingPackage.get();
if (pkg != null) {
return pkg.second;
@@ -962,6 +967,14 @@
}
/**
+ * @removed
+ */
+ @Deprecated
+ public final @Nullable String getCallingFeatureId() {
+ return getCallingAttributionTag();
+ }
+
+ /**
* Return the package name of the caller that initiated the request being
* processed on the current thread. The returned package will have
* <em>not</em> been verified to belong to the calling UID. Returns
diff --git a/core/java/android/content/ContentProviderClient.java b/core/java/android/content/ContentProviderClient.java
index a9b7862..d0f5ec4 100644
--- a/core/java/android/content/ContentProviderClient.java
+++ b/core/java/android/content/ContentProviderClient.java
@@ -80,7 +80,7 @@
private final IContentProvider mContentProvider;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private final String mPackageName;
- private final @Nullable String mFeatureId;
+ private final @Nullable String mAttributionTag;
private final String mAuthority;
private final boolean mStable;
@@ -104,7 +104,7 @@
mContentResolver = contentResolver;
mContentProvider = contentProvider;
mPackageName = contentResolver.mPackageName;
- mFeatureId = contentResolver.mFeatureId;
+ mAttributionTag = contentResolver.mAttributionTag;
mAuthority = authority;
mStable = stable;
@@ -195,7 +195,8 @@
cancellationSignal.setRemote(remoteCancellationSignal);
}
final Cursor cursor = mContentProvider.query(
- mPackageName, mFeatureId, uri, projection, queryArgs, remoteCancellationSignal);
+ mPackageName, mAttributionTag, uri, projection, queryArgs,
+ remoteCancellationSignal);
if (cursor == null) {
return null;
}
@@ -255,7 +256,7 @@
beforeRemote();
try {
- return mContentProvider.canonicalize(mPackageName, mFeatureId, url);
+ return mContentProvider.canonicalize(mPackageName, mAttributionTag, url);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -273,7 +274,7 @@
beforeRemote();
try {
- return mContentProvider.uncanonicalize(mPackageName, mFeatureId, url);
+ return mContentProvider.uncanonicalize(mPackageName, mAttributionTag, url);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -298,7 +299,7 @@
remoteCancellationSignal = mContentProvider.createCancellationSignal();
cancellationSignal.setRemote(remoteCancellationSignal);
}
- return mContentProvider.refresh(mPackageName, mFeatureId, url, extras,
+ return mContentProvider.refresh(mPackageName, mAttributionTag, url, extras,
remoteCancellationSignal);
} catch (DeadObjectException e) {
if (!mStable) {
@@ -318,7 +319,7 @@
beforeRemote();
try {
- return mContentProvider.checkUriPermission(mPackageName, mFeatureId, uri, uid,
+ return mContentProvider.checkUriPermission(mPackageName, mAttributionTag, uri, uid,
modeFlags);
} catch (DeadObjectException e) {
if (!mStable) {
@@ -344,7 +345,8 @@
beforeRemote();
try {
- return mContentProvider.insert(mPackageName, mFeatureId, url, initialValues, extras);
+ return mContentProvider.insert(mPackageName, mAttributionTag, url, initialValues,
+ extras);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -364,7 +366,7 @@
beforeRemote();
try {
- return mContentProvider.bulkInsert(mPackageName, mFeatureId, url, initialValues);
+ return mContentProvider.bulkInsert(mPackageName, mAttributionTag, url, initialValues);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -388,7 +390,7 @@
beforeRemote();
try {
- return mContentProvider.delete(mPackageName, mFeatureId, url, extras);
+ return mContentProvider.delete(mPackageName, mAttributionTag, url, extras);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -413,7 +415,7 @@
beforeRemote();
try {
- return mContentProvider.update(mPackageName, mFeatureId, url, values, extras);
+ return mContentProvider.update(mPackageName, mAttributionTag, url, values, extras);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -457,8 +459,8 @@
remoteSignal = mContentProvider.createCancellationSignal();
signal.setRemote(remoteSignal);
}
- return mContentProvider.openFile(mPackageName, mFeatureId, url, mode, remoteSignal,
- null);
+ return mContentProvider.openFile(mPackageName, mAttributionTag, url, mode,
+ remoteSignal, null);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -502,7 +504,7 @@
remoteSignal = mContentProvider.createCancellationSignal();
signal.setRemote(remoteSignal);
}
- return mContentProvider.openAssetFile(mPackageName, mFeatureId, url, mode,
+ return mContentProvider.openAssetFile(mPackageName, mAttributionTag, url, mode,
remoteSignal);
} catch (DeadObjectException e) {
if (!mStable) {
@@ -544,7 +546,7 @@
signal.setRemote(remoteSignal);
}
return mContentProvider.openTypedAssetFile(
- mPackageName, mFeatureId, uri, mimeTypeFilter, opts, remoteSignal);
+ mPackageName, mAttributionTag, uri, mimeTypeFilter, opts, remoteSignal);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -571,7 +573,8 @@
beforeRemote();
try {
- return mContentProvider.applyBatch(mPackageName, mFeatureId, authority, operations);
+ return mContentProvider.applyBatch(mPackageName, mAttributionTag, authority,
+ operations);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
@@ -597,7 +600,8 @@
beforeRemote();
try {
- return mContentProvider.call(mPackageName, mFeatureId, authority, method, arg, extras);
+ return mContentProvider.call(mPackageName, mAttributionTag, authority, method, arg,
+ extras);
} catch (DeadObjectException e) {
if (!mStable) {
mContentResolver.unstableProviderDied(mContentProvider);
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index ae786aa..b134c37 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -23,6 +23,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.UserIdInt;
@@ -82,6 +83,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Random;
@@ -765,7 +767,7 @@
public ContentResolver(@Nullable Context context, @Nullable ContentInterface wrapped) {
mContext = context != null ? context : ActivityThread.currentApplication();
mPackageName = mContext.getOpPackageName();
- mFeatureId = mContext.getFeatureId();
+ mAttributionTag = mContext.getAttributionTag();
mTargetSdkVersion = mContext.getApplicationInfo().targetSdkVersion;
mWrapped = wrapped;
}
@@ -1142,7 +1144,7 @@
cancellationSignal.setRemote(remoteCancellationSignal);
}
try {
- qCursor = unstableProvider.query(mPackageName, mFeatureId, uri, projection,
+ qCursor = unstableProvider.query(mPackageName, mAttributionTag, uri, projection,
queryArgs, remoteCancellationSignal);
} catch (DeadObjectException e) {
// The remote process has died... but we only hold an unstable
@@ -1153,7 +1155,7 @@
if (stableProvider == null) {
return null;
}
- qCursor = stableProvider.query(mPackageName, mFeatureId, uri, projection,
+ qCursor = stableProvider.query(mPackageName, mAttributionTag, uri, projection,
queryArgs, remoteCancellationSignal);
}
if (qCursor == null) {
@@ -1245,7 +1247,7 @@
try {
final UriResultListener resultListener = new UriResultListener();
- provider.canonicalizeAsync(mPackageName, mFeatureId, url,
+ provider.canonicalizeAsync(mPackageName, mAttributionTag, url,
new RemoteCallback(resultListener));
resultListener.waitForResult(CONTENT_PROVIDER_TIMEOUT_MILLIS);
return resultListener.result;
@@ -1292,7 +1294,7 @@
}
try {
- return provider.uncanonicalize(mPackageName, mFeatureId, url);
+ return provider.uncanonicalize(mPackageName, mAttributionTag, url);
} catch (RemoteException e) {
// Arbitrary and not worth documenting, as Activity
// Manager will kill this process shortly anyway.
@@ -1344,7 +1346,7 @@
remoteCancellationSignal = provider.createCancellationSignal();
cancellationSignal.setRemote(remoteCancellationSignal);
}
- return provider.refresh(mPackageName, mFeatureId, url, extras,
+ return provider.refresh(mPackageName, mAttributionTag, url, extras,
remoteCancellationSignal);
} catch (RemoteException e) {
// Arbitrary and not worth documenting, as Activity
@@ -1746,7 +1748,8 @@
try {
fd = unstableProvider.openAssetFile(
- mPackageName, mFeatureId, uri, mode, remoteCancellationSignal);
+ mPackageName, mAttributionTag, uri, mode,
+ remoteCancellationSignal);
if (fd == null) {
// The provider will be released by the finally{} clause
return null;
@@ -1761,7 +1764,7 @@
throw new FileNotFoundException("No content provider: " + uri);
}
fd = stableProvider.openAssetFile(
- mPackageName, mFeatureId, uri, mode, remoteCancellationSignal);
+ mPackageName, mAttributionTag, uri, mode, remoteCancellationSignal);
if (fd == null) {
// The provider will be released by the finally{} clause
return null;
@@ -1912,7 +1915,8 @@
try {
fd = unstableProvider.openTypedAssetFile(
- mPackageName, mFeatureId, uri, mimeType, opts, remoteCancellationSignal);
+ mPackageName, mAttributionTag, uri, mimeType, opts,
+ remoteCancellationSignal);
if (fd == null) {
// The provider will be released by the finally{} clause
return null;
@@ -1927,7 +1931,8 @@
throw new FileNotFoundException("No content provider: " + uri);
}
fd = stableProvider.openTypedAssetFile(
- mPackageName, mFeatureId, uri, mimeType, opts, remoteCancellationSignal);
+ mPackageName, mAttributionTag, uri, mimeType, opts,
+ remoteCancellationSignal);
if (fd == null) {
// The provider will be released by the finally{} clause
return null;
@@ -2075,7 +2080,7 @@
}
try {
long startTime = SystemClock.uptimeMillis();
- Uri createdRow = provider.insert(mPackageName, mFeatureId, url, values, extras);
+ Uri createdRow = provider.insert(mPackageName, mAttributionTag, url, values, extras);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "insert", null /* where */);
return createdRow;
@@ -2156,7 +2161,7 @@
}
try {
long startTime = SystemClock.uptimeMillis();
- int rowsCreated = provider.bulkInsert(mPackageName, mFeatureId, url, values);
+ int rowsCreated = provider.bulkInsert(mPackageName, mAttributionTag, url, values);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "bulkinsert", null /* where */);
return rowsCreated;
@@ -2215,7 +2220,7 @@
}
try {
long startTime = SystemClock.uptimeMillis();
- int rowsDeleted = provider.delete(mPackageName, mFeatureId, url, extras);
+ int rowsDeleted = provider.delete(mPackageName, mAttributionTag, url, extras);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "delete", null);
return rowsDeleted;
@@ -2282,7 +2287,7 @@
}
try {
long startTime = SystemClock.uptimeMillis();
- int rowsUpdated = provider.update(mPackageName, mFeatureId, uri, values, extras);
+ int rowsUpdated = provider.update(mPackageName, mAttributionTag, uri, values, extras);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, uri, "update", null);
return rowsUpdated;
@@ -2331,7 +2336,7 @@
throw new IllegalArgumentException("Unknown authority " + authority);
}
try {
- final Bundle res = provider.call(mPackageName, mFeatureId, authority, method, arg,
+ final Bundle res = provider.call(mPackageName, mAttributionTag, authority, method, arg,
extras);
Bundle.setDefusable(res, true);
return res;
@@ -2669,6 +2674,15 @@
ContentProvider.getUserIdFromUri(uri, mContext.getUserId()));
}
+ /** @removed */
+ @Deprecated
+ public void notifyChange(@NonNull Iterable<Uri> uris, @Nullable ContentObserver observer,
+ @NotifyFlags int flags) {
+ final Collection<Uri> asCollection = new ArrayList<>();
+ uris.forEach(asCollection::add);
+ notifyChange(asCollection, observer, flags);
+ }
+
/**
* Notify registered observers that several rows have been updated.
* <p>
@@ -2693,7 +2707,7 @@
* @param flags Flags such as {@link #NOTIFY_SYNC_TO_NETWORK} or
* {@link #NOTIFY_SKIP_NOTIFY_FOR_DESCENDANTS}.
*/
- public void notifyChange(@NonNull Iterable<Uri> uris, @Nullable ContentObserver observer,
+ public void notifyChange(@NonNull Collection<Uri> uris, @Nullable ContentObserver observer,
@NotifyFlags int flags) {
Objects.requireNonNull(uris, "uris");
@@ -3735,8 +3749,8 @@
}
/** @hide */
- public @Nullable String getFeatureId() {
- return mFeatureId;
+ public @Nullable String getAttributionTag() {
+ return mAttributionTag;
}
@UnsupportedAppUsage
@@ -3746,7 +3760,7 @@
@UnsupportedAppUsage
final String mPackageName;
- final @Nullable String mFeatureId;
+ final @Nullable String mAttributionTag;
final int mTargetSdkVersion;
final ContentInterface mWrapped;
@@ -4014,6 +4028,10 @@
* @hide
*/
@SystemApi
+ @TestApi
+ // We can't accept an already-opened FD here, since these methods are
+ // rewriting actual filesystem paths
+ @SuppressLint("StreamFiles")
public static @NonNull Uri decodeFromFile(@NonNull File file) {
return translateDeprecatedDataPath(file.getAbsolutePath());
}
@@ -4030,6 +4048,10 @@
* @hide
*/
@SystemApi
+ @TestApi
+ // We can't accept an already-opened FD here, since these methods are
+ // rewriting actual filesystem paths
+ @SuppressLint("StreamFiles")
public static @NonNull File encodeToFile(@NonNull Uri uri) {
return new File(translateDeprecatedDataPath(uri));
}
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index aba86e9..318ae11 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -71,6 +71,7 @@
import android.view.View;
import android.view.ViewDebug;
import android.view.WindowManager;
+import android.view.WindowManager.LayoutParams.WindowType;
import android.view.autofill.AutofillManager.AutofillClient;
import android.view.contentcapture.ContentCaptureManager.ContentCaptureClient;
import android.view.textclassifier.TextClassificationManager;
@@ -814,16 +815,25 @@
}
/**
- * <p>Features are used in complex apps to logically separate parts of the app. E.g. a
- * blogging app might also have a instant messaging app built in.
+ * <p>Attribution can be used in complex apps to logically separate parts of the app. E.g. a
+ * blogging app might also have a instant messaging app built in. In this case two separate tags
+ * can for used each sub-feature.
*
- * @return the feature id this context is for or {@code null} if this is the default
- * feature.
+ * @return the attribution tag this context is for or {@code null} if this is the default.
*/
- public @Nullable String getFeatureId() {
+ public @Nullable String getAttributionTag() {
return null;
}
+ // TODO moltmann: Remove
+ /**
+ * @removed
+ */
+ @Deprecated
+ public @Nullable String getFeatureId() {
+ return getAttributionTag();
+ }
+
/** Return the full application info for this context's package. */
public abstract ApplicationInfo getApplicationInfo();
@@ -5128,7 +5138,7 @@
* {@link android.os.incremental.IncrementalManager}.
* @hide
*/
- public static final String INCREMENTAL_SERVICE = "incremental_service";
+ public static final String INCREMENTAL_SERVICE = "incremental";
/**
* Use with {@link #getSystemService(String)} to retrieve an
@@ -5820,24 +5830,34 @@
* @see #WALLPAPER_SERVICE
* @throws IllegalArgumentException if token is invalid
*/
- public @NonNull Context createWindowContext(int type, @Nullable Bundle options) {
+ public @NonNull Context createWindowContext(@WindowType int type, @Nullable Bundle options) {
throw new RuntimeException("Not implemented. Must override in a subclass.");
}
/**
- * Return a new Context object for the current Context but for a different feature in the app.
- * Features can be used by complex apps to separate logical parts.
+ * Return a new Context object for the current Context but attribute to a different tag.
+ * In complex apps attribution tagging can be used to distinguish between separate logical
+ * parts.
*
- * @param featureId The feature id or {@code null} to create a context for the default feature.
+ * @param attributionTag The tag or {@code null} to create a context for the default.
*
- * @return A {@link Context} for the feature
+ * @return A {@link Context} that is tagged for the new attribution
*
- * @see #getFeatureId()
+ * @see #getAttributionTag()
*/
- public @NonNull Context createFeatureContext(@Nullable String featureId) {
+ public @NonNull Context createAttributionContext(@Nullable String attributionTag) {
throw new RuntimeException("Not implemented. Must override in a subclass.");
}
+ // TODO moltmann: remove
+ /**
+ * @removed
+ */
+ @Deprecated
+ public @NonNull Context createFeatureContext(@Nullable String featureId) {
+ return createAttributionContext(featureId);
+ }
+
/**
* Return a new Context object for the current Context but whose storage
* APIs are backed by device-protected storage.
diff --git a/core/java/android/content/ContextWrapper.java b/core/java/android/content/ContextWrapper.java
index 91d214b..d389d2a 100644
--- a/core/java/android/content/ContextWrapper.java
+++ b/core/java/android/content/ContextWrapper.java
@@ -42,6 +42,7 @@
import android.os.UserHandle;
import android.view.Display;
import android.view.DisplayAdjustments;
+import android.view.WindowManager.LayoutParams.WindowType;
import android.view.autofill.AutofillManager.AutofillClient;
import java.io.File;
@@ -163,8 +164,8 @@
/** @hide */
@Override
- public @Nullable String getFeatureId() {
- return mBase.getFeatureId();
+ public @Nullable String getAttributionTag() {
+ return mBase.getAttributionTag();
}
@Override
@@ -978,13 +979,13 @@
@Override
@NonNull
- public Context createWindowContext(int type, @Nullable Bundle options) {
+ public Context createWindowContext(@WindowType int type, @Nullable Bundle options) {
return mBase.createWindowContext(type, options);
}
@Override
- public @NonNull Context createFeatureContext(@Nullable String featureId) {
- return mBase.createFeatureContext(featureId);
+ public @NonNull Context createAttributionContext(@Nullable String attributionTag) {
+ return mBase.createAttributionContext(attributionTag);
}
@Override
diff --git a/core/java/android/content/IContentProvider.java b/core/java/android/content/IContentProvider.java
index 37643da..84b0f0e 100644
--- a/core/java/android/content/IContentProvider.java
+++ b/core/java/android/content/IContentProvider.java
@@ -38,7 +38,7 @@
* @hide
*/
public interface IContentProvider extends IInterface {
- public Cursor query(String callingPkg, @Nullable String featureId, Uri url,
+ public Cursor query(String callingPkg, @Nullable String attributionTag, Uri url,
@Nullable String[] projection,
@Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal)
throws RemoteException;
@@ -59,8 +59,8 @@
throws RemoteException {
return insert(callingPkg, null, url, initialValues, null);
}
- public Uri insert(String callingPkg, String featureId, Uri url, ContentValues initialValues,
- Bundle extras) throws RemoteException;
+ public Uri insert(String callingPkg, String attributionTag, Uri url,
+ ContentValues initialValues, Bundle extras) throws RemoteException;
@Deprecated
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, publicAlternatives = "Use {@link "
+ "ContentProviderClient#bulkInsert(android.net.Uri, android.content.ContentValues[])"
@@ -69,7 +69,7 @@
throws RemoteException {
return bulkInsert(callingPkg, null, url, initialValues);
}
- public int bulkInsert(String callingPkg, String featureId, Uri url,
+ public int bulkInsert(String callingPkg, String attributionTag, Uri url,
ContentValues[] initialValues) throws RemoteException;
@Deprecated
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, publicAlternatives = "Use {@link "
@@ -80,7 +80,7 @@
return delete(callingPkg, null, url,
ContentResolver.createSqlQueryBundle(selection, selectionArgs));
}
- public int delete(String callingPkg, String featureId, Uri url, Bundle extras)
+ public int delete(String callingPkg, String attributionTag, Uri url, Bundle extras)
throws RemoteException;
@Deprecated
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, publicAlternatives = "Use {@link "
@@ -91,18 +91,18 @@
return update(callingPkg, null, url, values,
ContentResolver.createSqlQueryBundle(selection, selectionArgs));
}
- public int update(String callingPkg, String featureId, Uri url, ContentValues values,
+ public int update(String callingPkg, String attributionTag, Uri url, ContentValues values,
Bundle extras) throws RemoteException;
- public ParcelFileDescriptor openFile(String callingPkg, @Nullable String featureId, Uri url,
- String mode, ICancellationSignal signal, IBinder callerToken)
+ public ParcelFileDescriptor openFile(String callingPkg, @Nullable String attributionTag,
+ Uri url, String mode, ICancellationSignal signal, IBinder callerToken)
throws RemoteException, FileNotFoundException;
- public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String featureId,
+ public AssetFileDescriptor openAssetFile(String callingPkg, @Nullable String attributionTag,
Uri url, String mode, ICancellationSignal signal)
throws RemoteException, FileNotFoundException;
- public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String featureId,
+ public ContentProviderResult[] applyBatch(String callingPkg, @Nullable String attributionTag,
String authority, ArrayList<ContentProviderOperation> operations)
throws RemoteException, OperationApplicationException;
@@ -115,15 +115,15 @@
return call(callingPkg, null, "unknown", method, arg, extras);
}
- public Bundle call(String callingPkg, @Nullable String featureId, String authority,
+ public Bundle call(String callingPkg, @Nullable String attributionTag, String authority,
String method, @Nullable String arg, @Nullable Bundle extras) throws RemoteException;
- public int checkUriPermission(String callingPkg, @Nullable String featureId, Uri uri, int uid,
- int modeFlags) throws RemoteException;
+ public int checkUriPermission(String callingPkg, @Nullable String attributionTag, Uri uri,
+ int uid, int modeFlags) throws RemoteException;
public ICancellationSignal createCancellationSignal() throws RemoteException;
- public Uri canonicalize(String callingPkg, @Nullable String featureId, Uri uri)
+ public Uri canonicalize(String callingPkg, @Nullable String attributionTag, Uri uri)
throws RemoteException;
/**
@@ -131,20 +131,21 @@
* call returns immediately, and the resulting type is returned when available via
* a binder callback.
*/
- void canonicalizeAsync(String callingPkg, @Nullable String featureId, Uri uri,
+ void canonicalizeAsync(String callingPkg, @Nullable String attributionTag, Uri uri,
RemoteCallback callback) throws RemoteException;
- public Uri uncanonicalize(String callingPkg, @Nullable String featureId, Uri uri)
+ public Uri uncanonicalize(String callingPkg, @Nullable String attributionTag, Uri uri)
throws RemoteException;
- public boolean refresh(String callingPkg, @Nullable String featureId, Uri url,
+ public boolean refresh(String callingPkg, @Nullable String attributionTag, Uri url,
@Nullable Bundle extras, ICancellationSignal cancellationSignal) throws RemoteException;
// Data interchange.
public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException;
- public AssetFileDescriptor openTypedAssetFile(String callingPkg, @Nullable String featureId,
- Uri url, String mimeType, Bundle opts, ICancellationSignal signal)
+ public AssetFileDescriptor openTypedAssetFile(String callingPkg,
+ @Nullable String attributionTag, Uri url, String mimeType, Bundle opts,
+ ICancellationSignal signal)
throws RemoteException, FileNotFoundException;
/* IPC constants */
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index c6f6972..38c1890 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -26,6 +26,7 @@
import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.app.AppGlobals;
@@ -86,6 +87,7 @@
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
+import java.util.TimeZone;
/**
* An intent is an abstract description of an operation to be performed. It
@@ -1881,6 +1883,20 @@
"android.intent.action.MANAGE_PERMISSIONS";
/**
+ * Activity action: Launch UI to manage auto-revoke state.
+ * <p>
+ * Input: {@link #EXTRA_PACKAGE_NAME} specifies the package whose
+ * auto-revoke state will be reviewed (mandatory).
+ * </p>
+ * <p>
+ * Output: Nothing.
+ * </p>
+ */
+ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+ public static final String ACTION_AUTO_REVOKE_PERMISSIONS =
+ "android.intent.action.AUTO_REVOKE_PERMISSIONS";
+
+ /**
* Activity action: Launch UI to review permissions for an app.
* The system uses this intent if permission review for apps not
* supporting the new runtime permissions model is enabled. In
@@ -2298,7 +2314,8 @@
/**
* Broadcast Action: The timezone has changed. The intent will have the following extra values:</p>
* <ul>
- * <li><em>time-zone</em> - The java.util.TimeZone.getID() value identifying the new time zone.</li>
+ * <li>{@link #EXTRA_TIMEZONE} - The java.util.TimeZone.getID() value identifying the new
+ * time zone.</li>
* </ul>
*
* <p class="note">This is a protected intent that can only be sent
@@ -5771,6 +5788,14 @@
public static final String EXTRA_TIME = "android.intent.extra.TIME";
/**
+ * Extra sent with {@link #ACTION_TIMEZONE_CHANGED} specifying the new time zone of the device.
+ *
+ * <p>Type: String, the same as returned by {@link TimeZone#getID()} to identify time zones.
+ */
+ @SuppressLint("ActionValue")
+ public static final String EXTRA_TIMEZONE = "time-zone";
+
+ /**
* Optional int extra for {@link #ACTION_TIME_CHANGED} that indicates the
* user has set their time format preference. See {@link #EXTRA_TIME_PREF_VALUE_USE_12_HOUR},
* {@link #EXTRA_TIME_PREF_VALUE_USE_24_HOUR} and
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index 61128f2..f19ab01 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -274,6 +274,9 @@
*/
public static final String SCHEME_HTTPS = "https";
+ /** The value to indicate a wildcard for incoming match arguments. */
+ private static final String WILDCARD = "*";
+
private int mPriority;
@UnsupportedAppUsage
private int mOrder;
@@ -758,6 +761,17 @@
* @return True if the action is listed in the filter.
*/
public final boolean matchAction(String action) {
+ return matchAction(action, false);
+ }
+
+ /**
+ * Variant of {@link #matchAction(String)} that allows a wildcard for the provided action.
+ * @param wildcardSupported if true, will allow action to use wildcards
+ */
+ private boolean matchAction(String action, boolean wildcardSupported) {
+ if (wildcardSupported && !mActions.isEmpty() && WILDCARD.equals(action)) {
+ return true;
+ }
return hasAction(action);
}
@@ -1120,20 +1134,33 @@
* {@link IntentFilter#MATCH_CATEGORY_HOST}.
*/
public int match(Uri data) {
+ return match(data, false);
+ }
+
+ /**
+ * Variant of {@link #match(Uri)} that supports wildcards on the scheme, host and
+ * path of the provided {@link Uri}
+ *
+ * @param wildcardSupported if true, will allow parameters to use wildcards
+ * @hide
+ */
+ public int match(Uri data, boolean wildcardSupported) {
String host = data.getHost();
if (host == null) {
return NO_MATCH_DATA;
}
if (false) Log.v("IntentFilter",
"Match host " + host + ": " + mHost);
- if (mWild) {
- if (host.length() < mHost.length()) {
+ if (!wildcardSupported || !WILDCARD.equals(host)) {
+ if (mWild) {
+ if (host.length() < mHost.length()) {
+ return NO_MATCH_DATA;
+ }
+ host = host.substring(host.length() - mHost.length());
+ }
+ if (host.compareToIgnoreCase(mHost) != 0) {
return NO_MATCH_DATA;
}
- host = host.substring(host.length()-mHost.length());
- }
- if (host.compareToIgnoreCase(mHost) != 0) {
- return NO_MATCH_DATA;
}
if (mPort >= 0) {
if (mPort != data.getPort()) {
@@ -1207,9 +1234,21 @@
* filter.
*/
public final boolean hasDataSchemeSpecificPart(String data) {
+ return hasDataSchemeSpecificPart(data, false);
+ }
+
+ /**
+ * Variant of {@link #hasDataSchemeSpecificPart(String)} that supports wildcards on the provided
+ * ssp.
+ * @param supportWildcards if true, will allow parameters to use wildcards
+ */
+ private boolean hasDataSchemeSpecificPart(String data, boolean supportWildcards) {
if (mDataSchemeSpecificParts == null) {
return false;
}
+ if (supportWildcards && WILDCARD.equals(data) && mDataSchemeSpecificParts.size() > 0) {
+ return true;
+ }
final int numDataSchemeSpecificParts = mDataSchemeSpecificParts.size();
for (int i = 0; i < numDataSchemeSpecificParts; i++) {
final PatternMatcher pe = mDataSchemeSpecificParts.get(i);
@@ -1388,9 +1427,21 @@
* filter.
*/
public final boolean hasDataPath(String data) {
+ return hasDataPath(data, false);
+ }
+
+ /**
+ * Variant of {@link #hasDataPath(String)} that supports wildcards on the provided scheme, host,
+ * and path.
+ * @param wildcardSupported if true, will allow parameters to use wildcards
+ */
+ private boolean hasDataPath(String data, boolean wildcardSupported) {
if (mDataPaths == null) {
return false;
}
+ if (wildcardSupported && WILDCARD.equals(data)) {
+ return true;
+ }
final int numDataPaths = mDataPaths.size();
for (int i = 0; i < numDataPaths; i++) {
final PatternMatcher pe = mDataPaths.get(i);
@@ -1435,13 +1486,24 @@
* {@link #MATCH_CATEGORY_PORT}, {@link #NO_MATCH_DATA}.
*/
public final int matchDataAuthority(Uri data) {
- if (mDataAuthorities == null || data == null) {
+ return matchDataAuthority(data, false);
+ }
+
+ /**
+ * Variant of {@link #matchDataAuthority(Uri)} that allows wildcard matching of the provided
+ * authority.
+ *
+ * @param wildcardSupported if true, will allow parameters to use wildcards
+ * @hide
+ */
+ public final int matchDataAuthority(Uri data, boolean wildcardSupported) {
+ if (data == null || mDataAuthorities == null) {
return NO_MATCH_DATA;
}
final int numDataAuthorities = mDataAuthorities.size();
for (int i = 0; i < numDataAuthorities; i++) {
final AuthorityEntry ae = mDataAuthorities.get(i);
- int match = ae.match(data);
+ int match = ae.match(data, wildcardSupported);
if (match >= 0) {
return match;
}
@@ -1488,6 +1550,15 @@
* @see #match
*/
public final int matchData(String type, String scheme, Uri data) {
+ return matchData(type, scheme, data, false);
+ }
+
+ /**
+ * Variant of {@link #matchData(String, String, Uri)} that allows wildcard matching
+ * of the provided type, scheme, host and path parameters.
+ * @param wildcardSupported if true, will allow parameters to use wildcards
+ */
+ private int matchData(String type, String scheme, Uri data, boolean wildcardSupported) {
final ArrayList<String> types = mDataTypes;
final ArrayList<String> schemes = mDataSchemes;
@@ -1499,7 +1570,8 @@
}
if (schemes != null) {
- if (schemes.contains(scheme != null ? scheme : "")) {
+ if (schemes.contains(scheme != null ? scheme : "")
+ || wildcardSupported && WILDCARD.equals(scheme)) {
match = MATCH_CATEGORY_SCHEME;
} else {
return NO_MATCH_DATA;
@@ -1507,19 +1579,19 @@
final ArrayList<PatternMatcher> schemeSpecificParts = mDataSchemeSpecificParts;
if (schemeSpecificParts != null && data != null) {
- match = hasDataSchemeSpecificPart(data.getSchemeSpecificPart())
+ match = hasDataSchemeSpecificPart(data.getSchemeSpecificPart(), wildcardSupported)
? MATCH_CATEGORY_SCHEME_SPECIFIC_PART : NO_MATCH_DATA;
}
if (match != MATCH_CATEGORY_SCHEME_SPECIFIC_PART) {
// If there isn't any matching ssp, we need to match an authority.
final ArrayList<AuthorityEntry> authorities = mDataAuthorities;
if (authorities != null) {
- int authMatch = matchDataAuthority(data);
+ int authMatch = matchDataAuthority(data, wildcardSupported);
if (authMatch >= 0) {
final ArrayList<PatternMatcher> paths = mDataPaths;
if (paths == null) {
match = authMatch;
- } else if (hasDataPath(data.getPath())) {
+ } else if (hasDataPath(data.getPath(), wildcardSupported)) {
match = MATCH_CATEGORY_PATH;
} else {
return NO_MATCH_DATA;
@@ -1541,7 +1613,8 @@
// to force everyone to say they handle content: or file: URIs.
if (scheme != null && !"".equals(scheme)
&& !"content".equals(scheme)
- && !"file".equals(scheme)) {
+ && !"file".equals(scheme)
+ && !(wildcardSupported && WILDCARD.equals(scheme))) {
return NO_MATCH_DATA;
}
}
@@ -1701,13 +1774,23 @@
*/
public final int match(String action, String type, String scheme,
Uri data, Set<String> categories, String logTag) {
- if (action != null && !matchAction(action)) {
+ return match(action, type, scheme, data, categories, logTag, false /*supportWildcards*/);
+ }
+
+ /**
+ * Variant of {@link #match(ContentResolver, Intent, boolean, String)} that supports wildcards
+ * in the action, type, scheme, host and path.
+ * @hide if true, will allow supported parameters to use wildcards to match this filter
+ */
+ public final int match(String action, String type, String scheme,
+ Uri data, Set<String> categories, String logTag, boolean supportWildcards) {
+ if (action != null && !matchAction(action, supportWildcards)) {
if (false) Log.v(
logTag, "No matching action " + action + " for " + this);
return NO_MATCH_ACTION;
}
- int dataMatch = matchData(type, scheme, data);
+ int dataMatch = matchData(type, scheme, data, supportWildcards);
if (dataMatch < 0) {
if (false) {
if (dataMatch == NO_MATCH_TYPE) {
diff --git a/core/java/android/content/PermissionChecker.java b/core/java/android/content/PermissionChecker.java
index 33bd839..b434072 100644
--- a/core/java/android/content/PermissionChecker.java
+++ b/core/java/android/content/PermissionChecker.java
@@ -123,7 +123,7 @@
* @param uid The uid for which to check.
* @param packageName The package name for which to check. If null the
* the first package for the calling UID will be used.
- * @param featureId Feature in the package
+ * @param attributionTag attribution tag
* @return The permission check result which is either {@link #PERMISSION_GRANTED}
* or {@link #PERMISSION_SOFT_DENIED} or {@link #PERMISSION_HARD_DENIED}.
* @param message A message describing the reason the permission was checked
@@ -133,9 +133,9 @@
@PermissionResult
public static int checkPermissionForDataDelivery(@NonNull Context context,
@NonNull String permission, int pid, int uid, @Nullable String packageName,
- @Nullable String featureId, @Nullable String message) {
- return checkPermissionCommon(context, permission, pid, uid, packageName, featureId, message,
- true /*forDataDelivery*/);
+ @Nullable String attributionTag, @Nullable String message) {
+ return checkPermissionCommon(context, permission, pid, uid, packageName, attributionTag,
+ message, true /*forDataDelivery*/);
}
/**
@@ -171,8 +171,8 @@
@PermissionResult
public static int checkPermissionForPreflight(@NonNull Context context,
@NonNull String permission, int pid, int uid, @Nullable String packageName) {
- return checkPermissionCommon(context, permission, pid, uid, packageName, null /*featureId*/,
- null /*message*/, false /*forDataDelivery*/);
+ return checkPermissionCommon(context, permission, pid, uid, packageName,
+ null /*attributionTag*/, null /*message*/, false /*forDataDelivery*/);
}
/**
@@ -207,7 +207,7 @@
public static int checkSelfPermissionForDataDelivery(@NonNull Context context,
@NonNull String permission, @Nullable String message) {
return checkPermissionForDataDelivery(context, permission, Process.myPid(),
- Process.myUid(), context.getPackageName(), context.getFeatureId(), message);
+ Process.myUid(), context.getPackageName(), context.getAttributionTag(), message);
}
/**
@@ -266,7 +266,7 @@
* @param permission The permission to check.
* @param packageName The package name making the IPC. If null the
* the first package for the calling UID will be used.
- * @param featureId The feature inside of the app
+ * @param attributionTag attribution tag
* @return The permission check result which is either {@link #PERMISSION_GRANTED}
* or {@link #PERMISSION_SOFT_DENIED} or {@link #PERMISSION_HARD_DENIED}.
* @param message A message describing the reason the permission was checked
@@ -276,12 +276,12 @@
@PermissionResult
public static int checkCallingPermissionForDataDelivery(@NonNull Context context,
@NonNull String permission, @Nullable String packageName,
- @Nullable String featureId, @Nullable String message) {
+ @Nullable String attributionTag, @Nullable String message) {
if (Binder.getCallingPid() == Process.myPid()) {
return PERMISSION_HARD_DENIED;
}
return checkPermissionForDataDelivery(context, permission, Binder.getCallingPid(),
- Binder.getCallingUid(), packageName, featureId, message);
+ Binder.getCallingUid(), packageName, attributionTag, message);
}
/**
@@ -343,20 +343,20 @@
* @param permission The permission to check.
* @return The permission check result which is either {@link #PERMISSION_GRANTED}
* or {@link #PERMISSION_SOFT_DENIED} or {@link #PERMISSION_HARD_DENIED}.
- * @param featureId feature Id of caller (if not self)
+ * @param attributionTag attribution tag of caller (if not self)
* @param message A message describing the reason the permission was checked
*
* @see #checkCallingOrSelfPermissionForPreflight(Context, String)
*/
@PermissionResult
public static int checkCallingOrSelfPermissionForDataDelivery(@NonNull Context context,
- @NonNull String permission, @Nullable String featureId, @Nullable String message) {
+ @NonNull String permission, @Nullable String attributionTag, @Nullable String message) {
String packageName = (Binder.getCallingPid() == Process.myPid())
? context.getPackageName() : null;
- featureId = (Binder.getCallingPid() == Process.myPid())
- ? context.getFeatureId() : featureId;
+ attributionTag = (Binder.getCallingPid() == Process.myPid())
+ ? context.getAttributionTag() : attributionTag;
return checkPermissionForDataDelivery(context, permission, Binder.getCallingPid(),
- Binder.getCallingUid(), packageName, featureId, message);
+ Binder.getCallingUid(), packageName, attributionTag, message);
}
/**
@@ -395,7 +395,7 @@
}
static int checkPermissionCommon(@NonNull Context context, @NonNull String permission,
- int pid, int uid, @Nullable String packageName, @Nullable String featureId,
+ int pid, int uid, @Nullable String packageName, @Nullable String attributionTag,
@Nullable String message, boolean forDataDelivery) {
final PermissionInfo permissionInfo;
try {
@@ -414,18 +414,18 @@
}
if (permissionInfo.isAppOp()) {
- return checkAppOpPermission(context, permission, pid, uid, packageName, featureId,
+ return checkAppOpPermission(context, permission, pid, uid, packageName, attributionTag,
message, forDataDelivery);
}
if (permissionInfo.isRuntime()) {
- return checkRuntimePermission(context, permission, pid, uid, packageName, featureId,
- message, forDataDelivery);
+ return checkRuntimePermission(context, permission, pid, uid, packageName,
+ attributionTag, message, forDataDelivery);
}
return context.checkPermission(permission, pid, uid);
}
private static int checkAppOpPermission(@NonNull Context context, @NonNull String permission,
- int pid, int uid, @Nullable String packageName, @Nullable String featureId,
+ int pid, int uid, @Nullable String packageName, @Nullable String attributionTag,
@Nullable String message, boolean forDataDelivery) {
final String op = AppOpsManager.permissionToOp(permission);
if (op == null || packageName == null) {
@@ -434,11 +434,12 @@
final AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class);
final int opMode = (forDataDelivery)
- ? appOpsManager.noteProxyOpNoThrow(op, packageName, uid, featureId, message)
- : appOpsManager.unsafeCheckOpNoThrow(op, uid, packageName);
+ ? appOpsManager.noteProxyOpNoThrow(op, packageName, uid, attributionTag, message)
+ : appOpsManager.unsafeCheckOpRawNoThrow(op, uid, packageName);
switch (opMode) {
- case AppOpsManager.MODE_ALLOWED: {
+ case AppOpsManager.MODE_ALLOWED:
+ case AppOpsManager.MODE_FOREGROUND: {
return PERMISSION_GRANTED;
}
case AppOpsManager.MODE_DEFAULT: {
@@ -453,7 +454,7 @@
}
private static int checkRuntimePermission(@NonNull Context context, @NonNull String permission,
- int pid, int uid, @Nullable String packageName, @Nullable String featureId,
+ int pid, int uid, @Nullable String packageName, @Nullable String attributionTag,
@Nullable String message, boolean forDataDelivery) {
if (context.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_DENIED) {
return PERMISSION_HARD_DENIED;
@@ -466,13 +467,15 @@
final AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class);
final int opMode = (forDataDelivery)
- ? appOpsManager.noteProxyOpNoThrow(op, packageName, uid, featureId, message)
- : appOpsManager.unsafeCheckOpNoThrow(op, uid, packageName);
+ ? appOpsManager.noteProxyOpNoThrow(op, packageName, uid, attributionTag, message)
+ : appOpsManager.unsafeCheckOpRawNoThrow(op, uid, packageName);
- if (opMode == AppOpsManager.MODE_ALLOWED) {
- return PERMISSION_GRANTED;
- } else {
- return PERMISSION_SOFT_DENIED;
+ switch (opMode) {
+ case AppOpsManager.MODE_ALLOWED:
+ case AppOpsManager.MODE_FOREGROUND:
+ return PERMISSION_GRANTED;
+ default:
+ return PERMISSION_SOFT_DENIED;
}
}
}
diff --git a/core/java/android/content/integrity/AppIntegrityManager.java b/core/java/android/content/integrity/AppIntegrityManager.java
index 9f95d4d..2869abb 100644
--- a/core/java/android/content/integrity/AppIntegrityManager.java
+++ b/core/java/android/content/integrity/AppIntegrityManager.java
@@ -25,6 +25,8 @@
import android.content.pm.ParceledListSlice;
import android.os.RemoteException;
+import java.util.List;
+
/**
* Class for pushing rules used to check the integrity of app installs.
*
@@ -121,4 +123,21 @@
throw e.rethrowAsRuntimeException();
}
}
+
+ /**
+ * Get the package names of all whitelisted rule providers.
+ *
+ * <p>Warning: this method is only used for tests.
+ *
+ * @hide
+ */
+ @TestApi
+ @NonNull
+ public List<String> getWhitelistedRuleProviders() {
+ try {
+ return mManager.getWhitelistedRuleProviders();
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
}
diff --git a/core/java/android/content/integrity/IAppIntegrityManager.aidl b/core/java/android/content/integrity/IAppIntegrityManager.aidl
index 4714ad7..94197bb 100644
--- a/core/java/android/content/integrity/IAppIntegrityManager.aidl
+++ b/core/java/android/content/integrity/IAppIntegrityManager.aidl
@@ -19,6 +19,7 @@
import android.content.integrity.Rule;
import android.content.IntentSender;
import android.content.pm.ParceledListSlice;
+import java.util.List;
/** @hide */
interface IAppIntegrityManager {
@@ -26,4 +27,5 @@
String getCurrentRuleSetVersion();
String getCurrentRuleSetProvider();
ParceledListSlice<Rule> getCurrentRules();
+ List<String> getWhitelistedRuleProviders();
}
diff --git a/core/java/android/content/om/OverlayManager.java b/core/java/android/content/om/OverlayManager.java
index dbe3954..2bdca7d 100644
--- a/core/java/android/content/om/OverlayManager.java
+++ b/core/java/android/content/om/OverlayManager.java
@@ -27,14 +27,50 @@
import android.compat.annotation.EnabledAfter;
import android.content.Context;
import android.os.Build;
+import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
+import com.android.server.SystemConfig;
+
import java.util.List;
/**
* Updates OverlayManager state; gets information about installed overlay packages.
+ *
+ * <p>Users of this API must be actors of any overlays they desire to change the state of.</p>
+ *
+ * <p>An actor is a package responsible for managing the state of overlays targeting overlayables
+ * that specify the actor. For example, an actor may enable or disable an overlay or otherwise
+ * change its state.</p>
+ *
+ * <p>Actors are specified as part of the overlayable definition.
+ *
+ * <pre>{@code
+ * <overlayable name="OverlayableResourcesName" actor="overlay://namespace/actorName">
+ * }</pre></p>
+ *
+ * <p>Actors are defined through {@link SystemConfig}. Only system packages can be used.
+ * The namespace "android" is reserved for use by AOSP and any "android" definitions must
+ * have an implementation on device that fulfill their intended functionality.</p>
+ *
+ * <pre>{@code
+ * <named-actor
+ * namespace="namespace"
+ * name="actorName"
+ * package="com.example.pkg"
+ * />
+ * }</pre></p>
+ *
+ * <p>An actor can manipulate a particular overlay if any of the following is true:
+ * <ul>
+ * <li>its UID is {@link Process#ROOT_UID}, {@link Process#SYSTEM_UID}</li>
+ * <li>it is the target of the overlay package</li>
+ * <li>it has the CHANGE_OVERLAY_PACKAGES permission and the target does not specify an actor</li>
+ * <li>it is the actor specified by the overlayable</li>
+ * </ul></p>
+ *
* @hide
*/
@SystemApi
@@ -84,6 +120,8 @@
* If a set of overlay packages share the same category, single call to this method is
* equivalent to multiple calls to {@link #setEnabled(String, boolean, UserHandle)}.
*
+ * The caller must pass the actor requirements specified in the class comment.
+ *
* @param packageName the name of the overlay package to enable.
* @param user The user for which to change the overlay.
*
@@ -116,6 +154,8 @@
* While {@link #setEnabledExclusiveInCategory(String, UserHandle)} doesn't support disabling
* every overlay in a category, this method allows you to disable everything.
*
+ * The caller must pass the actor requirements specified in the class comment.
+ *
* @param packageName the name of the overlay package to enable.
* @param enable {@code false} if the overlay should be turned off.
* @param user The user for which to change the overlay.
diff --git a/core/java/android/content/pm/ActivityInfo.java b/core/java/android/content/pm/ActivityInfo.java
index 0b2b5b1..f25ce76 100644
--- a/core/java/android/content/pm/ActivityInfo.java
+++ b/core/java/android/content/pm/ActivityInfo.java
@@ -1222,13 +1222,7 @@
dest.writeInt(lockTaskLaunchMode);
if (windowLayout != null) {
dest.writeInt(1);
- dest.writeInt(windowLayout.width);
- dest.writeFloat(windowLayout.widthFraction);
- dest.writeInt(windowLayout.height);
- dest.writeFloat(windowLayout.heightFraction);
- dest.writeInt(windowLayout.gravity);
- dest.writeInt(windowLayout.minWidth);
- dest.writeInt(windowLayout.minHeight);
+ windowLayout.writeToParcel(dest);
} else {
dest.writeInt(0);
}
@@ -1372,8 +1366,8 @@
* @attr ref android.R.styleable#AndroidManifestLayout_minHeight
*/
public static final class WindowLayout {
- public WindowLayout(int width, float widthFraction, int height, float heightFraction, int gravity,
- int minWidth, int minHeight) {
+ public WindowLayout(int width, float widthFraction, int height, float heightFraction,
+ int gravity, int minWidth, int minHeight) {
this.width = width;
this.widthFraction = widthFraction;
this.height = height;
@@ -1392,6 +1386,7 @@
gravity = source.readInt();
minWidth = source.readInt();
minHeight = source.readInt();
+ windowLayoutAffinity = source.readString();
}
/**
@@ -1458,11 +1453,30 @@
public final int minHeight;
/**
+ * Affinity of window layout parameters. Activities with the same UID and window layout
+ * affinity will share the same window dimension record.
+ * @hide
+ */
+ public String windowLayoutAffinity;
+
+ /**
* Returns if this {@link WindowLayout} has specified bounds.
* @hide
*/
public boolean hasSpecifiedSize() {
return width >= 0 || height >= 0 || widthFraction >= 0 || heightFraction >= 0;
}
+
+ /** @hide */
+ public void writeToParcel(Parcel dest) {
+ dest.writeInt(width);
+ dest.writeFloat(widthFraction);
+ dest.writeInt(height);
+ dest.writeFloat(heightFraction);
+ dest.writeInt(gravity);
+ dest.writeInt(minWidth);
+ dest.writeInt(minHeight);
+ dest.writeString(windowLayoutAffinity);
+ }
}
}
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 4c6fef2..c82fffa 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -25,6 +25,7 @@
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ProcessInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
@@ -38,6 +39,8 @@
import android.util.proto.ProtoOutputStream;
import com.android.internal.util.ArrayUtils;
+import com.android.internal.util.Parcelling;
+import com.android.internal.util.Parcelling.BuiltIn.ForBoolean;
import com.android.server.SystemConfig;
import java.lang.annotation.Retention;
@@ -56,7 +59,8 @@
* <application> tag.
*/
public class ApplicationInfo extends PackageItemInfo implements Parcelable {
-
+ private static ForBoolean sForBoolean = Parcelling.Cache.getOrCreate(ForBoolean.class);
+
/**
* Default task affinity of all activities in this application. See
* {@link ActivityInfo#taskAffinity} for more information. This comes
@@ -247,7 +251,11 @@
* accommodate different screen densities. Corresponds to
* {@link android.R.styleable#AndroidManifestSupportsScreens_anyDensity
* android:anyDensity}.
+ *
+ * @deprecated Set by default when targeting API 4 or higher and apps
+ * should not set this to false.
*/
+ @Deprecated
public static final int FLAG_SUPPORTS_SCREEN_DENSITIES = 1<<13;
/**
@@ -1269,6 +1277,14 @@
public String zygotePreloadName;
/**
+ * Indicates if the application has requested GWP-ASan to be enabled, disabled, or left
+ * unspecified. Processes can override this setting.
+ * @hide
+ */
+ @Nullable
+ public Boolean enableGwpAsan;
+
+ /**
* Represents the default policy. The actual policy used will depend on other properties of
* the application, e.g. the target SDK version.
* @hide
@@ -1409,6 +1425,9 @@
pw.println(prefix + "usesNonSdkApi=" + usesNonSdkApi());
pw.println(prefix + "allowsPlaybackCapture="
+ (isAudioPlaybackCaptureAllowed() ? "true" : "false"));
+ if (enableGwpAsan != null) {
+ pw.println(prefix + "enableGwpAsan=" + enableGwpAsan);
+ }
}
super.dumpBack(pw, prefix);
}
@@ -1507,6 +1526,9 @@
if (category != CATEGORY_UNDEFINED) {
proto.write(ApplicationInfoProto.Detail.CATEGORY, category);
}
+ if (enableGwpAsan != null) {
+ proto.write(ApplicationInfoProto.Detail.ENABLE_GWP_ASAN, enableGwpAsan);
+ }
proto.end(detailToken);
}
proto.end(token);
@@ -1616,6 +1638,7 @@
mHiddenApiPolicy = orig.mHiddenApiPolicy;
hiddenUntilInstalled = orig.hiddenUntilInstalled;
zygotePreloadName = orig.zygotePreloadName;
+ enableGwpAsan = orig.enableGwpAsan;
}
public String toString() {
@@ -1699,6 +1722,7 @@
dest.writeInt(mHiddenApiPolicy);
dest.writeInt(hiddenUntilInstalled ? 1 : 0);
dest.writeString(zygotePreloadName);
+ sForBoolean.parcel(enableGwpAsan, dest, parcelableFlags);
}
public static final @android.annotation.NonNull Parcelable.Creator<ApplicationInfo> CREATOR
@@ -1779,6 +1803,7 @@
mHiddenApiPolicy = source.readInt();
hiddenUntilInstalled = source.readInt() != 0;
zygotePreloadName = source.readString();
+ enableGwpAsan = sForBoolean.unparcel(source);
}
/**
@@ -2157,6 +2182,7 @@
/** {@hide} */ public void setResourcePath(String resourcePath) { scanPublicSourceDir = resourcePath; }
/** {@hide} */ public void setBaseResourcePath(String baseResourcePath) { publicSourceDir = baseResourcePath; }
/** {@hide} */ public void setSplitResourcePaths(String[] splitResourcePaths) { splitPublicSourceDirs = splitResourcePaths; }
+ /** {@hide} */ public void setGwpAsanEnabled(@Nullable Boolean value) { enableGwpAsan = value; }
/** {@hide} */
@UnsupportedAppUsage
@@ -2168,4 +2194,6 @@
@UnsupportedAppUsage
public String getBaseResourcePath() { return publicSourceDir; }
/** {@hide} */ public String[] getSplitResourcePaths() { return splitPublicSourceDirs; }
+ @Nullable
+ public Boolean isGwpAsanEnabled() { return enableGwpAsan; }
}
diff --git a/core/java/android/content/pm/CrossProfileApps.java b/core/java/android/content/pm/CrossProfileApps.java
index 3261cb1..dc3a029 100644
--- a/core/java/android/content/pm/CrossProfileApps.java
+++ b/core/java/android/content/pm/CrossProfileApps.java
@@ -27,6 +27,7 @@
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
+import android.os.Bundle;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
@@ -95,7 +96,7 @@
mService.startActivityAsUser(
mContext.getIApplicationThread(),
mContext.getPackageName(),
- mContext.getFeatureId(),
+ mContext.getAttributionTag(),
component,
targetUser.getIdentifier(),
true);
@@ -128,14 +129,44 @@
@NonNull Intent intent,
@NonNull UserHandle targetUser,
@Nullable Activity callingActivity) {
+ startActivity(intent, targetUser, callingActivity, /* options= */ null);
+ }
+
+ /**
+ * Starts the specified activity of the caller package in the specified profile.
+ *
+ * <p>The caller must have the {@link android.Manifest.permission#INTERACT_ACROSS_PROFILES},
+ * {@code android.Manifest.permission#INTERACT_ACROSS_USERS}, or {@code
+ * android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission. Both the caller and
+ * target user profiles must be in the same profile group. The target user must be a valid user
+ * returned from {@link #getTargetUserProfiles()}.
+ *
+ * @param intent The intent to launch. A component in the caller package must be specified.
+ * @param targetUser The {@link UserHandle} of the profile; must be one of the users returned by
+ * {@link #getTargetUserProfiles()} if different to the calling user, otherwise a
+ * {@link SecurityException} will be thrown.
+ * @param callingActivity The activity to start the new activity from for the purposes of
+ * deciding which task the new activity should belong to. If {@code null}, the activity
+ * will always be started in a new task.
+ * @param options The activity options or {@code null}. See {@link android.app.ActivityOptions}.
+ */
+ @RequiresPermission(anyOf = {
+ android.Manifest.permission.INTERACT_ACROSS_PROFILES,
+ android.Manifest.permission.INTERACT_ACROSS_USERS})
+ public void startActivity(
+ @NonNull Intent intent,
+ @NonNull UserHandle targetUser,
+ @Nullable Activity callingActivity,
+ @Nullable Bundle options) {
try {
mService.startActivityAsUserByIntent(
mContext.getIApplicationThread(),
mContext.getPackageName(),
- mContext.getFeatureId(),
+ mContext.getAttributionTag(),
intent,
targetUser.getIdentifier(),
- callingActivity != null ? callingActivity.getActivityToken() : null);
+ callingActivity != null ? callingActivity.getActivityToken() : null,
+ options);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
@@ -159,7 +190,7 @@
public void startActivity(@NonNull ComponentName component, @NonNull UserHandle targetUser) {
try {
mService.startActivityAsUser(mContext.getIApplicationThread(),
- mContext.getPackageName(), mContext.getFeatureId(), component,
+ mContext.getPackageName(), mContext.getAttributionTag(), component,
targetUser.getIdentifier(), false);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
diff --git a/core/java/android/content/pm/ICrossProfileApps.aidl b/core/java/android/content/pm/ICrossProfileApps.aidl
index 5a6e008..4cecb30 100644
--- a/core/java/android/content/pm/ICrossProfileApps.aidl
+++ b/core/java/android/content/pm/ICrossProfileApps.aidl
@@ -31,7 +31,8 @@
in String callingFeatureId, in ComponentName component, int userId,
boolean launchMainActivity);
void startActivityAsUserByIntent(in IApplicationThread caller, in String callingPackage,
- in String callingFeatureId, in Intent intent, int userId, in IBinder callingActivity);
+ in String callingFeatureId, in Intent intent, int userId, in IBinder callingActivity,
+ in Bundle options);
List<UserHandle> getTargetUserProfiles(in String callingPackage);
boolean canInteractAcrossProfiles(in String callingPackage);
boolean canRequestInteractAcrossProfiles(in String callingPackage);
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 8c3eef2..0311120 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -748,4 +748,6 @@
void clearMimeGroup(String packageName, String group);
List<String> getMimeGroup(String packageName, String group);
+
+ boolean isAutoRevokeWhitelisted(String packageName);
}
diff --git a/core/java/android/content/pm/InstallSourceInfo.java b/core/java/android/content/pm/InstallSourceInfo.java
index c0fdcc9..a45bf79 100644
--- a/core/java/android/content/pm/InstallSourceInfo.java
+++ b/core/java/android/content/pm/InstallSourceInfo.java
@@ -66,7 +66,18 @@
mInstallingPackageName = source.readString();
}
- /** The name of the package that requested the installation, or null if not available. */
+ /**
+ * The name of the package that requested the installation, or null if not available.
+ *
+ * This is normally the same as the installing package name. If the installing package name
+ * is changed, for example by calling
+ * {@link PackageManager#setInstallerPackageName(String, String)}, the initiating package name
+ * remains unchanged. It continues to identify the actual package that performed the install
+ * or update.
+ * <p>
+ * Null may be returned if the app was not installed by a package (e.g. a system app or an app
+ * installed via adb) or if the initiating package has itself been uninstalled.
+ */
@Nullable
public String getInitiatingPackageName() {
return mInitiatingPackageName;
@@ -100,9 +111,11 @@
/**
* The name of the package responsible for the installation (the installer of record), or null
* if not available.
- * Note that this may differ from the initiating package name and can be modified.
- *
- * @see PackageManager#setInstallerPackageName(String, String)
+ * Note that this may differ from the initiating package name and can be modified via
+ * {@link PackageManager#setInstallerPackageName(String, String)}.
+ * <p>
+ * Null may be returned if the app was not installed by a package (e.g. a system app or an app
+ * installed via adb) or if the installing package has itself been uninstalled.
*/
@Nullable
public String getInstallingPackageName() {
diff --git a/core/java/android/content/pm/InstallationFile.java b/core/java/android/content/pm/InstallationFile.java
index edc04c9..de761ad 100644
--- a/core/java/android/content/pm/InstallationFile.java
+++ b/core/java/android/content/pm/InstallationFile.java
@@ -21,13 +21,25 @@
import android.annotation.SystemApi;
/**
- * Defines the properties of a file in an installation session.
+ * Definition of a file in a streaming installation session.
+ * You can use this class to retrieve the information of such a file, such as its name, size and
+ * metadata. These file attributes will be consistent with those used in:
+ * {@code PackageInstaller.Session#addFile}, when the file was first added into the session.
+ *
+ * WARNING: This is a system API to aid internal development.
+ * Use at your own risk. It will change or be removed without warning.
+ *
+ * @see android.content.pm.PackageInstaller.Session#addFile
* @hide
*/
@SystemApi
public final class InstallationFile {
private final @NonNull InstallationFileParcel mParcel;
+ /**
+ * Constructor, internal use only
+ * @hide
+ */
public InstallationFile(@PackageInstaller.FileLocation int location, @NonNull String name,
long lengthBytes, @Nullable byte[] metadata, @Nullable byte[] signature) {
mParcel = new InstallationFileParcel();
@@ -38,22 +50,44 @@
mParcel.signature = signature;
}
+ /**
+ * Installation Location of this file. Can be one of the following three locations:
+ * <ul>
+ * <li>(1) {@code PackageInstaller.LOCATION_DATA_APP}</li>
+ * <li>(2) {@code PackageInstaller.LOCATION_MEDIA_OBB}</li>
+ * <li>(3) {@code PackageInstaller.LOCATION_MEDIA_DATA}</li>
+ * </ul>
+ * @see android.content.pm.PackageInstaller
+ * @return Integer that denotes the installation location of the file.
+ */
public @PackageInstaller.FileLocation int getLocation() {
return mParcel.location;
}
+ /**
+ * @return Name of the file.
+ */
public @NonNull String getName() {
return mParcel.name;
}
+ /**
+ * @return File size in bytes.
+ */
public long getLengthBytes() {
return mParcel.size;
}
+ /**
+ * @return File metadata as a byte array
+ */
public @Nullable byte[] getMetadata() {
return mParcel.metadata;
}
+ /**
+ * @return File signature info as a byte array
+ */
public @Nullable byte[] getSignature() {
return mParcel.signature;
}
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index 86242fd..4e4897f 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -721,7 +721,7 @@
}
try {
mService.startActivityAsUser(mContext.getIApplicationThread(),
- mContext.getPackageName(), mContext.getFeatureId(),
+ mContext.getPackageName(), mContext.getAttributionTag(),
component, sourceBounds, opts, user);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
@@ -739,8 +739,8 @@
@Nullable Rect sourceBounds, @Nullable Bundle opts) {
try {
mService.startSessionDetailsActivityAsUser(mContext.getIApplicationThread(),
- mContext.getPackageName(), mContext.getFeatureId(), sessionInfo, sourceBounds,
- opts, sessionInfo.getUser());
+ mContext.getPackageName(), mContext.getAttributionTag(), sessionInfo,
+ sourceBounds, opts, sessionInfo.getUser());
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
@@ -760,7 +760,7 @@
logErrorForInvalidProfileAccess(user);
try {
mService.showAppDetailsAsUser(mContext.getIApplicationThread(),
- mContext.getPackageName(), mContext.getFeatureId(),
+ mContext.getPackageName(), mContext.getAttributionTag(),
component, sourceBounds, opts, user);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index 1f53176..50bee85 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -16,6 +16,10 @@
package android.content.pm;
+import static android.app.AppOpsManager.MODE_ALLOWED;
+import static android.app.AppOpsManager.MODE_DEFAULT;
+import static android.app.AppOpsManager.MODE_IGNORED;
+
import android.Manifest;
import android.annotation.CurrentTimeMillisLong;
import android.annotation.IntDef;
@@ -1456,6 +1460,8 @@
/** {@hide} */
public List<String> whitelistedRestrictedPermissions;
/** {@hide} */
+ public int autoRevokePermissionsMode = MODE_DEFAULT;
+ /** {@hide} */
public String installerPackageName;
/** {@hide} */
public boolean isMultiPackage;
@@ -1498,6 +1504,7 @@
volumeUuid = source.readString();
grantedRuntimePermissions = source.readStringArray();
whitelistedRestrictedPermissions = source.createStringArrayList();
+ autoRevokePermissionsMode = source.readInt();
installerPackageName = source.readString();
isMultiPackage = source.readBoolean();
isStaged = source.readBoolean();
@@ -1528,6 +1535,7 @@
ret.volumeUuid = volumeUuid;
ret.grantedRuntimePermissions = grantedRuntimePermissions;
ret.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions;
+ ret.autoRevokePermissionsMode = autoRevokePermissionsMode;
ret.installerPackageName = installerPackageName;
ret.isMultiPackage = isMultiPackage;
ret.isStaged = isStaged;
@@ -1691,6 +1699,22 @@
}
/**
+ * Sets whether permissions should be auto-revoked if this package is unused for an
+ * extended periodd of time.
+ *
+ * It's disabled by default but generally the installer should enable it for most packages,
+ * excluding only those where doing so might cause breakage that cannot be easily addressed
+ * by simply re-requesting the permission(s).
+ *
+ * If user explicitly enabled or disabled it via settings, this call is ignored.
+ *
+ * @param shouldAutoRevoke whether permissions should be auto-revoked.
+ */
+ public void setAutoRevokePermissionsMode(boolean shouldAutoRevoke) {
+ autoRevokePermissionsMode = shouldAutoRevoke ? MODE_ALLOWED : MODE_IGNORED;
+ }
+
+ /**
* Request that rollbacks be enabled or disabled for the given upgrade with rollback data
* policy set to RESTORE.
*
@@ -1932,6 +1956,7 @@
pw.printPair("volumeUuid", volumeUuid);
pw.printPair("grantedRuntimePermissions", grantedRuntimePermissions);
pw.printPair("whitelistedRestrictedPermissions", whitelistedRestrictedPermissions);
+ pw.printPair("autoRevokePermissions", autoRevokePermissionsMode);
pw.printPair("installerPackageName", installerPackageName);
pw.printPair("isMultiPackage", isMultiPackage);
pw.printPair("isStaged", isStaged);
@@ -1964,6 +1989,7 @@
dest.writeString(volumeUuid);
dest.writeStringArray(grantedRuntimePermissions);
dest.writeStringList(whitelistedRestrictedPermissions);
+ dest.writeInt(autoRevokePermissionsMode);
dest.writeString(installerPackageName);
dest.writeBoolean(isMultiPackage);
dest.writeBoolean(isStaged);
@@ -2085,6 +2111,8 @@
public String[] grantedRuntimePermissions;
/** {@hide}*/
public List<String> whitelistedRestrictedPermissions;
+ /** {@hide}*/
+ public int autoRevokePermissionsMode = MODE_DEFAULT;
/** {@hide} */
public int installFlags;
/** {@hide} */
@@ -2147,6 +2175,7 @@
referrerUri = source.readParcelable(null);
grantedRuntimePermissions = source.readStringArray();
whitelistedRestrictedPermissions = source.createStringArrayList();
+ autoRevokePermissionsMode = source.readInt();
installFlags = source.readInt();
isMultiPackage = source.readBoolean();
@@ -2323,6 +2352,7 @@
/**
* Get the value set in {@link SessionParams#setOriginatingUri(Uri)}.
+ * Note: This value will only be non-null for the owner of the session.
*/
public @Nullable Uri getOriginatingUri() {
return originatingUri;
@@ -2337,6 +2367,7 @@
/**
* Get the value set in {@link SessionParams#setReferrerUri(Uri)}
+ * Note: This value will only be non-null for the owner of the session.
*/
public @Nullable Uri getReferrerUri() {
return referrerUri;
@@ -2372,6 +2403,24 @@
}
/**
+ * Get the status of whether permission auto-revocation should be allowed, ignored, or
+ * deferred to manifest data.
+ *
+ * @see android.app.AppOpsManager#MODE_ALLOWED
+ * @see android.app.AppOpsManager#MODE_IGNORED
+ * @see android.app.AppOpsManager#MODE_DEFAULT
+ *
+ * @return the status of auto-revoke for this package
+ *
+ * @hide
+ */
+ @TestApi
+ @SystemApi
+ public int getAutoRevokePermissionsMode() {
+ return autoRevokePermissionsMode;
+ }
+
+ /**
* Get the value set in {@link SessionParams#setAllowDowngrade(boolean)}.
*
* @deprecated use {@link #getRequestDowngrade()}.
@@ -2658,6 +2707,7 @@
dest.writeParcelable(referrerUri, flags);
dest.writeStringArray(grantedRuntimePermissions);
dest.writeStringList(whitelistedRestrictedPermissions);
+ dest.writeInt(autoRevokePermissionsMode);
dest.writeInt(installFlags);
dest.writeBoolean(isMultiPackage);
dest.writeBoolean(isStaged);
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 9b28cb5e8..05ff830 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -557,7 +557,6 @@
* Internal {@link PackageInfo} flag used to indicate that a package is a hidden system app.
* @hide
*/
- @SystemApi
public static final int MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS = 0x20000000;
/**
@@ -1978,7 +1977,7 @@
* Feature for {@link #getSystemAvailableFeatures} and
* {@link #hasSystemFeature}: The device's main front and back cameras can stream
* concurrently as described in {@link
- * android.hardware.camera2.CameraManager#getConcurrentStreamingCameraIds()}
+ * android.hardware.camera2.CameraManager#getConcurrentCameraIds()}
*/
@SdkConstant(SdkConstantType.FEATURE)
public static final String FEATURE_CAMERA_CONCURRENT = "android.hardware.camera.concurrent";
@@ -2227,6 +2226,9 @@
* <li>{@code VkPhysicalDeviceSamplerYcbcrConversionFeatures::samplerYcbcrConversion} is
* supported.</li>
* </ul>
+ * A subset of devices that support Vulkan 1.1 do so via software emulation. For more
+ * information, see
+ * <a href="{@docRoot}ndk/guides/graphics/design-notes">Vulkan Design Guidelines</a>.
*/
@SdkConstant(SdkConstantType.FEATURE)
public static final String FEATURE_VULKAN_HARDWARE_VERSION = "android.hardware.vulkan.version";
@@ -3400,37 +3402,21 @@
public static final int FLAG_PERMISSION_ONE_TIME = 1 << 16;
/**
- * Permission flag: The permission is whitelisted to not be auto-revoked when app goes unused.
- *
- * @hide
- */
- @SystemApi
- public static final int FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED = 1 << 17;
-
- /**
- * Permission flag: Whether {@link #FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED} state was set by
- * user.
- *
- * @hide
- */
- @SystemApi
- public static final int FLAG_PERMISSION_AUTO_REVOKE_USER_SET = 1 << 18;
-
- /**
* Permission flag: Whether permission was revoked by auto-revoke.
*
* @hide
*/
@SystemApi
- public static final int FLAG_PERMISSION_AUTO_REVOKED = 1 << 20;
+ public static final int FLAG_PERMISSION_AUTO_REVOKED = 1 << 17;
/**
- * Permission flags: Reserved for use by the permission controller.
- *
+ * Permission flags: Reserved for use by the permission controller. The platform and any
+ * packages besides the permission controller should not assume any definition about these
+ * flags.
* @hide
*/
@SystemApi
- public static final int FLAGS_PERMISSION_RESERVED_PERMISSIONCONTROLLER = 1 << 28 | 1 << 29
+ public static final int FLAGS_PERMISSION_RESERVED_PERMISSION_CONTROLLER = 1 << 28 | 1 << 29
| 1 << 30 | 1 << 31;
/**
@@ -3476,8 +3462,6 @@
| FLAG_PERMISSION_GRANTED_BY_ROLE
| FLAG_PERMISSION_REVOKED_COMPAT
| FLAG_PERMISSION_ONE_TIME
- | FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED
- | FLAG_PERMISSION_AUTO_REVOKE_USER_SET
| FLAG_PERMISSION_AUTO_REVOKED;
/**
@@ -4302,8 +4286,6 @@
FLAG_PERMISSION_GRANTED_BY_ROLE,
FLAG_PERMISSION_REVOKED_COMPAT,
FLAG_PERMISSION_ONE_TIME,
- FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED,
- FLAG_PERMISSION_AUTO_REVOKE_USER_SET,
FLAG_PERMISSION_AUTO_REVOKED
})
@Retention(RetentionPolicy.SOURCE)
@@ -4593,6 +4575,53 @@
}
/**
+ * Marks an application exempt from having its permissions be automatically revoked when
+ * the app is unused for an extended period of time.
+ *
+ * Only the installer on record that installed the given package, or a holder of
+ * {@code WHITELIST_AUTO_REVOKE_PERMISSIONS} is allowed to call this.
+ *
+ * Packages start in whitelisted state, and it is the installer's responsibility to
+ * un-whitelist the packages it installs, unless auto-revoking permissions from that package
+ * would cause breakages beyond having to re-request the permission(s).
+ *
+ * @param packageName The app for which to set exemption.
+ * @param whitelisted Whether the app should be whitelisted.
+ *
+ * @return whether any change took effect.
+ *
+ * @see #isAutoRevokeWhitelisted
+ *
+ * @throws SecurityException if you you have no access to modify this.
+ */
+ @RequiresPermission(value = Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS,
+ conditional = true)
+ public boolean setAutoRevokeWhitelisted(@NonNull String packageName, boolean whitelisted) {
+ return false;
+ }
+
+ /**
+ * Checks whether an application is exempt from having its permissions be automatically revoked
+ * when the app is unused for an extended period of time.
+ *
+ * Only the installer on record that installed the given package, or a holder of
+ * {@code WHITELIST_AUTO_REVOKE_PERMISSIONS} is allowed to call this.
+ * @param packageName The app for which to set exemption.
+ *
+ * @return Whether the app is whitelisted.
+ *
+ * @see #setAutoRevokeWhitelisted
+ *
+ * @throws SecurityException if you you have no access to this.
+ */
+ @RequiresPermission(value = Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS,
+ conditional = true)
+ public boolean isAutoRevokeWhitelisted(@NonNull String packageName) {
+ return false;
+ }
+
+
+ /**
* Gets whether you should show UI with rationale for requesting a permission.
* You should do this only if you do not have the permission and the context in
* which the permission is requested does not clearly communicate to the user
@@ -7471,8 +7500,6 @@
case FLAG_PERMISSION_GRANTED_BY_ROLE: return "GRANTED_BY_ROLE";
case FLAG_PERMISSION_REVOKED_COMPAT: return "REVOKED_COMPAT";
case FLAG_PERMISSION_ONE_TIME: return "ONE_TIME";
- case FLAG_PERMISSION_AUTO_REVOKE_IF_UNUSED: return "AUTO_REVOKE_IF_UNUSED";
- case FLAG_PERMISSION_AUTO_REVOKE_USER_SET: return "AUTO_REVOKE_USER_SET";
case FLAG_PERMISSION_AUTO_REVOKED: return "AUTO_REVOKED";
default: return Integer.toString(flag);
}
@@ -7854,6 +7881,15 @@
}
/**
+ * @return whether this package is whitelisted from having its runtime permission be
+ * auto-revoked if unused for an extended period of time.
+ */
+ public boolean isAutoRevokeWhitelisted() {
+ throw new UnsupportedOperationException(
+ "isAutoRevokeWhitelisted not implemented in subclass");
+ }
+
+ /**
* Returns if the provided drawable represents the default activity icon provided by the system.
*
* PackageManager silently returns a default application icon for any package/activity if the
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index c6875a4..18f1343 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -55,7 +55,6 @@
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.pm.parsing.ParsingPackageUtils;
import android.content.pm.permission.SplitPermissionInfoParcelable;
import android.content.pm.split.DefaultSplitAssetLoader;
import android.content.pm.split.SplitAssetDependencyLoader;
@@ -190,7 +189,7 @@
public static final String TAG_OVERLAY = "overlay";
public static final String TAG_PACKAGE = "package";
public static final String TAG_PACKAGE_VERIFIER = "package-verifier";
- public static final String TAG_FEATURE = "feature";
+ public static final String TAG_ATTRIBUTION = "attribution";
public static final String TAG_PERMISSION = "permission";
public static final String TAG_PERMISSION_GROUP = "permission-group";
public static final String TAG_PERMISSION_TREE = "permission-tree";
@@ -209,6 +208,8 @@
public static final String TAG_USES_SPLIT = "uses-split";
public static final String METADATA_MAX_ASPECT_RATIO = "android.max_aspect";
+ public static final String METADATA_ACTIVITY_WINDOW_LAYOUT_AFFINITY =
+ "android.activity_window_layout_affinity";
/**
* Bit mask of all the valid bits that can be set in recreateOnConfigChanges.
@@ -4560,6 +4561,8 @@
}
}
+ resolveWindowLayout(a);
+
if (!setExported) {
a.info.exported = a.intents.size() > 0;
}
@@ -4726,6 +4729,35 @@
height, heightFraction, gravity, minWidth, minHeight);
}
+ /**
+ * Resolves values in {@link ActivityInfo.WindowLayout}.
+ *
+ * <p>{@link ActivityInfo.WindowLayout#windowLayoutAffinity} has a fallback metadata used in
+ * Android R and some variants of pre-R.
+ */
+ private void resolveWindowLayout(Activity activity) {
+ // There isn't a metadata for us to fall back. Whatever is in layout is correct.
+ if (activity.metaData == null
+ || !activity.metaData.containsKey(METADATA_ACTIVITY_WINDOW_LAYOUT_AFFINITY)) {
+ return;
+ }
+
+ final ActivityInfo aInfo = activity.info;
+ // Layout already specifies a value. We should just use that one.
+ if (aInfo.windowLayout != null && aInfo.windowLayout.windowLayoutAffinity != null) {
+ return;
+ }
+
+ String windowLayoutAffinity = activity.metaData.getString(
+ METADATA_ACTIVITY_WINDOW_LAYOUT_AFFINITY);
+ if (aInfo.windowLayout == null) {
+ aInfo.windowLayout = new ActivityInfo.WindowLayout(-1 /* width */,
+ -1 /* widthFraction */, -1 /* height */, -1 /* heightFraction */,
+ Gravity.NO_GRAVITY, -1 /* minWidth */, -1 /* minHeight */);
+ }
+ aInfo.windowLayout.windowLayoutAffinity = windowLayoutAffinity;
+ }
+
private Activity parseActivityAlias(Package owner, Resources res,
XmlResourceParser parser, int flags, String[] outError,
CachedComponentArgs cachedArgs)
diff --git a/core/java/android/content/pm/ProcessInfo.java b/core/java/android/content/pm/ProcessInfo.java
index c77a267..a373067 100644
--- a/core/java/android/content/pm/ProcessInfo.java
+++ b/core/java/android/content/pm/ProcessInfo.java
@@ -23,66 +23,157 @@
import android.text.TextUtils;
import android.util.ArraySet;
+import com.android.internal.util.DataClass;
+import com.android.internal.util.Parcelling;
+
/**
* Information about a process an app may run. This corresponds to information collected from the
* AndroidManifest.xml's <permission-group> tags.
* @hide
*/
+@DataClass(genGetters = true, genSetters = false, genParcelable = true, genAidl = false,
+ genBuilder = false)
public class ProcessInfo implements Parcelable {
/**
* The name of the process, fully-qualified based on the app's package name.
*/
+ @NonNull
public String name;
/**
* If non-null, these are permissions that are not allowed in this process.
*/
@Nullable
+ @DataClass.ParcelWith(Parcelling.BuiltIn.ForInternedStringArraySet.class)
public ArraySet<String> deniedPermissions;
- public ProcessInfo(String name, ArraySet<String> deniedPermissions) {
- this.name = name;
- this.deniedPermissions = deniedPermissions;
- }
+ /**
+ * Indicates if the process has requested GWP-ASan to be enabled, disabled, or left unspecified.
+ */
+ @Nullable
+ public Boolean enableGwpAsan;
@Deprecated
public ProcessInfo(@NonNull ProcessInfo orig) {
this.name = orig.name;
this.deniedPermissions = orig.deniedPermissions;
+ this.enableGwpAsan = orig.enableGwpAsan;
}
- public int describeContents() {
- return 0;
+
+
+ // Code below generated by codegen v1.0.15.
+ //
+ // DO NOT MODIFY!
+ // CHECKSTYLE:OFF Generated code
+ //
+ // To regenerate run:
+ // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/content/pm/ProcessInfo.java
+ //
+ // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
+ // Settings > Editor > Code Style > Formatter Control
+ //@formatter:off
+
+
+ /**
+ * Creates a new ProcessInfo.
+ *
+ * @param name
+ * The name of the process, fully-qualified based on the app's package name.
+ * @param deniedPermissions
+ * If non-null, these are permissions that are not allowed in this process.
+ * @param enableGwpAsan
+ * Indicates if the process has requested GWP-ASan to be enabled, disabled, or left unspecified.
+ */
+ @DataClass.Generated.Member
+ public ProcessInfo(
+ @NonNull String name,
+ @Nullable ArraySet<String> deniedPermissions,
+ @Nullable Boolean enableGwpAsan) {
+ this.name = name;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, name);
+ this.deniedPermissions = deniedPermissions;
+ this.enableGwpAsan = enableGwpAsan;
+
+ // onConstructed(); // You can define this method to get a callback
}
- public void writeToParcel(Parcel dest, int parcelableFlags) {
- dest.writeString(this.name);
- final int numDenied = this.deniedPermissions != null
- ? this.deniedPermissions.size() : 0;
- dest.writeInt(numDenied);
- for (int i = 0; i < numDenied; i++) {
- dest.writeString(this.deniedPermissions.valueAt(i));
+ @DataClass.Generated.Member
+ static Parcelling<ArraySet<String>> sParcellingForDeniedPermissions =
+ Parcelling.Cache.get(
+ Parcelling.BuiltIn.ForInternedStringArraySet.class);
+ static {
+ if (sParcellingForDeniedPermissions == null) {
+ sParcellingForDeniedPermissions = Parcelling.Cache.put(
+ new Parcelling.BuiltIn.ForInternedStringArraySet());
}
}
- public static final @NonNull Creator<ProcessInfo> CREATOR =
- new Creator<ProcessInfo>() {
- public ProcessInfo createFromParcel(Parcel source) {
- return new ProcessInfo(source);
- }
- public ProcessInfo[] newArray(int size) {
- return new ProcessInfo[size];
- }
- };
+ @Override
+ @DataClass.Generated.Member
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ // You can override field parcelling by defining methods like:
+ // void parcelFieldName(Parcel dest, int flags) { ... }
- private ProcessInfo(Parcel source) {
- this.name = source.readString();
- final int numDenied = source.readInt();
- if (numDenied > 0) {
- this.deniedPermissions = new ArraySet<>(numDenied);
- for (int i = numDenied - 1; i >= 0; i--) {
- this.deniedPermissions.add(TextUtils.safeIntern(source.readString()));
- }
- }
+ byte flg = 0;
+ if (deniedPermissions != null) flg |= 0x2;
+ if (enableGwpAsan != null) flg |= 0x4;
+ dest.writeByte(flg);
+ dest.writeString(name);
+ sParcellingForDeniedPermissions.parcel(deniedPermissions, dest, flags);
+ if (enableGwpAsan != null) dest.writeBoolean(enableGwpAsan);
}
+
+ @Override
+ @DataClass.Generated.Member
+ public int describeContents() { return 0; }
+
+ /** @hide */
+ @SuppressWarnings({"unchecked", "RedundantCast"})
+ @DataClass.Generated.Member
+ protected ProcessInfo(@NonNull Parcel in) {
+ // You can override field unparcelling by defining methods like:
+ // static FieldType unparcelFieldName(Parcel in) { ... }
+
+ byte flg = in.readByte();
+ String _name = in.readString();
+ ArraySet<String> _deniedPermissions = sParcellingForDeniedPermissions.unparcel(in);
+ Boolean _enableGwpAsan = (flg & 0x4) == 0 ? null : (Boolean) in.readBoolean();
+
+ this.name = _name;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, name);
+ this.deniedPermissions = _deniedPermissions;
+ this.enableGwpAsan = _enableGwpAsan;
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ @DataClass.Generated.Member
+ public static final @NonNull Parcelable.Creator<ProcessInfo> CREATOR
+ = new Parcelable.Creator<ProcessInfo>() {
+ @Override
+ public ProcessInfo[] newArray(int size) {
+ return new ProcessInfo[size];
+ }
+
+ @Override
+ public ProcessInfo createFromParcel(@NonNull Parcel in) {
+ return new ProcessInfo(in);
+ }
+ };
+
+ @DataClass.Generated(
+ time = 1582840056156L,
+ codegenVersion = "1.0.15",
+ sourceFile = "frameworks/base/core/java/android/content/pm/ProcessInfo.java",
+ inputSignatures = "public @android.annotation.NonNull java.lang.String name\npublic @android.annotation.Nullable @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInternedStringArraySet.class) android.util.ArraySet<java.lang.String> deniedPermissions\npublic @android.annotation.Nullable java.lang.Boolean enableGwpAsan\nclass ProcessInfo extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genGetters=true, genSetters=false, genParcelable=true, genAidl=false, genBuilder=false)")
+ @Deprecated
+ private void __metadata() {}
+
+
+ //@formatter:on
+ // End of generated code
+
}
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 49e8c05..af87578 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -1558,11 +1558,6 @@
* "Rank" of a shortcut, which is a non-negative, sequential value that's unique for each
* {@link #getActivity} for each of the two types of shortcuts (static and dynamic).
*
- * <p>Because static shortcuts and dynamic shortcuts have overlapping ranks,
- * when a launcher app shows shortcuts for an activity, it should first show
- * the static shortcuts, followed by the dynamic shortcuts. Within each of those categories,
- * shortcuts should be sorted by rank in ascending order.
- *
* <p><em>Floating shortcuts</em>, or shortcuts that are neither static nor dynamic, will all
* have rank 0, because they aren't sorted.
*
diff --git a/core/java/android/content/pm/parsing/ParsingPackage.java b/core/java/android/content/pm/parsing/ParsingPackage.java
index aa93d80..1304ba8 100644
--- a/core/java/android/content/pm/parsing/ParsingPackage.java
+++ b/core/java/android/content/pm/parsing/ParsingPackage.java
@@ -24,7 +24,7 @@
import android.content.pm.FeatureInfo;
import android.content.pm.PackageParser;
import android.content.pm.parsing.component.ParsedActivity;
-import android.content.pm.parsing.component.ParsedFeature;
+import android.content.pm.parsing.component.ParsedAttribution;
import android.content.pm.parsing.component.ParsedInstrumentation;
import android.content.pm.parsing.component.ParsedIntentInfo;
import android.content.pm.parsing.component.ParsedPermission;
@@ -77,7 +77,7 @@
ParsingPackage addProvider(ParsedProvider parsedProvider);
- ParsingPackage addFeature(ParsedFeature permission);
+ ParsingPackage addAttribution(ParsedAttribution attribution);
ParsingPackage addReceiver(ParsedActivity parsedReceiver);
@@ -191,7 +191,11 @@
ParsingPackage setRequestLegacyExternalStorage(boolean requestLegacyExternalStorage);
ParsingPackage setAllowNativeHeapPointerTagging(boolean allowNativeHeapPointerTagging);
-
+
+ ParsingPackage setDontAutoRevokePermissions(boolean dontAutoRevokePermissions);
+
+ ParsingPackage setAllowDontAutoRevokePermissions(boolean allowDontAutoRevokePermissions);
+
ParsingPackage setPreserveLegacyExternalStorage(boolean preserveLegacyExternalStorage);
ParsingPackage setRestoreAnyVersion(boolean restoreAnyVersion);
@@ -236,6 +240,8 @@
ParsingPackage setEnabled(boolean enabled);
+ ParsingPackage setGwpAsanEnabled(Boolean enableGwpAsan);
+
ParsingPackage setCrossProfile(boolean crossProfile);
ParsingPackage setFullBackupContent(int fullBackupContent);
diff --git a/core/java/android/content/pm/parsing/ParsingPackageImpl.java b/core/java/android/content/pm/parsing/ParsingPackageImpl.java
index a9b72d0..3390f16 100644
--- a/core/java/android/content/pm/parsing/ParsingPackageImpl.java
+++ b/core/java/android/content/pm/parsing/ParsingPackageImpl.java
@@ -30,9 +30,10 @@
import android.content.pm.FeatureInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageParser;
+import android.content.pm.ProcessInfo;
import android.content.pm.parsing.component.ParsedActivity;
+import android.content.pm.parsing.component.ParsedAttribution;
import android.content.pm.parsing.component.ParsedComponent;
-import android.content.pm.parsing.component.ParsedFeature;
import android.content.pm.parsing.component.ParsedInstrumentation;
import android.content.pm.parsing.component.ParsedIntentInfo;
import android.content.pm.parsing.component.ParsedMainComponent;
@@ -243,7 +244,7 @@
protected List<ParsedProvider> providers = emptyList();
@NonNull
- private List<ParsedFeature> features = emptyList();
+ private List<ParsedAttribution> attributions = emptyList();
@NonNull
protected List<ParsedPermission> permissions = emptyList();
@@ -404,8 +405,14 @@
private boolean hasFragileUserData;
private boolean cantSaveState;
private boolean allowNativeHeapPointerTagging;
+ private boolean dontAutoRevokePermissions;
+ private boolean allowDontAutoRevokePermissions;
private boolean preserveLegacyExternalStorage;
+ @Nullable
+ @DataClass.ParcelWith(ForBoolean.class)
+ protected Boolean enableGwpAsan = null;
+
// TODO(chiuwinson): Non-null
@Nullable
private ArraySet<String> mimeGroups;
@@ -620,8 +627,8 @@
}
@Override
- public ParsingPackageImpl addFeature(ParsedFeature feature) {
- this.features = CollectionUtils.add(this.features, feature);
+ public ParsingPackageImpl addAttribution(ParsedAttribution attribution) {
+ this.attributions = CollectionUtils.add(this.attributions, attribution);
return this;
}
@@ -904,7 +911,7 @@
appInfo.volumeUuid = volumeUuid;
appInfo.zygotePreloadName = zygotePreloadName;
appInfo.crossProfile = isCrossProfile();
-
+ appInfo.setGwpAsanEnabled(enableGwpAsan);
appInfo.setBaseCodePath(baseCodePath);
appInfo.setBaseResourcePath(baseCodePath);
appInfo.setCodePath(codePath);
@@ -990,7 +997,7 @@
dest.writeTypedList(this.receivers);
dest.writeTypedList(this.services);
dest.writeTypedList(this.providers);
- dest.writeTypedList(this.features);
+ dest.writeTypedList(this.attributions);
dest.writeTypedList(this.permissions);
dest.writeTypedList(this.permissionGroups);
dest.writeTypedList(this.instrumentations);
@@ -1084,8 +1091,11 @@
dest.writeBoolean(this.hasFragileUserData);
dest.writeBoolean(this.cantSaveState);
dest.writeBoolean(this.allowNativeHeapPointerTagging);
+ dest.writeBoolean(this.dontAutoRevokePermissions);
+ dest.writeBoolean(this.allowDontAutoRevokePermissions);
dest.writeBoolean(this.preserveLegacyExternalStorage);
dest.writeArraySet(this.mimeGroups);
+ sForBoolean.parcel(this.enableGwpAsan, dest, flags);
}
public ParsingPackageImpl(Parcel in) {
@@ -1149,7 +1159,7 @@
this.receivers = in.createTypedArrayList(ParsedActivity.CREATOR);
this.services = in.createTypedArrayList(ParsedService.CREATOR);
this.providers = in.createTypedArrayList(ParsedProvider.CREATOR);
- this.features = in.createTypedArrayList(ParsedFeature.CREATOR);
+ this.attributions = in.createTypedArrayList(ParsedAttribution.CREATOR);
this.permissions = in.createTypedArrayList(ParsedPermission.CREATOR);
this.permissionGroups = in.createTypedArrayList(ParsedPermissionGroup.CREATOR);
this.instrumentations = in.createTypedArrayList(ParsedInstrumentation.CREATOR);
@@ -1241,8 +1251,11 @@
this.hasFragileUserData = in.readBoolean();
this.cantSaveState = in.readBoolean();
this.allowNativeHeapPointerTagging = in.readBoolean();
+ this.dontAutoRevokePermissions = in.readBoolean();
+ this.allowDontAutoRevokePermissions = in.readBoolean();
this.preserveLegacyExternalStorage = in.readBoolean();
this.mimeGroups = (ArraySet<String>) in.readArraySet(boot);
+ this.enableGwpAsan = sForBoolean.unparcel(in);
}
public static final Parcelable.Creator<ParsingPackageImpl> CREATOR =
@@ -1509,8 +1522,8 @@
@NonNull
@Override
- public List<ParsedFeature> getFeatures() {
- return features;
+ public List<ParsedAttribution> getAttributions() {
+ return attributions;
}
@NonNull
@@ -1965,6 +1978,12 @@
}
@Override
+ @Nullable
+ public Boolean isGwpAsanEnabled() {
+ return enableGwpAsan;
+ }
+
+ @Override
public boolean isPartiallyDirectBootAware() {
return partiallyDirectBootAware;
}
@@ -2010,6 +2029,16 @@
}
@Override
+ public boolean isDontAutoRevokePermmissions() {
+ return dontAutoRevokePermissions;
+ }
+
+ @Override
+ public boolean isAllowDontAutoRevokePermmissions() {
+ return allowDontAutoRevokePermissions;
+ }
+
+ @Override
public boolean hasPreserveLegacyExternalStorage() {
return preserveLegacyExternalStorage;
}
@@ -2420,6 +2449,12 @@
}
@Override
+ public ParsingPackageImpl setGwpAsanEnabled(@Nullable Boolean value) {
+ enableGwpAsan = value;
+ return this;
+ }
+
+ @Override
public ParsingPackageImpl setPartiallyDirectBootAware(boolean value) {
partiallyDirectBootAware = value;
return this;
@@ -2474,6 +2509,18 @@
}
@Override
+ public ParsingPackageImpl setDontAutoRevokePermissions(boolean value) {
+ dontAutoRevokePermissions = value;
+ return this;
+ }
+
+ @Override
+ public ParsingPackageImpl setAllowDontAutoRevokePermissions(boolean value) {
+ allowDontAutoRevokePermissions = value;
+ return this;
+ }
+
+ @Override
public ParsingPackageImpl setPreserveLegacyExternalStorage(boolean value) {
preserveLegacyExternalStorage = value;
return this;
diff --git a/core/java/android/content/pm/parsing/ParsingPackageRead.java b/core/java/android/content/pm/parsing/ParsingPackageRead.java
index 048b924..9c13c85 100644
--- a/core/java/android/content/pm/parsing/ParsingPackageRead.java
+++ b/core/java/android/content/pm/parsing/ParsingPackageRead.java
@@ -28,7 +28,7 @@
import android.content.pm.PackageParser;
import android.content.pm.ServiceInfo;
import android.content.pm.parsing.component.ParsedActivity;
-import android.content.pm.parsing.component.ParsedFeature;
+import android.content.pm.parsing.component.ParsedAttribution;
import android.content.pm.parsing.component.ParsedInstrumentation;
import android.content.pm.parsing.component.ParsedIntentInfo;
import android.content.pm.parsing.component.ParsedPermission;
@@ -80,7 +80,7 @@
List<ConfigurationInfo> getConfigPreferences();
@NonNull
- List<ParsedFeature> getFeatures();
+ List<ParsedAttribution> getAttributions();
/**
* @see PackageInfo#featureGroups
@@ -771,6 +771,12 @@
/** @see ApplicationInfo#PRIVATE_FLAG_ALLOW_NATIVE_HEAP_POINTER_TAGGING */
boolean isAllowNativeHeapPointerTagging();
+ /** @see ApplicationInfo#PRIVATE_FLAG2_DONT_AUTO_REVOKE_PERMISSIONS */
+ boolean isDontAutoRevokePermmissions();
+
+ /** @see ApplicationInfo#PRIVATE_FLAG2_ALLOW_DONT_AUTO_REVOKE_PERMISSIONS */
+ boolean isAllowDontAutoRevokePermmissions();
+
boolean hasPreserveLegacyExternalStorage();
/**
@@ -840,6 +846,13 @@
@Nullable
Set<String> getMimeGroups();
+ /**
+ * @see ApplicationInfo#enableGwpAsan
+ * @see R.styleable#AndroidManifest_enableGwpAsan
+ */
+ @Nullable
+ public Boolean isGwpAsanEnabled();
+
// TODO(b/135203078): Hide and enforce going through PackageInfoUtils
ApplicationInfo toAppInfoWithoutState();
}
diff --git a/core/java/android/content/pm/parsing/ParsingPackageUtils.java b/core/java/android/content/pm/parsing/ParsingPackageUtils.java
index b4f2159..e41ed85 100644
--- a/core/java/android/content/pm/parsing/ParsingPackageUtils.java
+++ b/core/java/android/content/pm/parsing/ParsingPackageUtils.java
@@ -40,6 +40,7 @@
import android.content.pm.FeatureGroupInfo;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageInfo;
+import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageParser;
import android.content.pm.PackageParser.PackageParserException;
@@ -48,8 +49,8 @@
import android.content.pm.parsing.component.ComponentParseUtils;
import android.content.pm.parsing.component.ParsedActivity;
import android.content.pm.parsing.component.ParsedActivityUtils;
-import android.content.pm.parsing.component.ParsedFeature;
-import android.content.pm.parsing.component.ParsedFeatureUtils;
+import android.content.pm.parsing.component.ParsedAttribution;
+import android.content.pm.parsing.component.ParsedAttributionUtils;
import android.content.pm.parsing.component.ParsedInstrumentation;
import android.content.pm.parsing.component.ParsedInstrumentationUtils;
import android.content.pm.parsing.component.ParsedIntentInfo;
@@ -672,7 +673,7 @@
);
}
- if (!ParsedFeature.isCombinationValid(pkg.getFeatures())) {
+ if (!ParsedAttribution.isCombinationValid(pkg.getAttributions())) {
return input.error(
INSTALL_PARSE_FAILED_BAD_MANIFEST,
"Combination <feature> tags are not valid"
@@ -707,8 +708,9 @@
return parseOverlay(input, pkg, res, parser);
case PackageParser.TAG_KEY_SETS:
return parseKeySets(input, pkg, res, parser);
- case PackageParser.TAG_FEATURE:
- return parseFeature(input, pkg, res, parser);
+ case "feature": // TODO moltmann: Remove
+ case PackageParser.TAG_ATTRIBUTION:
+ return parseAttribution(input, pkg, res, parser);
case PackageParser.TAG_PERMISSION_GROUP:
return parsePermissionGroup(input, pkg, res, parser);
case PackageParser.TAG_PERMISSION:
@@ -917,13 +919,15 @@
return input.success(pkg);
}
- private static ParseResult<ParsingPackage> parseFeature(ParseInput input, ParsingPackage pkg,
- Resources res, XmlResourceParser parser) throws IOException, XmlPullParserException {
- ParseResult<ParsedFeature> result = ParsedFeatureUtils.parseFeature(res, parser, input);
+ private static ParseResult<ParsingPackage> parseAttribution(ParseInput input,
+ ParsingPackage pkg, Resources res, XmlResourceParser parser)
+ throws IOException, XmlPullParserException {
+ ParseResult<ParsedAttribution> result = ParsedAttributionUtils.parseAttribution(res,
+ parser, input);
if (result.isError()) {
return input.error(result);
}
- return input.success(pkg.addFeature(result.getResult()));
+ return input.success(pkg.addAttribution(result.getResult()));
}
private static ParseResult<ParsingPackage> parsePermissionGroup(ParseInput input,
@@ -1660,6 +1664,11 @@
&& !ClassLoaderFactory.isValidClassLoaderName(classLoaderName)) {
return input.error("Invalid class loader name: " + classLoaderName);
}
+
+ if (sa.hasValue(R.styleable.AndroidManifestApplication_enableGwpAsan)) {
+ pkg.setGwpAsanEnabled(
+ sa.getBoolean(R.styleable.AndroidManifestApplication_enableGwpAsan, false));
+ }
} finally {
sa.recycle();
}
@@ -1811,6 +1820,8 @@
.setUseEmbeddedDex(bool(false, R.styleable.AndroidManifestApplication_useEmbeddedDex, sa))
.setUsesNonSdkApi(bool(false, R.styleable.AndroidManifestApplication_usesNonSdkApi, sa))
.setVmSafeMode(bool(false, R.styleable.AndroidManifestApplication_vmSafeMode, sa))
+ .setDontAutoRevokePermissions(bool(false, R.styleable.AndroidManifestApplication_requestDontAutoRevokePermissions, sa))
+ .setAllowDontAutoRevokePermissions(bool(false, R.styleable.AndroidManifestApplication_allowDontAutoRevokePermissions, sa))
// targetSdkVersion gated
.setAllowAudioPlaybackCapture(bool(targetSdk >= Build.VERSION_CODES.Q, R.styleable.AndroidManifestApplication_allowAudioPlaybackCapture, sa))
.setBaseHardwareAccelerated(bool(targetSdk >= Build.VERSION_CODES.ICE_CREAM_SANDWICH, R.styleable.AndroidManifestApplication_hardwareAccelerated, sa))
diff --git a/core/java/android/content/pm/parsing/component/ParsedActivity.java b/core/java/android/content/pm/parsing/component/ParsedActivity.java
index d32171d..4c93d09 100644
--- a/core/java/android/content/pm/parsing/component/ParsedActivity.java
+++ b/core/java/android/content/pm/parsing/component/ParsedActivity.java
@@ -285,14 +285,8 @@
dest.writeBundle(this.metaData);
if (windowLayout != null) {
- dest.writeBoolean(true);
- dest.writeInt(windowLayout.width);
- dest.writeFloat(windowLayout.widthFraction);
- dest.writeInt(windowLayout.height);
- dest.writeFloat(windowLayout.heightFraction);
- dest.writeInt(windowLayout.gravity);
- dest.writeInt(windowLayout.minWidth);
- dest.writeInt(windowLayout.minHeight);
+ dest.writeInt(1);
+ windowLayout.writeToParcel(dest);
} else {
dest.writeBoolean(false);
}
diff --git a/core/java/android/content/pm/parsing/component/ParsedActivityUtils.java b/core/java/android/content/pm/parsing/component/ParsedActivityUtils.java
index 1dcf262..6e5c51a 100644
--- a/core/java/android/content/pm/parsing/component/ParsedActivityUtils.java
+++ b/core/java/android/content/pm/parsing/component/ParsedActivityUtils.java
@@ -17,16 +17,17 @@
package android.content.pm.parsing.component;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
-
import static android.content.pm.parsing.component.ComponentParseUtils.flag;
import android.annotation.NonNull;
import android.app.ActivityTaskManager;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageParser;
-
import android.content.pm.parsing.ParsingPackage;
+import android.content.pm.parsing.ParsingPackageUtils;
import android.content.pm.parsing.ParsingUtils;
+import android.content.pm.parsing.result.ParseInput;
+import android.content.pm.parsing.result.ParseResult;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
@@ -42,9 +43,6 @@
import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ArrayUtils;
-import android.content.pm.parsing.ParsingPackageUtils;
-import android.content.pm.parsing.result.ParseInput;
-import android.content.pm.parsing.result.ParseResult;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
@@ -379,6 +377,12 @@
}
}
+ ParseResult<ActivityInfo.WindowLayout> layoutResult = resolveWindowLayout(activity, input);
+ if (layoutResult.isError()) {
+ return input.error(layoutResult);
+ }
+ activity.windowLayout = layoutResult.getResult();
+
if (!setExported) {
activity.exported = activity.getIntents().size() > 0;
}
@@ -481,4 +485,35 @@
sw.recycle();
}
}
+
+ /**
+ * Resolves values in {@link ActivityInfo.WindowLayout}.
+ *
+ * <p>{@link ActivityInfo.WindowLayout#windowLayoutAffinity} has a fallback metadata used in
+ * Android R and some variants of pre-R.
+ */
+ private static ParseResult<ActivityInfo.WindowLayout> resolveWindowLayout(
+ ParsedActivity activity, ParseInput input) {
+ // There isn't a metadata for us to fall back. Whatever is in layout is correct.
+ if (activity.metaData == null || !activity.metaData.containsKey(
+ PackageParser.METADATA_ACTIVITY_WINDOW_LAYOUT_AFFINITY)) {
+ return input.success(activity.windowLayout);
+ }
+
+ // Layout already specifies a value. We should just use that one.
+ if (activity.windowLayout != null && activity.windowLayout.windowLayoutAffinity != null) {
+ return input.success(activity.windowLayout);
+ }
+
+ String windowLayoutAffinity = activity.metaData.getString(
+ PackageParser.METADATA_ACTIVITY_WINDOW_LAYOUT_AFFINITY);
+ ActivityInfo.WindowLayout layout = activity.windowLayout;
+ if (layout == null) {
+ layout = new ActivityInfo.WindowLayout(-1 /* width */, -1 /* widthFraction */,
+ -1 /* height */, -1 /* heightFraction */, Gravity.NO_GRAVITY,
+ -1 /* minWidth */, -1 /* minHeight */);
+ }
+ layout.windowLayoutAffinity = windowLayoutAffinity;
+ return input.success(layout);
+ }
}
diff --git a/core/java/android/content/pm/parsing/component/ParsedAttribution.java b/core/java/android/content/pm/parsing/component/ParsedAttribution.java
new file mode 100644
index 0000000..02b3c7d
--- /dev/null
+++ b/core/java/android/content/pm/parsing/component/ParsedAttribution.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2020 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.content.pm.parsing.component;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.StringRes;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.ArraySet;
+
+import com.android.internal.util.DataClass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A {@link android.R.styleable#AndroidManifestAttribution <attribution>} tag parsed from the
+ * manifest.
+ *
+ * @hide
+ */
+@DataClass(genAidl = false)
+public class ParsedAttribution implements Parcelable {
+ /** Maximum length of attribution tag */
+ public static final int MAX_ATTRIBUTION_TAG_LEN = 50;
+
+ /** Maximum amount of attributions per package */
+ private static final int MAX_NUM_ATTRIBUTIONS = 1000;
+
+ /** Tag of the attribution */
+ public final @NonNull String tag;
+
+ /** User visible label fo the attribution */
+ public final @StringRes int label;
+
+ /** Ids of previously declared attributions this attribution inherits from */
+ public final @NonNull List<String> inheritFrom;
+
+ /**
+ * @return Is this set of attributions a valid combination for a single package?
+ */
+ public static boolean isCombinationValid(@Nullable List<ParsedAttribution> attributions) {
+ if (attributions == null) {
+ return true;
+ }
+
+ ArraySet<String> attributionTags = new ArraySet<>(attributions.size());
+ ArraySet<String> inheritFromAttributionTags = new ArraySet<>();
+
+ int numAttributions = attributions.size();
+ if (numAttributions > MAX_NUM_ATTRIBUTIONS) {
+ return false;
+ }
+
+ for (int attributionNum = 0; attributionNum < numAttributions; attributionNum++) {
+ boolean wasAdded = attributionTags.add(attributions.get(attributionNum).tag);
+ if (!wasAdded) {
+ // feature id is not unique
+ return false;
+ }
+ }
+
+ for (int attributionNum = 0; attributionNum < numAttributions; attributionNum++) {
+ ParsedAttribution feature = attributions.get(attributionNum);
+
+ int numInheritFrom = feature.inheritFrom.size();
+ for (int inheritFromNum = 0; inheritFromNum < numInheritFrom; inheritFromNum++) {
+ String inheritFrom = feature.inheritFrom.get(inheritFromNum);
+
+ if (attributionTags.contains(inheritFrom)) {
+ // Cannot inherit from a attribution that is still defined
+ return false;
+ }
+
+ boolean wasAdded = inheritFromAttributionTags.add(inheritFrom);
+ if (!wasAdded) {
+ // inheritFrom is not unique
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+
+
+ // Code below generated by codegen v1.0.14.
+ //
+ // DO NOT MODIFY!
+ // CHECKSTYLE:OFF Generated code
+ //
+ // To regenerate run:
+ // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/content/pm/parsing/component/ParsedAttribution.java
+ //
+ // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
+ // Settings > Editor > Code Style > Formatter Control
+ //@formatter:off
+
+
+ @android.annotation.IntDef(prefix = "MAX_", value = {
+ MAX_ATTRIBUTION_TAG_LEN,
+ MAX_NUM_ATTRIBUTIONS
+ })
+ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE)
+ @DataClass.Generated.Member
+ public @interface Max {}
+
+ @DataClass.Generated.Member
+ public static String maxToString(@Max int value) {
+ switch (value) {
+ case MAX_ATTRIBUTION_TAG_LEN:
+ return "MAX_ATTRIBUTION_TAG_LEN";
+ case MAX_NUM_ATTRIBUTIONS:
+ return "MAX_NUM_ATTRIBUTIONS";
+ default: return Integer.toHexString(value);
+ }
+ }
+
+ /**
+ * Creates a new ParsedAttribution.
+ *
+ * @param tag
+ * Tag of the attribution
+ * @param label
+ * User visible label fo the attribution
+ * @param inheritFrom
+ * Ids of previously declared attributions this attribution inherits from
+ */
+ @DataClass.Generated.Member
+ public ParsedAttribution(
+ @NonNull String tag,
+ @StringRes int label,
+ @NonNull List<String> inheritFrom) {
+ this.tag = tag;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, tag);
+ this.label = label;
+ com.android.internal.util.AnnotationValidations.validate(
+ StringRes.class, null, label);
+ this.inheritFrom = inheritFrom;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, inheritFrom);
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ // You can override field parcelling by defining methods like:
+ // void parcelFieldName(Parcel dest, int flags) { ... }
+
+ dest.writeString(tag);
+ dest.writeInt(label);
+ dest.writeStringList(inheritFrom);
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public int describeContents() { return 0; }
+
+ /** @hide */
+ @SuppressWarnings({"unchecked", "RedundantCast"})
+ @DataClass.Generated.Member
+ protected ParsedAttribution(@NonNull Parcel in) {
+ // You can override field unparcelling by defining methods like:
+ // static FieldType unparcelFieldName(Parcel in) { ... }
+
+ String _tag = in.readString();
+ int _label = in.readInt();
+ List<String> _inheritFrom = new ArrayList<>();
+ in.readStringList(_inheritFrom);
+
+ this.tag = _tag;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, tag);
+ this.label = _label;
+ com.android.internal.util.AnnotationValidations.validate(
+ StringRes.class, null, label);
+ this.inheritFrom = _inheritFrom;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, inheritFrom);
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ @DataClass.Generated.Member
+ public static final @NonNull Parcelable.Creator<ParsedAttribution> CREATOR
+ = new Parcelable.Creator<ParsedAttribution>() {
+ @Override
+ public ParsedAttribution[] newArray(int size) {
+ return new ParsedAttribution[size];
+ }
+
+ @Override
+ public ParsedAttribution createFromParcel(@NonNull Parcel in) {
+ return new ParsedAttribution(in);
+ }
+ };
+
+ @DataClass.Generated(
+ time = 1583436566499L,
+ codegenVersion = "1.0.14",
+ sourceFile = "frameworks/base/core/java/android/content/pm/parsing/component/ParsedAttribution.java",
+ inputSignatures = "public static final int MAX_ATTRIBUTION_TAG_LEN\nprivate static final int MAX_NUM_ATTRIBUTIONS\npublic final @android.annotation.NonNull java.lang.String tag\npublic final @android.annotation.StringRes int label\npublic final @android.annotation.NonNull java.util.List<java.lang.String> inheritFrom\npublic static boolean isCombinationValid(java.util.List<android.content.pm.parsing.component.ParsedAttribution>)\nclass ParsedAttribution extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genAidl=false)")
+ @Deprecated
+ private void __metadata() {}
+
+
+ //@formatter:on
+ // End of generated code
+
+}
diff --git a/core/java/android/content/pm/parsing/component/ParsedFeatureUtils.java b/core/java/android/content/pm/parsing/component/ParsedAttributionUtils.java
similarity index 63%
rename from core/java/android/content/pm/parsing/component/ParsedFeatureUtils.java
rename to core/java/android/content/pm/parsing/component/ParsedAttributionUtils.java
index fb52801..c4b1a0e 100644
--- a/core/java/android/content/pm/parsing/component/ParsedFeatureUtils.java
+++ b/core/java/android/content/pm/parsing/component/ParsedAttributionUtils.java
@@ -34,34 +34,40 @@
import java.util.List;
/** @hide */
-public class ParsedFeatureUtils {
+public class ParsedAttributionUtils {
@NonNull
- public static ParseResult<ParsedFeature> parseFeature(Resources res, XmlResourceParser parser,
- ParseInput input) throws IOException, XmlPullParserException {
- String featureId;
+ public static ParseResult<ParsedAttribution> parseAttribution(Resources res,
+ XmlResourceParser parser, ParseInput input)
+ throws IOException, XmlPullParserException {
+ String attributionTag;
int label;
List<String> inheritFrom = null;
- TypedArray sa = res.obtainAttributes(parser, R.styleable.AndroidManifestFeature);
+ TypedArray sa = res.obtainAttributes(parser, R.styleable.AndroidManifestAttribution);
if (sa == null) {
- return input.error("<feature> could not be parsed");
+ return input.error("<attribution> could not be parsed");
}
try {
- featureId = sa.getNonConfigurationString(R.styleable.AndroidManifestFeature_featureId,
- 0);
- if (featureId == null) {
- return input.error("<featureId> does not specify android:featureId");
+ attributionTag = sa.getNonConfigurationString(
+ R.styleable.AndroidManifestAttribution_tag, 0);
+ if (attributionTag == null) {
+ // TODO moltmann: Remove handling of featureId
+ attributionTag = sa.getNonConfigurationString(
+ R.styleable.AndroidManifestAttribution_featureId, 0);
+ if (attributionTag == null) {
+ return input.error("<attribution> does not specify android:tag");
+ }
}
- if (featureId.length() > ParsedFeature.MAX_FEATURE_ID_LEN) {
- return input.error("<featureId> is too long. Max length is "
- + ParsedFeature.MAX_FEATURE_ID_LEN);
+ if (attributionTag.length() > ParsedAttribution.MAX_ATTRIBUTION_TAG_LEN) {
+ return input.error("android:tag is too long. Max length is "
+ + ParsedAttribution.MAX_ATTRIBUTION_TAG_LEN);
}
- label = sa.getResourceId(R.styleable.AndroidManifestFeature_label, 0);
+ label = sa.getResourceId(R.styleable.AndroidManifestAttribution_label, 0);
if (label == Resources.ID_NULL) {
- return input.error("<featureId> does not specify android:label");
+ return input.error("<attribution> does not specify android:label");
}
} finally {
sa.recycle();
@@ -77,14 +83,15 @@
String tagName = parser.getName();
if (tagName.equals("inherit-from")) {
- sa = res.obtainAttributes(parser, R.styleable.AndroidManifestFeatureInheritFrom);
+ sa = res.obtainAttributes(parser,
+ R.styleable.AndroidManifestAttributionInheritFrom);
if (sa == null) {
return input.error("<inherit-from> could not be parsed");
}
try {
String inheritFromId = sa.getNonConfigurationString(
- R.styleable.AndroidManifestFeatureInheritFrom_featureId,0);
+ R.styleable.AndroidManifestAttributionInheritFrom_tag, 0);
if (inheritFrom == null) {
inheritFrom = new ArrayList<>();
@@ -94,7 +101,7 @@
sa.recycle();
}
} else {
- return input.error("Bad element under <feature>: " + tagName);
+ return input.error("Bad element under <attribution>: " + tagName);
}
}
@@ -104,6 +111,6 @@
((ArrayList) inheritFrom).trimToSize();
}
- return input.success(new ParsedFeature(featureId, label, inheritFrom));
+ return input.success(new ParsedAttribution(attributionTag, label, inheritFrom));
}
}
diff --git a/core/java/android/content/pm/parsing/component/ParsedFeature.java b/core/java/android/content/pm/parsing/component/ParsedFeature.java
deleted file mode 100644
index b8a9098..0000000
--- a/core/java/android/content/pm/parsing/component/ParsedFeature.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2020 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.content.pm.parsing.component;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.StringRes;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.ArraySet;
-
-import com.android.internal.util.DataClass;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A {@link android.R.styleable#AndroidManifestFeature <feature>} tag parsed from the
- * manifest.
- *
- * @hide
- */
-@DataClass(genAidl = false)
-public class ParsedFeature implements Parcelable {
- /** Maximum length of featureId */
- public static final int MAX_FEATURE_ID_LEN = 50;
-
- /** Maximum amount of features per package */
- private static final int MAX_NUM_FEATURES = 1000;
-
- /** Id of the feature */
- public final @NonNull String id;
-
- /** User visible label fo the feature */
- public final @StringRes int label;
-
- /** Ids of previously declared features this feature inherits from */
- public final @NonNull List<String> inheritFrom;
-
- /**
- * @return Is this set of features a valid combination for a single package?
- */
- public static boolean isCombinationValid(@Nullable List<ParsedFeature> features) {
- if (features == null) {
- return true;
- }
-
- ArraySet<String> featureIds = new ArraySet<>(features.size());
- ArraySet<String> inheritFromFeatureIds = new ArraySet<>();
-
- int numFeatures = features.size();
- if (numFeatures > MAX_NUM_FEATURES) {
- return false;
- }
-
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- boolean wasAdded = featureIds.add(features.get(featureNum).id);
- if (!wasAdded) {
- // feature id is not unique
- return false;
- }
- }
-
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- ParsedFeature feature = features.get(featureNum);
-
- int numInheritFrom = feature.inheritFrom.size();
- for (int inheritFromNum = 0; inheritFromNum < numInheritFrom; inheritFromNum++) {
- String inheritFrom = feature.inheritFrom.get(inheritFromNum);
-
- if (featureIds.contains(inheritFrom)) {
- // Cannot inherit from a feature that is still defined
- return false;
- }
-
- boolean wasAdded = inheritFromFeatureIds.add(inheritFrom);
- if (!wasAdded) {
- // inheritFrom is not unique
- return false;
- }
- }
- }
-
- return true;
- }
-
-
-
- // Code below generated by codegen v1.0.14.
- //
- // DO NOT MODIFY!
- // CHECKSTYLE:OFF Generated code
- //
- // To regenerate run:
- // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/content/pm/parsing/component/ParsedFeature.java
- //
- // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
- // Settings > Editor > Code Style > Formatter Control
- //@formatter:off
-
-
- @android.annotation.IntDef(prefix = "MAX_", value = {
- MAX_FEATURE_ID_LEN,
- MAX_NUM_FEATURES
- })
- @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE)
- @DataClass.Generated.Member
- public @interface Max {}
-
- @DataClass.Generated.Member
- public static String maxToString(@Max int value) {
- switch (value) {
- case MAX_FEATURE_ID_LEN:
- return "MAX_FEATURE_ID_LEN";
- case MAX_NUM_FEATURES:
- return "MAX_NUM_FEATURES";
- default: return Integer.toHexString(value);
- }
- }
-
- /**
- * Creates a new ParsedFeature.
- *
- * @param id
- * Id of the feature
- * @param label
- * User visible label fo the feature
- * @param inheritFrom
- * Ids of previously declared features this feature inherits from
- */
- @DataClass.Generated.Member
- public ParsedFeature(
- @NonNull String id,
- @StringRes int label,
- @NonNull List<String> inheritFrom) {
- this.id = id;
- com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, id);
- this.label = label;
- com.android.internal.util.AnnotationValidations.validate(
- StringRes.class, null, label);
- this.inheritFrom = inheritFrom;
- com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, inheritFrom);
-
- // onConstructed(); // You can define this method to get a callback
- }
-
- @Override
- @DataClass.Generated.Member
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- // You can override field parcelling by defining methods like:
- // void parcelFieldName(Parcel dest, int flags) { ... }
-
- dest.writeString(id);
- dest.writeInt(label);
- dest.writeStringList(inheritFrom);
- }
-
- @Override
- @DataClass.Generated.Member
- public int describeContents() { return 0; }
-
- /** @hide */
- @SuppressWarnings({"unchecked", "RedundantCast"})
- @DataClass.Generated.Member
- protected ParsedFeature(@NonNull Parcel in) {
- // You can override field unparcelling by defining methods like:
- // static FieldType unparcelFieldName(Parcel in) { ... }
-
- String _id = in.readString();
- int _label = in.readInt();
- List<String> _inheritFrom = new ArrayList<>();
- in.readStringList(_inheritFrom);
-
- this.id = _id;
- com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, id);
- this.label = _label;
- com.android.internal.util.AnnotationValidations.validate(
- StringRes.class, null, label);
- this.inheritFrom = _inheritFrom;
- com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, inheritFrom);
-
- // onConstructed(); // You can define this method to get a callback
- }
-
- @DataClass.Generated.Member
- public static final @NonNull Parcelable.Creator<ParsedFeature> CREATOR
- = new Parcelable.Creator<ParsedFeature>() {
- @Override
- public ParsedFeature[] newArray(int size) {
- return new ParsedFeature[size];
- }
-
- @Override
- public ParsedFeature createFromParcel(@NonNull Parcel in) {
- return new ParsedFeature(in);
- }
- };
-
- @DataClass.Generated(
- time = 1581379861853L,
- codegenVersion = "1.0.14",
- sourceFile = "frameworks/base/core/java/android/content/pm/parsing/component/ParsedFeature.java",
- inputSignatures = "public static final int MAX_FEATURE_ID_LEN\nprivate static final int MAX_NUM_FEATURES\npublic final @android.annotation.NonNull java.lang.String id\npublic final @android.annotation.StringRes int label\npublic final @android.annotation.NonNull java.util.List<java.lang.String> inheritFrom\npublic static boolean isCombinationValid(java.util.List<android.content.pm.parsing.component.ParsedFeature>)\nclass ParsedFeature extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genAidl=false)")
- @Deprecated
- private void __metadata() {}
-
-
- //@formatter:on
- // End of generated code
-
-}
diff --git a/core/java/android/content/pm/parsing/component/ParsedProcess.java b/core/java/android/content/pm/parsing/component/ParsedProcess.java
index da7bf98..3b6020a 100644
--- a/core/java/android/content/pm/parsing/component/ParsedProcess.java
+++ b/core/java/android/content/pm/parsing/component/ParsedProcess.java
@@ -41,6 +41,9 @@
@DataClass.ParcelWith(Parcelling.BuiltIn.ForInternedStringSet.class)
protected Set<String> deniedPermissions = emptySet();
+ @Nullable
+ protected Boolean enableGwpAsan = null;
+
public ParsedProcess() {
}
@@ -71,13 +74,15 @@
@DataClass.Generated.Member
public ParsedProcess(
@NonNull String name,
- @NonNull Set<String> deniedPermissions) {
+ @NonNull Set<String> deniedPermissions,
+ @Nullable Boolean enableGwpAsan) {
this.name = name;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, name);
this.deniedPermissions = deniedPermissions;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, deniedPermissions);
+ this.enableGwpAsan = enableGwpAsan;
// onConstructed(); // You can define this method to get a callback
}
@@ -93,6 +98,11 @@
}
@DataClass.Generated.Member
+ public @Nullable Boolean getEnableGwpAsan() {
+ return enableGwpAsan;
+ }
+
+ @DataClass.Generated.Member
static Parcelling<Set<String>> sParcellingForDeniedPermissions =
Parcelling.Cache.get(
Parcelling.BuiltIn.ForInternedStringSet.class);
@@ -109,8 +119,12 @@
// You can override field parcelling by defining methods like:
// void parcelFieldName(Parcel dest, int flags) { ... }
+ byte flg = 0;
+ if (enableGwpAsan != null) flg |= 0x4;
+ dest.writeByte(flg);
dest.writeString(name);
sParcellingForDeniedPermissions.parcel(deniedPermissions, dest, flags);
+ if (enableGwpAsan != null) dest.writeBoolean(enableGwpAsan);
}
@Override
@@ -124,8 +138,10 @@
// You can override field unparcelling by defining methods like:
// static FieldType unparcelFieldName(Parcel in) { ... }
+ byte flg = in.readByte();
String _name = in.readString();
Set<String> _deniedPermissions = sParcellingForDeniedPermissions.unparcel(in);
+ Boolean _enableGwpAsan = (flg & 0x4) == 0 ? null : (Boolean) in.readBoolean();
this.name = _name;
com.android.internal.util.AnnotationValidations.validate(
@@ -133,6 +149,7 @@
this.deniedPermissions = _deniedPermissions;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, deniedPermissions);
+ this.enableGwpAsan = _enableGwpAsan;
// onConstructed(); // You can define this method to get a callback
}
@@ -152,10 +169,10 @@
};
@DataClass.Generated(
- time = 1581452315946L,
+ time = 1582589960479L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/content/pm/parsing/component/ParsedProcess.java",
- inputSignatures = "protected @android.annotation.NonNull java.lang.String name\nprotected @android.annotation.NonNull @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInternedStringSet.class) java.util.Set<java.lang.String> deniedPermissions\npublic void addStateFrom(android.content.pm.parsing.component.ParsedProcess)\nclass ParsedProcess extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genGetters=true, genSetters=false, genParcelable=true, genAidl=false, genBuilder=false)")
+ inputSignatures = "protected @android.annotation.NonNull java.lang.String name\nprotected @android.annotation.NonNull @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForInternedStringSet.class) java.util.Set<java.lang.String> deniedPermissions\nprotected @android.annotation.Nullable java.lang.Boolean enableGwpAsan\npublic void addStateFrom(android.content.pm.parsing.component.ParsedProcess)\nclass ParsedProcess extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genGetters=true, genSetters=false, genParcelable=true, genAidl=false, genBuilder=false)")
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/content/pm/parsing/component/ParsedProcessUtils.java b/core/java/android/content/pm/parsing/component/ParsedProcessUtils.java
index 4825066..3820790 100644
--- a/core/java/android/content/pm/parsing/component/ParsedProcessUtils.java
+++ b/core/java/android/content/pm/parsing/component/ParsedProcessUtils.java
@@ -103,6 +103,11 @@
if (proc.name == null || proc.name.length() <= 0) {
return input.error("<process> does not specify android:process");
}
+
+ if (sa.hasValue(R.styleable.AndroidManifestProcess_enableGwpAsan)) {
+ proc.enableGwpAsan =
+ sa.getBoolean(R.styleable.AndroidManifestProcess_enableGwpAsan, false);
+ }
} finally {
sa.recycle();
}
diff --git a/core/java/android/database/ContentObserver.java b/core/java/android/database/ContentObserver.java
index ede264d..578d53b 100644
--- a/core/java/android/database/ContentObserver.java
+++ b/core/java/android/database/ContentObserver.java
@@ -19,6 +19,9 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
+import android.app.compat.CompatChanges;
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledAfter;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentResolver.NotifyFlags;
import android.net.Uri;
@@ -26,12 +29,26 @@
import android.os.UserHandle;
import java.util.Arrays;
+import java.util.Collection;
/**
* Receives call backs for changes to content.
* Must be implemented by objects which are added to a {@link ContentObservable}.
*/
public abstract class ContentObserver {
+ /**
+ * Starting in {@link android.os.Build.VERSION_CODES#R}, there is a new
+ * public API overload {@link #onChange(boolean, Uri, int)} that delivers a
+ * {@code int flags} argument.
+ * <p>
+ * Some apps may be relying on a previous hidden API that delivered a
+ * {@code int userId} argument, and this change is used to control delivery
+ * of the new {@code int flags} argument in its place.
+ */
+ @ChangeId
+ @EnabledAfter(targetSdkVersion=android.os.Build.VERSION_CODES.Q)
+ private static final long ADD_CONTENT_OBSERVER_FLAGS = 150939131L;
+
private final Object mLock = new Object();
private Transport mTransport; // guarded by mLock
@@ -164,16 +181,26 @@
* @param uris The Uris of the changed content.
* @param flags Flags indicating details about this change.
*/
- public void onChange(boolean selfChange, @NonNull Iterable<Uri> uris, @NotifyFlags int flags) {
+ public void onChange(boolean selfChange, @NonNull Collection<Uri> uris,
+ @NotifyFlags int flags) {
for (Uri uri : uris) {
onChange(selfChange, uri, flags);
}
}
/** @hide */
- public void onChange(boolean selfChange, @NonNull Iterable<Uri> uris, @NotifyFlags int flags,
- @UserIdInt int userId) {
- onChange(selfChange, uris, flags);
+ public void onChange(boolean selfChange, @NonNull Collection<Uri> uris,
+ @NotifyFlags int flags, @UserIdInt int userId) {
+ // There are dozens of people relying on the hidden API inside the
+ // system UID, so hard-code the old behavior for all of them; for
+ // everyone else we gate based on a specific change
+ if (!CompatChanges.isChangeEnabled(ADD_CONTENT_OBSERVER_FLAGS)
+ || android.os.Process.myUid() == android.os.Process.SYSTEM_UID) {
+ // Deliver userId through argument to preserve hidden API behavior
+ onChange(selfChange, uris, userId);
+ } else {
+ onChange(selfChange, uris, flags);
+ }
}
/**
@@ -186,7 +213,7 @@
*
* @deprecated Callers should migrate towards using a richer overload that
* provides more details about the change, such as
- * {@link #dispatchChange(boolean, Iterable, int)}.
+ * {@link #dispatchChange(boolean, Collection, int)}.
*/
@Deprecated
public final void dispatchChange(boolean selfChange) {
@@ -206,7 +233,7 @@
* @param uri The Uri of the changed content.
*/
public final void dispatchChange(boolean selfChange, @Nullable Uri uri) {
- dispatchChange(selfChange, Arrays.asList(uri), 0, UserHandle.getCallingUserId());
+ dispatchChange(selfChange, uri, 0);
}
/**
@@ -224,7 +251,7 @@
*/
public final void dispatchChange(boolean selfChange, @Nullable Uri uri,
@NotifyFlags int flags) {
- dispatchChange(selfChange, Arrays.asList(uri), flags, UserHandle.getCallingUserId());
+ dispatchChange(selfChange, Arrays.asList(uri), flags);
}
/**
@@ -240,13 +267,13 @@
* @param uris The Uri of the changed content.
* @param flags Flags indicating details about this change.
*/
- public final void dispatchChange(boolean selfChange, @NonNull Iterable<Uri> uris,
+ public final void dispatchChange(boolean selfChange, @NonNull Collection<Uri> uris,
@NotifyFlags int flags) {
dispatchChange(selfChange, uris, flags, UserHandle.getCallingUserId());
}
/** @hide */
- public final void dispatchChange(boolean selfChange, @NonNull Iterable<Uri> uris,
+ public final void dispatchChange(boolean selfChange, @NonNull Collection<Uri> uris,
@NotifyFlags int flags, @UserIdInt int userId) {
if (mHandler == null) {
onChange(selfChange, uris, flags, userId);
diff --git a/core/java/android/database/CursorToBulkCursorAdaptor.java b/core/java/android/database/CursorToBulkCursorAdaptor.java
index 1855dd2..ce86807 100644
--- a/core/java/android/database/CursorToBulkCursorAdaptor.java
+++ b/core/java/android/database/CursorToBulkCursorAdaptor.java
@@ -20,10 +20,12 @@
import android.annotation.UserIdInt;
import android.content.ContentResolver.NotifyFlags;
import android.net.Uri;
-import android.os.*;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
import java.util.ArrayList;
-
+import java.util.Collection;
/**
* Wraps a BulkCursor around an existing Cursor making it remotable.
@@ -81,7 +83,7 @@
}
@Override
- public void onChange(boolean selfChange, @NonNull Iterable<Uri> uris,
+ public void onChange(boolean selfChange, @NonNull Collection<Uri> uris,
@NotifyFlags int flags, @UserIdInt int userId) {
// Since we deliver changes from the most-specific to least-specific
// overloads, we only need to redirect from the most-specific local
diff --git a/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl b/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl
index 61310f3..8bcaf82 100644
--- a/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl
+++ b/core/java/android/hardware/biometrics/IBiometricServiceReceiverInternal.aidl
@@ -35,7 +35,7 @@
// Notifies that a biometric has been acquired.
void onAcquired(int acquiredInfo, String message);
// Notifies that the SystemUI dialog has been dismissed.
- void onDialogDismissed(int reason);
+ void onDialogDismissed(int reason, in byte[] credentialAttestation);
// Notifies that the user has pressed the "try again" button on SystemUI
void onTryAgainPressed();
// Notifies that the user has pressed the "use password" button on SystemUI
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index b3a1ee2..7e72b73d 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -2884,12 +2884,12 @@
* generated according to the documented
* {@link android.hardware.camera2.CameraDevice#createCaptureSession guideline} for each device
* which has its Id present in the set returned by
- * {@link android.hardware.camera2.CameraManager#getConcurrentStreamingCameraIds}.
+ * {@link android.hardware.camera2.CameraManager#getConcurrentCameraIds}.
* Clients can use the array as a quick reference to find an appropriate camera stream
* combination.
* The mandatory stream combination array will be {@code null} in case the device is not a part
* of at least one set of combinations returned by
- * {@link android.hardware.camera2.CameraManager#getConcurrentStreamingCameraIds}.</p>
+ * {@link android.hardware.camera2.CameraManager#getConcurrentCameraIds}.</p>
* <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p>
*/
@PublicKey
diff --git a/core/java/android/hardware/camera2/CameraDevice.java b/core/java/android/hardware/camera2/CameraDevice.java
index cc0c1a30..30ee326 100644
--- a/core/java/android/hardware/camera2/CameraDevice.java
+++ b/core/java/android/hardware/camera2/CameraDevice.java
@@ -681,7 +681,7 @@
* </p>
*
*<p>Devices capable of streaming concurrently with other devices as described by
- * {@link android.hardware.camera2.CameraManager#getConcurrentStreamingCameraIds} have the
+ * {@link android.hardware.camera2.CameraManager#getConcurrentCameraIds} have the
* following guaranteed streams (when streaming concurrently with other devices)</p>
*
* <table>
diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java
index 85ef4a3..e81c649 100644
--- a/core/java/android/hardware/camera2/CameraManager.java
+++ b/core/java/android/hardware/camera2/CameraManager.java
@@ -160,8 +160,8 @@
* @throws CameraAccessException if the camera device has been disconnected.
*/
@NonNull
- public Set<Set<String>> getConcurrentStreamingCameraIds() throws CameraAccessException {
- return CameraManagerGlobal.get().getConcurrentStreamingCameraIds();
+ public Set<Set<String>> getConcurrentCameraIds() throws CameraAccessException {
+ return CameraManagerGlobal.get().getConcurrentCameraIds();
}
/**
@@ -189,11 +189,11 @@
*
* @return {@code true} if the given combination of session configurations and corresponding
* camera ids are concurrently supported by the camera sub-system,
- * {@code false} otherwise.
+ * {@code false} otherwise OR if the set of camera devices provided is not a subset of
+ * those returned by {@link #getConcurrentCameraIds}.
*
- * @throws IllegalArgumentException if the set of camera devices provided is not a subset of
- * those returned by getConcurrentStreamingCameraIds()
* @throws CameraAccessException if one of the camera devices queried is no longer connected.
+ *
*/
@RequiresPermission(android.Manifest.permission.CAMERA)
public boolean isConcurrentSessionConfigurationSupported(
@@ -486,7 +486,7 @@
"Camera service is currently unavailable");
}
cameraUser = cameraService.connectDevice(callbacks, cameraId,
- mContext.getOpPackageName(), mContext.getFeatureId(), uid);
+ mContext.getOpPackageName(), mContext.getAttributionTag(), uid);
} else {
// Use legacy camera implementation for HAL1 devices
int id;
@@ -846,6 +846,33 @@
@NonNull String physicalCameraId) {
// default empty implementation
}
+
+ /**
+ * A camera device has been opened by an application.
+ *
+ * <p>The default implementation of this method does nothing.</p>
+ *
+ * @param cameraId The unique identifier of the new camera.
+ * @param packageId The package Id of the application opening the camera.
+ *
+ * @see #onCameraClosed
+ */
+ /** @hide */
+ public void onCameraOpened(@NonNull String cameraId, @NonNull String packageId) {
+ // default empty implementation
+ }
+
+ /**
+ * A previously-opened camera has been closed.
+ *
+ * <p>The default implementation of this method does nothing.</p>
+ *
+ * @param cameraId The unique identifier of the closed camera.
+ */
+ /** @hide */
+ public void onCameraClosed(@NonNull String cameraId) {
+ // default empty implementation
+ }
}
/**
@@ -1156,7 +1183,7 @@
try {
ConcurrentCameraIdCombination[] cameraIdCombinations =
- cameraService.getConcurrentStreamingCameraIds();
+ cameraService.getConcurrentCameraIds();
for (ConcurrentCameraIdCombination comb : cameraIdCombinations) {
mConcurrentCameraIdCombinations.add(comb.getConcurrentCameraIdCombination());
}
@@ -1276,6 +1303,12 @@
}
@Override
public void onCameraAccessPrioritiesChanged() {
+ }
+ @Override
+ public void onCameraOpened(String id, String clientPackageId) {
+ }
+ @Override
+ public void onCameraClosed(String id) {
}};
String[] cameraIds = null;
@@ -1339,7 +1372,7 @@
return cameraIds;
}
- public @NonNull Set<Set<String>> getConcurrentStreamingCameraIds() {
+ public @NonNull Set<Set<String>> getConcurrentCameraIds() {
Set<Set<String>> concurrentStreamingCameraIds = null;
synchronized (mLock) {
// Try to make sure we have an up-to-date list of concurrent camera devices.
@@ -1365,7 +1398,7 @@
synchronized (mLock) {
// Go through all the elements and check if the camera ids are valid at least /
- // belong to one of the combinations returned by getConcurrentStreamingCameraIds()
+ // belong to one of the combinations returned by getConcurrentCameraIds()
boolean subsetFound = false;
for (Set<String> combination : mConcurrentCameraIdCombinations) {
if (combination.containsAll(cameraIdsAndSessionConfigurations.keySet())) {
@@ -1373,9 +1406,9 @@
}
}
if (!subsetFound) {
- throw new IllegalArgumentException(
- "The set of camera ids provided is not a subset of"
- + "getConcurrentStreamingCameraIds");
+ Log.v(TAG, "isConcurrentSessionConfigurationSupported called with a subset of"
+ + "camera ids not returned by getConcurrentCameraIds");
+ return false;
}
CameraIdAndSessionConfiguration [] cameraIdsAndConfigs =
new CameraIdAndSessionConfiguration[size];
@@ -1403,10 +1436,10 @@
/**
* Helper function to find out if a camera id is in the set of combinations returned by
- * getConcurrentStreamingCameraIds()
+ * getConcurrentCameraIds()
* @param cameraId the unique identifier of the camera device to query
* @return Whether the camera device was found in the set of combinations returned by
- * getConcurrentStreamingCameraIds
+ * getConcurrentCameraIds
*/
public boolean cameraIdHasConcurrentStreamsLocked(String cameraId) {
if (!mDeviceStatus.containsKey(cameraId)) {
@@ -1503,6 +1536,38 @@
}
}
+ private void postSingleCameraOpenedUpdate(final AvailabilityCallback callback,
+ final Executor executor, final String id, final String packageId) {
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ executor.execute(
+ new Runnable() {
+ @Override
+ public void run() {
+ callback.onCameraOpened(id, packageId);
+ }
+ });
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
+
+ private void postSingleCameraClosedUpdate(final AvailabilityCallback callback,
+ final Executor executor, final String id) {
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ executor.execute(
+ new Runnable() {
+ @Override
+ public void run() {
+ callback.onCameraClosed(id);
+ }
+ });
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
+
private void postSingleUpdate(final AvailabilityCallback callback, final Executor executor,
final String id, final String physicalId, final int status) {
if (isAvailable(status)) {
@@ -1846,6 +1911,32 @@
}
}
+ @Override
+ public void onCameraOpened(String cameraId, String clientPackageId) {
+ synchronized (mLock) {
+ final int callbackCount = mCallbackMap.size();
+ for (int i = 0; i < callbackCount; i++) {
+ Executor executor = mCallbackMap.valueAt(i);
+ final AvailabilityCallback callback = mCallbackMap.keyAt(i);
+
+ postSingleCameraOpenedUpdate(callback, executor, cameraId, clientPackageId);
+ }
+ }
+ }
+
+ @Override
+ public void onCameraClosed(String cameraId) {
+ synchronized (mLock) {
+ final int callbackCount = mCallbackMap.size();
+ for (int i = 0; i < callbackCount; i++) {
+ Executor executor = mCallbackMap.valueAt(i);
+ final AvailabilityCallback callback = mCallbackMap.keyAt(i);
+
+ postSingleCameraClosedUpdate(callback, executor, cameraId);
+ }
+ }
+ }
+
/**
* Try to connect to camera service after some delay if any client registered camera
* availability callback or torch status callback.
diff --git a/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java b/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java
index f0fab6a..20d9c30 100644
--- a/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java
+++ b/core/java/android/hardware/camera2/params/MandatoryStreamCombination.java
@@ -721,7 +721,7 @@
/**
* Retrieve a list of all available mandatory concurrent stream combinations.
* This method should only be called for devices which are listed in combinations returned
- * by CameraManager.getConcurrentStreamingCameraIds.
+ * by CameraManager.getConcurrentCameraIds.
*
* @return a non-modifiable list of supported mandatory concurrent stream combinations.
*/
diff --git a/core/java/android/hardware/fingerprint/FingerprintManager.java b/core/java/android/hardware/fingerprint/FingerprintManager.java
index 2a71da8..9145142 100644
--- a/core/java/android/hardware/fingerprint/FingerprintManager.java
+++ b/core/java/android/hardware/fingerprint/FingerprintManager.java
@@ -129,10 +129,6 @@
super(mac);
}
- public CryptoObject(@NonNull IdentityCredential credential) {
- super(credential);
- }
-
/**
* Get {@link Signature} object.
* @return {@link Signature} object or null if this doesn't contain one.
@@ -160,8 +156,9 @@
/**
* Get {@link IdentityCredential} object.
* @return {@link IdentityCredential} object or null if this doesn't contain one.
+ * @hide
*/
- public @Nullable IdentityCredential getIdentityCredential() {
+ public IdentityCredential getIdentityCredential() {
return super.getIdentityCredential();
}
}
diff --git a/core/java/android/hardware/lights/Light.java b/core/java/android/hardware/lights/Light.java
index c5cb803..e90b57c 100644
--- a/core/java/android/hardware/lights/Light.java
+++ b/core/java/android/hardware/lights/Light.java
@@ -37,7 +37,8 @@
/**
* Creates a new light with the given data.
*
- * @hide */
+ * @hide
+ */
public Light(int id, int ordinal, int type) {
mId = id;
mOrdinal = ordinal;
@@ -76,8 +77,24 @@
}
};
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof Light) {
+ Light light = (Light) obj;
+ return mId == light.mId && mOrdinal == light.mOrdinal && mType == light.mType;
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return mId;
+ }
+
/**
* Returns the id of the light.
+ *
+ * <p>This is an opaque value used as a unique identifier for the light.
*/
public int getId() {
return mId;
@@ -86,11 +103,9 @@
/**
* Returns the ordinal of the light.
*
- * <p>This represents the physical order of the lights on the device. The exact values are
- * device-dependent, but for example, if there are lights in a row, sorting the Light objects
- * by ordinal should match the order in which they appear on the device. If the device has
- * 4 lights, the ordinals could be [1, 2, 3, 4] or [0, 10, 20, 30] or any other values that
- * have the same sort order.
+ * <p>This is a sort key that represents the physical order of lights on the device with the
+ * same type. In the case of multiple lights arranged in a line, for example, the ordinals
+ * could be [1, 2, 3, 4], or [0, 10, 20, 30], or any other values that have the same sort order.
*/
public int getOrdinal() {
return mOrdinal;
diff --git a/core/java/android/hardware/lights/LightsManager.java b/core/java/android/hardware/lights/LightsManager.java
index 1bc051b..8cd2312 100644
--- a/core/java/android/hardware/lights/LightsManager.java
+++ b/core/java/android/hardware/lights/LightsManager.java
@@ -161,7 +161,7 @@
* @param request the settings for lights that should change
*/
@RequiresPermission(Manifest.permission.CONTROL_DEVICE_LIGHTS)
- public void setLights(@NonNull LightsRequest request) {
+ public void requestLights(@NonNull LightsRequest request) {
Preconditions.checkNotNull(request);
if (!mClosed) {
try {
diff --git a/core/java/android/hardware/lights/LightsRequest.java b/core/java/android/hardware/lights/LightsRequest.java
index a36da4c..5c4fc67 100644
--- a/core/java/android/hardware/lights/LightsRequest.java
+++ b/core/java/android/hardware/lights/LightsRequest.java
@@ -86,7 +86,7 @@
* Create a LightsRequest object used to override lights on the device.
*
* <p>The generated {@link LightsRequest} should be used in
- * {@link LightsManager.Session#setLights(LightsLightsRequest).
+ * {@link LightsManager.Session#requestLights(LightsLightsRequest).
*/
public @NonNull LightsRequest build() {
return new LightsRequest(mChanges);
diff --git a/core/java/android/hardware/soundtrigger/KeyphraseEnrollmentInfo.java b/core/java/android/hardware/soundtrigger/KeyphraseEnrollmentInfo.java
index bf641d7..1aeb76a3 100644
--- a/core/java/android/hardware/soundtrigger/KeyphraseEnrollmentInfo.java
+++ b/core/java/android/hardware/soundtrigger/KeyphraseEnrollmentInfo.java
@@ -28,7 +28,6 @@
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.AttributeSet;
-import android.util.Log;
import android.util.Slog;
import android.util.Xml;
@@ -231,15 +230,7 @@
com.android.internal.R.styleable.VoiceEnrollmentApplication);
keyphraseMetadata = getKeyphraseFromTypedArray(array, packageName, parseErrors);
array.recycle();
- } catch (XmlPullParserException e) {
- String error = "Error parsing keyphrase enrollment meta-data for " + packageName;
- parseErrors.add(error + ": " + e);
- Slog.w(TAG, error, e);
- } catch (IOException e) {
- String error = "Error parsing keyphrase enrollment meta-data for " + packageName;
- parseErrors.add(error + ": " + e);
- Slog.w(TAG, error, e);
- } catch (PackageManager.NameNotFoundException e) {
+ } catch (XmlPullParserException | PackageManager.NameNotFoundException | IOException e) {
String error = "Error parsing keyphrase enrollment meta-data for " + packageName;
parseErrors.add(error + ": " + e);
Slog.w(TAG, error, e);
@@ -390,7 +381,6 @@
* False if not.
*/
public boolean isUidSupportedEnrollmentApplication(int uid) {
- Log.d(TAG, "isUidSupportedEnrollmentApplication: " + toString());
return mEnrollmentApplicationUids.contains(uid);
}
diff --git a/core/java/android/inputmethodservice/SoftInputWindow.java b/core/java/android/inputmethodservice/SoftInputWindow.java
index 0513fee..6efd03c 100644
--- a/core/java/android/inputmethodservice/SoftInputWindow.java
+++ b/core/java/android/inputmethodservice/SoftInputWindow.java
@@ -28,6 +28,7 @@
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
+import android.view.View;
import android.view.WindowManager;
import java.lang.annotation.Retention;
@@ -94,6 +95,13 @@
lp.token = token;
getWindow().setAttributes(lp);
updateWindowState(SoftInputWindowState.TOKEN_SET);
+
+ // As soon as we have a token, make sure the window is added (but not shown) by
+ // setting visibility to INVISIBLE and calling show() on Dialog. Note that
+ // WindowInsetsController.OnControllableInsetsChangedListener relies on the window
+ // being added to function.
+ getWindow().getDecorView().setVisibility(View.INVISIBLE);
+ show();
return;
case SoftInputWindowState.TOKEN_SET:
case SoftInputWindowState.SHOWN_AT_LEAST_ONCE:
diff --git a/core/java/android/net/ConnectivityDiagnosticsManager.java b/core/java/android/net/ConnectivityDiagnosticsManager.java
index d009144..1710ccb 100644
--- a/core/java/android/net/ConnectivityDiagnosticsManager.java
+++ b/core/java/android/net/ConnectivityDiagnosticsManager.java
@@ -368,7 +368,14 @@
/** Class that includes information for a suspected data stall on a specific Network */
public static final class DataStallReport implements Parcelable {
+ /**
+ * Indicates that the Data Stall was detected using DNS events.
+ */
public static final int DETECTION_METHOD_DNS_EVENTS = 1;
+
+ /**
+ * Indicates that the Data Stall was detected using TCP metrics.
+ */
public static final int DETECTION_METHOD_TCP_METRICS = 2;
/** @hide */
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index 38ef814..81735ac 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -53,7 +53,6 @@
import android.os.ResultReceiver;
import android.os.ServiceManager;
import android.os.ServiceSpecificException;
-import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
@@ -808,7 +807,7 @@
private INetworkManagementService mNMService;
private INetworkPolicyManager mNPManager;
- private TetheringManager mTetheringManager;
+ private final TetheringManager mTetheringManager;
/**
* Tests if a given integer represents a valid network type.
@@ -2274,6 +2273,7 @@
public ConnectivityManager(Context context, IConnectivityManager service) {
mContext = Preconditions.checkNotNull(context, "missing context");
mService = Preconditions.checkNotNull(service, "missing IConnectivityManager");
+ mTetheringManager = (TetheringManager) mContext.getSystemService(Context.TETHERING_SERVICE);
sInstance = this;
}
@@ -2347,28 +2347,6 @@
return getInstanceOrNull();
}
- private static final int TETHERING_TIMEOUT_MS = 60_000;
- private final Object mTetheringLock = new Object();
-
- private TetheringManager getTetheringManager() {
- synchronized (mTetheringLock) {
- if (mTetheringManager != null) {
- return mTetheringManager;
- }
- final long before = System.currentTimeMillis();
- while ((mTetheringManager = (TetheringManager) mContext.getSystemService(
- Context.TETHERING_SERVICE)) == null) {
- if (System.currentTimeMillis() - before > TETHERING_TIMEOUT_MS) {
- Log.e(TAG, "Timeout waiting tethering service not ready yet");
- throw new IllegalStateException("No tethering service yet");
- }
- SystemClock.sleep(100);
- }
-
- return mTetheringManager;
- }
- }
-
/**
* Get the set of tetherable, available interfaces. This list is limited by
* device configuration and current interface existence.
@@ -2382,7 +2360,7 @@
@UnsupportedAppUsage
@Deprecated
public String[] getTetherableIfaces() {
- return getTetheringManager().getTetherableIfaces();
+ return mTetheringManager.getTetherableIfaces();
}
/**
@@ -2397,7 +2375,7 @@
@UnsupportedAppUsage
@Deprecated
public String[] getTetheredIfaces() {
- return getTetheringManager().getTetheredIfaces();
+ return mTetheringManager.getTetheredIfaces();
}
/**
@@ -2418,7 +2396,7 @@
@UnsupportedAppUsage
@Deprecated
public String[] getTetheringErroredIfaces() {
- return getTetheringManager().getTetheringErroredIfaces();
+ return mTetheringManager.getTetheringErroredIfaces();
}
/**
@@ -2462,7 +2440,7 @@
@UnsupportedAppUsage
@Deprecated
public int tether(String iface) {
- return getTetheringManager().tether(iface);
+ return mTetheringManager.tether(iface);
}
/**
@@ -2486,7 +2464,7 @@
@UnsupportedAppUsage
@Deprecated
public int untether(String iface) {
- return getTetheringManager().untether(iface);
+ return mTetheringManager.untether(iface);
}
/**
@@ -2512,7 +2490,7 @@
@RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
android.Manifest.permission.WRITE_SETTINGS})
public boolean isTetheringSupported() {
- return getTetheringManager().isTetheringSupported();
+ return mTetheringManager.isTetheringSupported();
}
/**
@@ -2605,7 +2583,7 @@
final TetheringRequest request = new TetheringRequest.Builder(type)
.setSilentProvisioning(!showProvisioningUi).build();
- getTetheringManager().startTethering(request, executor, tetheringCallback);
+ mTetheringManager.startTethering(request, executor, tetheringCallback);
}
/**
@@ -2624,7 +2602,7 @@
@Deprecated
@RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
public void stopTethering(int type) {
- getTetheringManager().stopTethering(type);
+ mTetheringManager.stopTethering(type);
}
/**
@@ -2682,7 +2660,7 @@
synchronized (mTetheringEventCallbacks) {
mTetheringEventCallbacks.put(callback, tetherCallback);
- getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
+ mTetheringManager.registerTetheringEventCallback(executor, tetherCallback);
}
}
@@ -2704,7 +2682,7 @@
synchronized (mTetheringEventCallbacks) {
final TetheringEventCallback tetherCallback =
mTetheringEventCallbacks.remove(callback);
- getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
+ mTetheringManager.unregisterTetheringEventCallback(tetherCallback);
}
}
@@ -2724,7 +2702,7 @@
@UnsupportedAppUsage
@Deprecated
public String[] getTetherableUsbRegexs() {
- return getTetheringManager().getTetherableUsbRegexs();
+ return mTetheringManager.getTetherableUsbRegexs();
}
/**
@@ -2742,7 +2720,7 @@
@UnsupportedAppUsage
@Deprecated
public String[] getTetherableWifiRegexs() {
- return getTetheringManager().getTetherableWifiRegexs();
+ return mTetheringManager.getTetherableWifiRegexs();
}
/**
@@ -2761,7 +2739,7 @@
@UnsupportedAppUsage
@Deprecated
public String[] getTetherableBluetoothRegexs() {
- return getTetheringManager().getTetherableBluetoothRegexs();
+ return mTetheringManager.getTetherableBluetoothRegexs();
}
/**
@@ -2785,7 +2763,7 @@
@UnsupportedAppUsage
@Deprecated
public int setUsbTethering(boolean enable) {
- return getTetheringManager().setUsbTethering(enable);
+ return mTetheringManager.setUsbTethering(enable);
}
/**
@@ -2902,7 +2880,7 @@
@UnsupportedAppUsage
@Deprecated
public int getLastTetherError(String iface) {
- return getTetheringManager().getLastTetherError(iface);
+ return mTetheringManager.getLastTetherError(iface);
}
/** @hide */
@@ -2973,7 +2951,7 @@
}
};
- getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
+ mTetheringManager.requestLatestTetheringEntitlementResult(type, wrappedListener,
showEntitlementUi);
}
@@ -3244,7 +3222,9 @@
/** {@hide} - returns the factory serial number */
@UnsupportedAppUsage
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public int registerNetworkFactory(Messenger messenger, String name) {
try {
return mService.registerNetworkFactory(messenger, name);
@@ -3255,7 +3235,9 @@
/** {@hide} */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public void unregisterNetworkFactory(Messenger messenger) {
try {
mService.unregisterNetworkFactory(messenger);
@@ -3275,7 +3257,9 @@
* @hide
*/
@SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public int registerNetworkProvider(@NonNull NetworkProvider provider) {
if (provider.getProviderId() != NetworkProvider.ID_NONE) {
throw new IllegalStateException("NetworkProviders can only be registered once");
@@ -3298,7 +3282,9 @@
* @hide
*/
@SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
try {
mService.unregisterNetworkProvider(provider.getMessenger());
@@ -3310,7 +3296,9 @@
/** @hide exposed via the NetworkProvider class. */
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
try {
mService.declareNetworkRequestUnfulfillable(request);
@@ -3328,7 +3316,9 @@
* Register a NetworkAgent with ConnectivityService.
* @return Network corresponding to NetworkAgent.
*/
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
NetworkCapabilities nc, int score, NetworkAgentConfig config) {
return registerNetworkAgent(messenger, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
@@ -3339,7 +3329,9 @@
* Register a NetworkAgent with ConnectivityService.
* @return Network corresponding to NetworkAgent.
*/
- @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_FACTORY})
public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
try {
@@ -4469,7 +4461,7 @@
public void factoryReset() {
try {
mService.factoryReset();
- getTetheringManager().stopAllTethering();
+ mTetheringManager.stopAllTethering();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/core/java/android/net/EthernetManager.java b/core/java/android/net/EthernetManager.java
index a3899b7..83b5f63 100644
--- a/core/java/android/net/EthernetManager.java
+++ b/core/java/android/net/EthernetManager.java
@@ -17,6 +17,7 @@
package android.net;
import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
@@ -28,6 +29,7 @@
import java.util.ArrayList;
import java.util.Objects;
+import java.util.concurrent.Executor;
/**
* A class representing the IP configuration of the Ethernet network.
@@ -247,19 +249,24 @@
* interface, the existing interface will be used.
* @param callback A callback to be called once the request has been fulfilled.
*/
+ @RequiresPermission(anyOf = {
+ android.Manifest.permission.NETWORK_STACK,
+ android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
+ })
@NonNull
- public TetheredInterfaceRequest requestTetheredInterface(
- @NonNull TetheredInterfaceCallback callback) {
+ public TetheredInterfaceRequest requestTetheredInterface(@NonNull final Executor executor,
+ @NonNull final TetheredInterfaceCallback callback) {
Objects.requireNonNull(callback, "Callback must be non-null");
+ Objects.requireNonNull(executor, "Executor must be non-null");
final ITetheredInterfaceCallback cbInternal = new ITetheredInterfaceCallback.Stub() {
@Override
public void onAvailable(String iface) {
- callback.onAvailable(iface);
+ executor.execute(() -> callback.onAvailable(iface));
}
@Override
public void onUnavailable() {
- callback.onUnavailable();
+ executor.execute(() -> callback.onUnavailable());
}
};
diff --git a/core/java/android/net/KeepalivePacketData.java b/core/java/android/net/KeepalivePacketData.java
index 2b8b7e6..6c0ba2f 100644
--- a/core/java/android/net/KeepalivePacketData.java
+++ b/core/java/android/net/KeepalivePacketData.java
@@ -22,7 +22,6 @@
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.net.util.IpUtils;
-import android.os.Parcel;
import android.util.Log;
import java.net.InetAddress;
@@ -30,7 +29,6 @@
/**
* Represents the actual packets that are sent by the
* {@link android.net.SocketKeepalive} API.
- *
* @hide
*/
@SystemApi
@@ -54,6 +52,9 @@
/** Packet data. A raw byte string of packet data, not including the link-layer header. */
private final byte[] mPacket;
+ // Note: If you add new fields, please modify the parcelling code in the child classes.
+
+
// This should only be constructed via static factory methods, such as
// nattKeepalivePacket.
/**
@@ -87,21 +88,4 @@
return mPacket.clone();
}
- /** @hide */
- public void writeToParcel(Parcel out, int flags) {
- out.writeString(srcAddress.getHostAddress());
- out.writeString(dstAddress.getHostAddress());
- out.writeInt(srcPort);
- out.writeInt(dstPort);
- out.writeByteArray(mPacket);
- }
-
- /** @hide */
- protected KeepalivePacketData(Parcel in) {
- srcAddress = NetworkUtils.numericToInetAddress(in.readString());
- dstAddress = NetworkUtils.numericToInetAddress(in.readString());
- srcPort = in.readInt();
- dstPort = in.readInt();
- mPacket = in.createByteArray();
- }
}
diff --git a/core/java/android/net/Network.java b/core/java/android/net/Network.java
index c5681cb..6f5471b 100644
--- a/core/java/android/net/Network.java
+++ b/core/java/android/net/Network.java
@@ -61,6 +61,7 @@
public class Network implements Parcelable {
/**
+ * The unique id of the network.
* @hide
*/
@SystemApi
diff --git a/core/java/android/net/NetworkAgent.java b/core/java/android/net/NetworkAgent.java
index 7cc569a..5c754a1 100644
--- a/core/java/android/net/NetworkAgent.java
+++ b/core/java/android/net/NetworkAgent.java
@@ -78,6 +78,7 @@
/**
* The ID of the {@link NetworkProvider} that created this object, or
* {@link NetworkProvider#ID_NONE} if unknown.
+ * @hide
*/
public final int providerId;
@@ -126,7 +127,7 @@
/**
* Sent by the NetworkAgent to ConnectivityService to pass the current
* network score.
- * obj = network score Integer
+ * arg1 = network score int
* @hide
*/
public static final int EVENT_NETWORK_SCORE_CHANGED = BASE + 4;
@@ -584,6 +585,7 @@
*
* @deprecated this is for backward compatibility only.
* @param legacySubtype the legacy subtype.
+ * @hide
*/
@Deprecated
public void setLegacySubtype(final int legacySubtype, @NonNull final String legacySubtypeName) {
@@ -608,6 +610,7 @@
*
* @deprecated this is for backward compatibility only.
* @param extraInfo the ExtraInfo.
+ * @hide
*/
@Deprecated
public void setLegacyExtraInfo(@Nullable final String extraInfo) {
@@ -650,18 +653,7 @@
if (score < 0) {
throw new IllegalArgumentException("Score must be >= 0");
}
- final NetworkScore ns = new NetworkScore();
- ns.putIntExtension(NetworkScore.LEGACY_SCORE, score);
- updateScore(ns);
- }
-
- /**
- * Must be called by the agent when it has a new {@link NetworkScore} for this network.
- * @param ns the new score.
- * @hide TODO: unhide the NetworkScore class, and rename to sendNetworkScore.
- */
- public void updateScore(@NonNull NetworkScore ns) {
- queueOrSendMessage(EVENT_NETWORK_SCORE_CHANGED, new NetworkScore(ns));
+ queueOrSendMessage(EVENT_NETWORK_SCORE_CHANGED, score, 0);
}
/**
@@ -722,6 +714,7 @@
/**
* Called when ConnectivityService request a bandwidth update. The parent factory
* shall try to overwrite this method and produce a bandwidth update if capable.
+ * @hide
*/
public void onBandwidthUpdateRequested() {
pollLceData();
diff --git a/core/java/android/net/NetworkAgentConfig.java b/core/java/android/net/NetworkAgentConfig.java
index 7e2db4a..ca9328a 100644
--- a/core/java/android/net/NetworkAgentConfig.java
+++ b/core/java/android/net/NetworkAgentConfig.java
@@ -108,6 +108,7 @@
/**
*
* @return whether the sign in to network notification is enabled by this configuration.
+ * @hide
*/
public boolean isProvisioningNotificationEnabled() {
return !provisioningNotificationDisabled;
@@ -122,6 +123,7 @@
/**
* @return the subscriber ID, or null if none.
+ * @hide
*/
@Nullable
public String getSubscriberId() {
@@ -138,6 +140,7 @@
/**
* @return whether NAT64 prefix detection is enabled.
+ * @hide
*/
public boolean isNat64DetectionEnabled() {
return !skip464xlat;
@@ -247,6 +250,7 @@
* Sets the subscriber ID for this network.
*
* @return this builder, to facilitate chaining.
+ * @hide
*/
@NonNull
public Builder setSubscriberId(@Nullable String subscriberId) {
@@ -259,6 +263,7 @@
* and reduce idle traffic on networks that are known to be IPv6-only without a NAT64.
*
* @return this builder, to facilitate chaining.
+ * @hide
*/
@NonNull
public Builder disableNat64Detection() {
@@ -271,6 +276,7 @@
* perform its own carrier-specific provisioning procedure.
*
* @return this builder, to facilitate chaining.
+ * @hide
*/
@NonNull
public Builder disableProvisioningNotification() {
diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java
index 83f9980..116e343 100644
--- a/core/java/android/net/NetworkCapabilities.java
+++ b/core/java/android/net/NetworkCapabilities.java
@@ -613,7 +613,6 @@
* @return {@code true} if the network should be restricted.
* @hide
*/
- @SystemApi
public boolean deduceRestrictedCapability() {
// Check if we have any capability that forces the network to be restricted.
final boolean forceRestrictedCapability =
diff --git a/core/java/android/net/NetworkPolicyManager.java b/core/java/android/net/NetworkPolicyManager.java
index 14442a2..1922b6d 100644
--- a/core/java/android/net/NetworkPolicyManager.java
+++ b/core/java/android/net/NetworkPolicyManager.java
@@ -21,7 +21,6 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.app.ActivityManager;
import android.compat.annotation.UnsupportedAppUsage;
@@ -56,7 +55,6 @@
* @hide
*/
@SystemService(Context.NETWORK_POLICY_SERVICE)
-@SystemApi
public class NetworkPolicyManager {
/* POLICY_* are masks and can be ORed, although currently they are not.*/
@@ -162,11 +160,13 @@
/**
* Mask used to check if an override value is marked as unmetered.
+ * @hide
*/
public static final int SUBSCRIPTION_OVERRIDE_UNMETERED = 1 << 0;
/**
* Mask used to check if an override value is marked as congested.
+ * @hide
*/
public static final int SUBSCRIPTION_OVERRIDE_CONGESTED = 1 << 1;
@@ -294,7 +294,6 @@
/** @hide */
@RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
- @SystemApi
public void registerSubscriptionCallback(@NonNull SubscriptionCallback callback) {
if (callback == null) {
throw new NullPointerException("Callback cannot be null.");
@@ -309,7 +308,6 @@
/** @hide */
@RequiresPermission(android.Manifest.permission.OBSERVE_NETWORK_POLICY)
- @SystemApi
public void unregisterSubscriptionCallback(@NonNull SubscriptionCallback callback) {
if (callback == null) {
throw new NullPointerException("Callback cannot be null.");
@@ -373,6 +371,7 @@
* requested state until explicitly cleared, or the next reboot,
* whichever happens first
* @param callingPackage the name of the package making the call.
+ * @hide
*/
public void setSubscriptionOverride(int subId, @SubscriptionOverrideMask int overrideMask,
@SubscriptionOverrideMask int overrideValue, long timeoutMillis,
@@ -391,6 +390,7 @@
* @param subId the subscriber this relationship applies to.
* @param plans the list of plans.
* @param callingPackage the name of the package making the call
+ * @hide
*/
public void setSubscriptionPlans(int subId, @NonNull SubscriptionPlan[] plans,
@NonNull String callingPackage) {
@@ -406,6 +406,7 @@
*
* @param subId the subscriber to get the subscription plans for.
* @param callingPackage the name of the package making the call.
+ * @hide
*/
@NonNull
public SubscriptionPlan[] getSubscriptionPlans(int subId, @NonNull String callingPackage) {
@@ -549,7 +550,6 @@
}
/** @hide */
- @SystemApi
public static class SubscriptionCallback {
/**
* Notify clients of a new override about a given subscription.
diff --git a/core/java/android/net/NetworkProvider.java b/core/java/android/net/NetworkProvider.java
index 2c0e4aa..418d691 100644
--- a/core/java/android/net/NetworkProvider.java
+++ b/core/java/android/net/NetworkProvider.java
@@ -106,10 +106,12 @@
}
// TODO: consider adding a register() method so ConnectivityManager does not need to call this.
+ /** @hide */
public @Nullable Messenger getMessenger() {
return mMessenger;
}
+ /** @hide */
public @NonNull String getName() {
return mName;
}
diff --git a/core/java/android/net/NetworkScore.java b/core/java/android/net/NetworkScore.java
deleted file mode 100644
index 13f2994..0000000
--- a/core/java/android/net/NetworkScore.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2019 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.net;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/**
- * Object representing the quality of a network as perceived by the user.
- *
- * A NetworkScore object represents the characteristics of a network that affects how good the
- * network is considered for a particular use.
- * @hide
- */
-public final class NetworkScore implements Parcelable {
-
- // The key of bundle which is used to get the legacy network score of NetworkAgentInfo.
- // TODO: Remove this when the transition to NetworkScore is over.
- public static final String LEGACY_SCORE = "LEGACY_SCORE";
- @NonNull
- private final Bundle mExtensions;
-
- public NetworkScore() {
- mExtensions = new Bundle();
- }
-
- public NetworkScore(@NonNull NetworkScore source) {
- mExtensions = new Bundle(source.mExtensions);
- }
-
- /**
- * Put the value of parcelable inside the bundle by key.
- */
- public void putExtension(@Nullable String key, @Nullable Parcelable value) {
- mExtensions.putParcelable(key, value);
- }
-
- /**
- * Put the value of int inside the bundle by key.
- */
- public void putIntExtension(@Nullable String key, int value) {
- mExtensions.putInt(key, value);
- }
-
- /**
- * Get the value of non primitive type by key.
- */
- public <T extends Parcelable> T getExtension(@Nullable String key) {
- return mExtensions.getParcelable(key);
- }
-
- /**
- * Get the value of int by key.
- */
- public int getIntExtension(@Nullable String key) {
- return mExtensions.getInt(key);
- }
-
- /**
- * Remove the entry by given key.
- */
- public void removeExtension(@Nullable String key) {
- mExtensions.remove(key);
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- synchronized (this) {
- dest.writeBundle(mExtensions);
- }
- }
-
- public static final @NonNull Creator<NetworkScore> CREATOR = new Creator<NetworkScore>() {
- @Override
- public NetworkScore createFromParcel(@NonNull Parcel in) {
- return new NetworkScore(in);
- }
-
- @Override
- public NetworkScore[] newArray(int size) {
- return new NetworkScore[size];
- }
- };
-
- private NetworkScore(@NonNull Parcel in) {
- mExtensions = in.readBundle();
- }
-
- // TODO: Modify this method once new fields are added into this class.
- @Override
- public boolean equals(@Nullable Object obj) {
- if (!(obj instanceof NetworkScore)) {
- return false;
- }
- final NetworkScore other = (NetworkScore) obj;
- return bundlesEqual(mExtensions, other.mExtensions);
- }
-
- @Override
- public int hashCode() {
- int result = 29;
- for (String key : mExtensions.keySet()) {
- final Object value = mExtensions.get(key);
- // The key may be null, so call Objects.hash() is safer.
- result += 31 * value.hashCode() + 37 * Objects.hash(key);
- }
- return result;
- }
-
- // mExtensions won't be null since the constructor will create it.
- private boolean bundlesEqual(@NonNull Bundle bundle1, @NonNull Bundle bundle2) {
- if (bundle1 == bundle2) {
- return true;
- }
-
- // This is unlikely but it's fine to add this clause here.
- if (null == bundle1 || null == bundle2) {
- return false;
- }
-
- if (bundle1.size() != bundle2.size()) {
- return false;
- }
-
- for (String key : bundle1.keySet()) {
- final Object value1 = bundle1.get(key);
- final Object value2 = bundle2.get(key);
- if (!Objects.equals(value1, value2)) {
- return false;
- }
- }
- return true;
- }
-
- /** Convert to a string */
- public String toString() {
- return "NetworkScore[" + mExtensions.toString() + "]";
- }
-}
diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java
index fe7c7c9..c889ee6 100644
--- a/core/java/android/os/Binder.java
+++ b/core/java/android/os/Binder.java
@@ -248,6 +248,27 @@
}
}
+ static ThreadLocal<Boolean> sWarnOnBlockingOnCurrentThread =
+ ThreadLocal.withInitial(() -> sWarnOnBlocking);
+
+ /**
+ * Allow blocking calls for the current thread. See {@link #allowBlocking}.
+ *
+ * @hide
+ */
+ public static void allowBlockingForCurrentThread() {
+ sWarnOnBlockingOnCurrentThread.set(false);
+ }
+
+ /**
+ * Reset the current thread to the default blocking behavior. See {@link #defaultBlocking}.
+ *
+ * @hide
+ */
+ public static void defaultBlockingForCurrentThread() {
+ sWarnOnBlockingOnCurrentThread.set(sWarnOnBlocking);
+ }
+
/**
* Raw native pointer to JavaBBinderHolder object. Owned by this Java object. Not null.
*/
diff --git a/core/java/android/os/BinderProxy.java b/core/java/android/os/BinderProxy.java
index be307ab..20e5f24 100644
--- a/core/java/android/os/BinderProxy.java
+++ b/core/java/android/os/BinderProxy.java
@@ -479,16 +479,21 @@
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
Binder.checkParcel(this, code, data, "Unreasonably large binder buffer");
- if (mWarnOnBlocking && ((flags & FLAG_ONEWAY) == 0)) {
+ if (mWarnOnBlocking && ((flags & FLAG_ONEWAY) == 0)
+ && Binder.sWarnOnBlockingOnCurrentThread.get()) {
+
// For now, avoid spamming the log by disabling after we've logged
// about this interface at least once
mWarnOnBlocking = false;
+
if (Build.IS_USERDEBUG) {
// Log this as a WTF on userdebug builds.
- Log.wtf(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
+ Log.wtf(Binder.TAG,
+ "Outgoing transactions from this process must be FLAG_ONEWAY",
new Throwable());
} else {
- Log.w(Binder.TAG, "Outgoing transactions from this process must be FLAG_ONEWAY",
+ Log.w(Binder.TAG,
+ "Outgoing transactions from this process must be FLAG_ONEWAY",
new Throwable());
}
}
@@ -521,7 +526,7 @@
final AppOpsManager.PausedNotedAppOpsCollection prevCollection =
AppOpsManager.pauseNotedAppOpsCollection();
- if ((flags & FLAG_ONEWAY) == 0 && AppOpsManager.isCollectingNotedAppOps()) {
+ if ((flags & FLAG_ONEWAY) == 0 && AppOpsManager.isListeningForOpNoted()) {
flags |= FLAG_COLLECT_NOTED_APP_OPS;
}
diff --git a/core/java/android/os/BugreportManager.java b/core/java/android/os/BugreportManager.java
index 9ca1c33..fab906b 100644
--- a/core/java/android/os/BugreportManager.java
+++ b/core/java/android/os/BugreportManager.java
@@ -157,20 +157,20 @@
Preconditions.checkNotNull(executor);
Preconditions.checkNotNull(callback);
- boolean validScreenshotFd = screenshotFd != null;
+ boolean isScreenshotRequested = screenshotFd != null;
if (screenshotFd == null) {
// Binder needs a valid File Descriptor to be passed
screenshotFd = ParcelFileDescriptor.open(new File("/dev/null"),
ParcelFileDescriptor.MODE_READ_ONLY);
}
DumpstateListener dsListener = new DumpstateListener(executor, callback,
- validScreenshotFd);
+ isScreenshotRequested);
// Note: mBinder can get callingUid from the binder transaction.
mBinder.startBugreport(-1 /* callingUid */,
mContext.getOpPackageName(),
bugreportFd.getFileDescriptor(),
screenshotFd.getFileDescriptor(),
- params.getMode(), dsListener);
+ params.getMode(), dsListener, isScreenshotRequested);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
} catch (FileNotFoundException e) {
@@ -225,13 +225,13 @@
private final class DumpstateListener extends IDumpstateListener.Stub {
private final Executor mExecutor;
private final BugreportCallback mCallback;
- private final boolean mValidScreenshotFd;
+ private final boolean mIsScreenshotRequested;
DumpstateListener(Executor executor, BugreportCallback callback,
- boolean validScreenshotFd) {
+ boolean isScreenshotRequested) {
mExecutor = executor;
mCallback = callback;
- mValidScreenshotFd = validScreenshotFd;
+ mIsScreenshotRequested = isScreenshotRequested;
}
@Override
@@ -272,7 +272,7 @@
@Override
public void onScreenshotTaken(boolean success) throws RemoteException {
- if (!mValidScreenshotFd) {
+ if (!mIsScreenshotRequested) {
return;
}
diff --git a/core/java/android/os/ConfigUpdate.java b/core/java/android/os/ConfigUpdate.java
index 9c999b2..590fbb3 100644
--- a/core/java/android/os/ConfigUpdate.java
+++ b/core/java/android/os/ConfigUpdate.java
@@ -16,6 +16,7 @@
package android.os;
+import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
/**
@@ -114,20 +115,36 @@
= "android.os.action.UPDATE_CARRIER_ID_DB";
/**
- * Broadcast intent action indicating that the updated emergency number database is available.
- * <p>Extra: "VERSION" the numeric version of the new data. Devices should only install if the
- * update version is newer than the current one.
- * <p>Extra: "REQUIRED_HASH" the hash of the current update data.
- * <p>Input: {@link android.content.Intent#getData} is URI of downloaded emergency number file.
- * Devices should pick up the downloaded file and persist to the database
- * {@code com.android.internal.telephony.emergency.EmergencyNumberTracker}.
+ * Update the emergency number database into the devices.
+ * <p>Extra: {@link #EXTRA_VERSION} the numeric version of the database.
+ * <p>Extra: {@link #EXTRA_REQUIRED_HASH} the hash of the database.
+ * <p>Input: {@link android.content.Intent#getData} the URI to download emergency number
+ * database.
*
* @hide
*/
@SystemApi
+ @RequiresPermission(android.Manifest.permission.UPDATE_CONFIG)
public static final String ACTION_UPDATE_EMERGENCY_NUMBER_DB =
"android.os.action.UPDATE_EMERGENCY_NUMBER_DB";
+ /**
+ * An integer to indicate the numeric version of the new data. Devices should only install
+ * if the update version is newer than the current one.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static final String EXTRA_VERSION = "android.os.extra.VERSION";
+
+ /**
+ * A string to indicate the hash of the data.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static final String EXTRA_REQUIRED_HASH = "android.os.extra.REQUIRED_HASH";
+
private ConfigUpdate() {
}
}
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 21a1e0f..09ccb72 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -23,6 +23,7 @@
import android.app.AppGlobals;
import android.app.AppOpsManager;
import android.app.admin.DevicePolicyManager;
+import android.compat.Compatibility;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
@@ -39,6 +40,7 @@
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
+import java.util.Objects;
/**
* Provides access to environment variables.
@@ -87,6 +89,16 @@
private static final File DIR_APEX_ROOT = getDirectory(ENV_APEX_ROOT,
"/apex");
+ /**
+ * See definition in com.android.providers.media.LocalCallingIdentity
+ */
+ private static final long DEFAULT_SCOPED_STORAGE = 149924527L;
+
+ /**
+ * See definition in com.android.providers.media.LocalCallingIdentity
+ */
+ private static final long FORCE_ENABLE_SCOPED_STORAGE = 132649864L;
+
@UnsupportedAppUsage
private static UserEnvironment sCurrentUser;
private static boolean sUserRequired;
@@ -1190,12 +1202,13 @@
}
/**
- * Returns whether the primary shared/external storage media is a legacy
- * view that includes files not owned by the app.
+ * Returns whether the shared/external storage media is a
+ * legacy view that includes files not owned by the app.
* <p>
* This value may be different from the value requested by
* {@code requestLegacyExternalStorage} in the app's manifest, since an app
- * may inherit its legacy state based on when it was first installed.
+ * may inherit its legacy state based on when it was first installed, target sdk and other
+ * factors.
* <p>
* Non-legacy apps can continue to discover and read media belonging to
* other apps via {@link android.provider.MediaStore}.
@@ -1206,18 +1219,19 @@
}
/**
- * Returns whether the shared/external storage media at the given path is a
+ * Returns whether the shared/external storage media is a
* legacy view that includes files not owned by the app.
* <p>
* This value may be different from the value requested by
* {@code requestLegacyExternalStorage} in the app's manifest, since an app
- * may inherit its legacy state based on when it was first installed.
+ * may inherit its legacy state based on when it was first installed, target sdk and other
+ * factors.
* <p>
* Non-legacy apps can continue to discover and read media belonging to
* other apps via {@link android.provider.MediaStore}.
*
* @throws IllegalArgumentException if the path is not a valid storage
- * device.
+ * device.
*/
public static boolean isExternalStorageLegacy(@NonNull File path) {
final Context context = AppGlobals.getInitialApplication();
@@ -1231,28 +1245,81 @@
return false;
}
- if (packageManager.checkPermission(Manifest.permission.WRITE_MEDIA_STORAGE,
- context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
+ // TODO(b/150672994): Compat flags do not override instant app and isolated process's
+ // behavior.
+ boolean defaultScopedStorage = Compatibility.isChangeEnabled(DEFAULT_SCOPED_STORAGE);
+ boolean forceEnableScopedStorage = Compatibility.isChangeEnabled(
+ FORCE_ENABLE_SCOPED_STORAGE);
+ // if Scoped Storage is strictly enforced, the app does *not* have legacy storage access
+ // Note: does not require packagename/uid as this is directly called from an app process
+ if (isScopedStorageEnforced(defaultScopedStorage, forceEnableScopedStorage)) {
+ return false;
+ }
+ // if Scoped Storage is strictly disabled, the app has legacy storage access
+ // Note: does not require packagename/uid as this is directly called from an app process
+ if (isScopedStorageDisabled(defaultScopedStorage, forceEnableScopedStorage)) {
return true;
}
- if (packageManager.checkPermission(Manifest.permission.INSTALL_PACKAGES,
- context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
- return true;
- }
final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
- final String[] packagesForUid = packageManager.getPackagesForUid(uid);
- for (String packageName : packagesForUid) {
- if (appOps.checkOpNoThrow(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
- uid, packageName) == AppOpsManager.MODE_ALLOWED) {
- return true;
- }
- }
-
return appOps.checkOpNoThrow(AppOpsManager.OP_LEGACY_STORAGE,
uid, context.getOpPackageName()) == AppOpsManager.MODE_ALLOWED;
}
+ /**
+ * Returns whether the calling app has All Files Access on the primary shared/external storage
+ * media.
+ * <p>Declaring the permission {@link android.Manifest.permission#MANAGE_EXTERNAL_STORAGE} isn't
+ * enough to gain the access.
+ * <p>To request access, use
+ * {@link android.provider.Settings#ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION}.
+ */
+ public static boolean isExternalStorageManager() {
+ final File externalDir = sCurrentUser.getExternalDirs()[0];
+ return isExternalStorageManager(externalDir);
+ }
+
+ /**
+ * Returns whether the calling app has All Files Access at the given {@code path}
+ * <p>Declaring the permission {@link android.Manifest.permission#MANAGE_EXTERNAL_STORAGE} isn't
+ * enough to gain the access.
+ * <p>To request access, use
+ * {@link android.provider.Settings#ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION}.
+ */
+ public static boolean isExternalStorageManager(@NonNull File path) {
+ final Context context = Objects.requireNonNull(AppGlobals.getInitialApplication());
+ String packageName = Objects.requireNonNull(context.getPackageName());
+ int uid = context.getApplicationInfo().uid;
+
+ final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
+ final int opMode =
+ appOps.checkOpNoThrow(AppOpsManager.OP_MANAGE_EXTERNAL_STORAGE, uid, packageName);
+
+ switch (opMode) {
+ case AppOpsManager.MODE_DEFAULT:
+ return PackageManager.PERMISSION_GRANTED
+ == context.checkPermission(
+ Manifest.permission.MANAGE_EXTERNAL_STORAGE, Process.myPid(), uid);
+ case AppOpsManager.MODE_ALLOWED:
+ return true;
+ case AppOpsManager.MODE_ERRORED:
+ case AppOpsManager.MODE_IGNORED:
+ return false;
+ default:
+ throw new IllegalStateException("Unknown AppOpsManager mode " + opMode);
+ }
+ }
+
+ private static boolean isScopedStorageEnforced(boolean defaultScopedStorage,
+ boolean forceEnableScopedStorage) {
+ return defaultScopedStorage && forceEnableScopedStorage;
+ }
+
+ private static boolean isScopedStorageDisabled(boolean defaultScopedStorage,
+ boolean forceEnableScopedStorage) {
+ return !defaultScopedStorage && !forceEnableScopedStorage;
+ }
+
static File getDirectory(String variableName, String defaultPath) {
String path = System.getenv(variableName);
return path == null ? new File(defaultPath) : new File(path);
diff --git a/core/java/android/os/IPowerManager.aidl b/core/java/android/os/IPowerManager.aidl
index 1cefbd9..c44a0bd 100644
--- a/core/java/android/os/IPowerManager.aidl
+++ b/core/java/android/os/IPowerManager.aidl
@@ -38,6 +38,8 @@
void releaseWakeLock(IBinder lock, int flags);
void updateWakeLockUids(IBinder lock, in int[] uids);
oneway void powerHint(int hintId, int data);
+ oneway void setPowerBoost(int boost, int durationMs);
+ oneway void setPowerMode(int mode, boolean enabled);
void updateWakeLockWorkSource(IBinder lock, in WorkSource ws, String historyTag);
boolean isWakeLockLevelSupported(int level);
diff --git a/core/java/android/os/Looper.java b/core/java/android/os/Looper.java
index b478dbe..a7e3263 100644
--- a/core/java/android/os/Looper.java
+++ b/core/java/android/os/Looper.java
@@ -77,6 +77,7 @@
@UnsupportedAppUsage
final MessageQueue mQueue;
final Thread mThread;
+ private boolean mInLoop;
@UnsupportedAppUsage
private Printer mLogging;
@@ -155,6 +156,12 @@
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
+ if (me.mInLoop) {
+ Slog.w(TAG, "Loop again would have the queued messages be executed"
+ + " before this one completed.");
+ }
+
+ me.mInLoop = true;
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
diff --git a/core/java/android/os/ParcelFileDescriptor.java b/core/java/android/os/ParcelFileDescriptor.java
index 89ddf8c..c084787 100644
--- a/core/java/android/os/ParcelFileDescriptor.java
+++ b/core/java/android/os/ParcelFileDescriptor.java
@@ -282,9 +282,7 @@
* @param listener to be invoked when the returned descriptor has been
* closed.
* @return a new ParcelFileDescriptor pointing to the given file.
- * @hide
*/
- @SystemApi
// We can't accept a generic Executor here, since we need to use
// MessageQueue.addOnFileDescriptorEventListener()
@SuppressLint("ExecutorRegistration")
diff --git a/core/java/android/os/PowerManagerInternal.java b/core/java/android/os/PowerManagerInternal.java
index 9661a08..51f01ca 100644
--- a/core/java/android/os/PowerManagerInternal.java
+++ b/core/java/android/os/PowerManagerInternal.java
@@ -201,6 +201,119 @@
*/
public abstract void powerHint(int hintId, int data);
+ /**
+ * Boost: It is sent when user interacting with the device, for example,
+ * touchscreen events are incoming.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Boost.aidl
+ */
+ public static final int BOOST_INTERACTION = 0;
+
+ /**
+ * Boost: It indicates that the framework is likely to provide a new display
+ * frame soon. This implies that the device should ensure that the display
+ * processing path is powered up and ready to receive that update.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Boost.aidl
+ */
+ public static final int BOOST_DISPLAY_UPDATE_IMMINENT = 1;
+
+ /**
+ * SetPowerBoost() indicates the device may need to boost some resources, as
+ * the load is likely to increase before the kernel governors can react.
+ * Depending on the boost, it may be appropriate to raise the frequencies of
+ * CPU, GPU, memory subsystem, or stop CPU from going into deep sleep state.
+ *
+ * @param boost Boost which is to be set with a timeout.
+ * @param durationMs The expected duration of the user's interaction, if
+ * known, or 0 if the expected duration is unknown.
+ * a negative value indicates canceling previous boost.
+ * A given platform can choose to boost some time based on durationMs,
+ * and may also pick an appropriate timeout for 0 case.
+ */
+ public abstract void setPowerBoost(int boost, int durationMs);
+
+ /**
+ * Mode: It indicates that the device is to allow wake up when the screen
+ * is tapped twice.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_DOUBLE_TAP_TO_WAKE = 0;
+
+ /**
+ * Mode: It indicates Low power mode is activated or not. Low power mode
+ * is intended to save battery at the cost of performance.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_LOW_POWER = 1;
+
+ /**
+ * Mode: It indicates Sustained Performance mode is activated or not.
+ * Sustained performance mode is intended to provide a consistent level of
+ * performance for a prolonged amount of time.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_SUSTAINED_PERFORMANCE = 2;
+
+ /**
+ * Mode: It sets the device to a fixed performance level which can be sustained
+ * under normal indoor conditions for at least 10 minutes.
+ * Fixed performance mode puts both upper and lower bounds on performance such
+ * that any workload run while in a fixed performance mode should complete in
+ * a repeatable amount of time.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_FIXED_PERFORMANCE = 3;
+
+ /**
+ * Mode: It indicates VR Mode is activated or not. VR mode is intended to
+ * provide minimum guarantee for performance for the amount of time the device
+ * can sustain it.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_VR = 4;
+
+ /**
+ * Mode: It indicates that an application has been launched.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_LAUNCH = 5;
+
+ /**
+ * Mode: It indicates that the device is about to enter a period of expensive
+ * rendering.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_EXPENSIVE_RENDERING = 6;
+
+ /**
+ * Mode: It indicates that the device is about entering/leaving interactive
+ * state or on-interactive state.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_INTERACTIVE = 7;
+
+ /**
+ * Mode: It indicates the device is in device idle, externally known as doze.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_DEVICE_IDLE = 8;
+
+ /**
+ * Mode: It indicates that display is either off or still on but is optimized
+ * for low power.
+ * Defined in hardware/interfaces/power/aidl/android/hardware/power/Mode.aidl
+ */
+ public static final int MODE_DISPLAY_INACTIVE = 9;
+
+ /**
+ * SetPowerMode() is called to enable/disable specific hint mode, which
+ * may result in adjustment of power/performance parameters of the
+ * cpufreq governor and other controls on device side.
+ *
+ * @param mode Mode which is to be enable/disable.
+ * @param enabled true to enable, false to disable the mode.
+ */
+ public abstract void setPowerMode(int mode, boolean enabled);
+
/** Returns whether there hasn't been a user activity event for the given number of ms. */
public abstract boolean wasDeviceIdleFor(long ms);
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index d7af1b9..a557bd9 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -607,6 +607,7 @@
* started.
* @param pkgDataInfoMap Map from related package names to private data directory
* volume UUID and inode number.
+ * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data.
* @param zygoteArgs Additional arguments to supply to the zygote process.
* @return An object that describes the result of the attempt to start the process.
* @throws RuntimeException on fatal start failure
@@ -630,12 +631,13 @@
@Nullable long[] disabledCompatChanges,
@Nullable Map<String, Pair<String, Long>>
pkgDataInfoMap,
+ boolean bindMountAppStorageDirs,
@Nullable String[] zygoteArgs) {
return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, packageName,
zygotePolicyFlags, isTopApp, disabledCompatChanges,
- pkgDataInfoMap, zygoteArgs);
+ pkgDataInfoMap, bindMountAppStorageDirs, zygoteArgs);
}
/** @hide */
@@ -659,7 +661,7 @@
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, packageName,
/*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, /*isTopApp=*/ false,
- disabledCompatChanges, /* pkgDataInfoMap */ null, zygoteArgs);
+ disabledCompatChanges, /* pkgDataInfoMap */ null, false, zygoteArgs);
}
/**
diff --git a/core/java/android/os/Users.md b/core/java/android/os/Users.md
new file mode 100644
index 0000000..3bbbe54
--- /dev/null
+++ b/core/java/android/os/Users.md
@@ -0,0 +1,109 @@
+<!--
+ Copyright (C) 2020 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
+ -->
+
+# Users for system developers
+
+## Concepts
+
+### User
+
+A user of a device e.g. usually a human being. Each user has its own home screen.
+
+#### User Profile
+
+A user can have multiple profiles. E.g. one for the private life and one for work. Each profile
+has a different set of apps and accounts but they share one home screen. All profiles of a
+profile group can be active at the same time.
+
+Each profile has a separate [`userId`](#int-userid). Unless needed user profiles are treated as
+completely separate users.
+
+#### Profile Group
+
+All user profiles that share a home screen. You can list the profiles of a user via
+`UserManager#getEnabledProfiles` (you usually don't deal with disabled profiles)
+
+#### Foreground user vs background user
+
+Only a single user profile group can be in the foreground. This is the user profile the user
+currently interacts with.
+
+#### Parent user (profile)
+
+The main profile of a profile group, usually the personal (as opposed to work) profile. Get this via
+`UserManager#getProfileParent` (returns `null` if the user does not have profiles)
+
+#### Managed user (profile)
+
+The other profiles of a profile group. The name comes from the fact that these profiles are usually
+managed by a device policy controller app. You can create a managed profile from within the device
+policy controller app on your phone.
+
+#### Account
+
+An account of a user profile with a (usually internet based) service. E.g. aname@gmail.com or
+aname@yahoo.com. Each profile can have multiple accounts. A profile does not have to have a
+account.
+
+## Data types
+
+### int userId
+
+... usually marked as `@UserIdInt`
+
+The id of a user profile. List all users via `adb shell dumpsys user`. There is no data type for a
+user, all you can do is using the user id of the parent profile as a proxy for the user.
+
+### int uid
+
+Identity of an app. This is the same as a Linux uid, but in Android there is one uid per package,
+per user.
+
+It is highly discouraged, but uids can be shared between multiple packages using the
+`android:sharedUserId` manifest attribute.
+
+### class UserHandle
+
+A wrapper for userId. Used esp. in public APIs instead of `int userId` as it clearly distinguishes
+from uid.
+
+## Security model
+
+Multiple packages can share an uid by using `android:sharedUserId` manifest attribute. If packages
+share a uid they can run in the same process via `android:process` manifest attribute. Further file
+level access is also tracked by uid. Hence any security or privacy mechanism needs to be built on
+a uid granularity.
+
+On the other hand apps belonging to the same user cannot see each others files. They can only
+interact via activity launches, broadcasts, providers, and service bindings. All of them can be be
+protected by [permissions](../permission/Permissions.md). Hence any new general communication
+mechanism should be access controlled by permissions.
+
+## Lifecycle
+
+A system service should deal with users being started and stopped by overriding
+`SystemService.onSwitchUser` and `SystemService.onStopUser`.
+
+If users profiles become inactive the system should stop all apps of this profile from interacting
+with other apps or the system.
+
+Another important lifecycle event is `onUnlockUser`. Only for unlocked user profiles you can access
+all data, e.g. which packages are installed.
+
+You only want to deal with user profiles that
+
+- are in the profile group of the foreground user
+- the user profile is unlocked and not yet stopped
diff --git a/core/java/android/os/VibrationEffect.java b/core/java/android/os/VibrationEffect.java
index 2d218f4..1992f1d 100644
--- a/core/java/android/os/VibrationEffect.java
+++ b/core/java/android/os/VibrationEffect.java
@@ -963,7 +963,7 @@
PRIMITIVE_QUICK_RISE,
PRIMITIVE_SLOW_RISE,
PRIMITIVE_QUICK_FALL,
- PRIMITIVE_LIGHT_TICK,
+ PRIMITIVE_TICK,
})
@Retention(RetentionPolicy.SOURCE)
public @interface Primitive {}
@@ -981,10 +981,14 @@
* A haptic effect that simulates downwards movement with gravity. Often
* followed by extra energy of hitting and reverberation to augment
* physicality.
+ *
+ * @hide Not confident enough to expose publicly yet
*/
public static final int PRIMITIVE_THUD = 2;
/**
* A haptic effect that simulates spinning momentum.
+ *
+ * @hide Not confident enough to expose publicly yet
*/
public static final int PRIMITIVE_SPIN = 3;
/**
@@ -1003,7 +1007,8 @@
* This very short effect should produce a light crisp sensation intended
* to be used repetitively for dynamic feedback.
*/
- public static final int PRIMITIVE_LIGHT_TICK = 7;
+ // Internally this maps to the HAL constant CompositePrimitive::LIGHT_TICK
+ public static final int PRIMITIVE_TICK = 7;
private ArrayList<PrimitiveEffect> mEffects = new ArrayList<>();
@@ -1081,7 +1086,7 @@
*
*/
static int checkPrimitive(int primitiveId) {
- Preconditions.checkArgumentInRange(primitiveId, PRIMITIVE_NOOP, PRIMITIVE_LIGHT_TICK,
+ Preconditions.checkArgumentInRange(primitiveId, PRIMITIVE_NOOP, PRIMITIVE_TICK,
"primitiveId");
return primitiveId;
}
@@ -1108,8 +1113,8 @@
return "PRIMITIVE_SLOW_RISE";
case PRIMITIVE_QUICK_FALL:
return "PRIMITIVE_QUICK_FALL";
- case PRIMITIVE_LIGHT_TICK:
- return "PRIMITIVE_LIGHT_TICK";
+ case PRIMITIVE_TICK:
+ return "PRIMITIVE_TICK";
default:
return Integer.toString(id);
diff --git a/core/java/android/os/ZygoteProcess.java b/core/java/android/os/ZygoteProcess.java
index 34cec06..5f3f14f 100644
--- a/core/java/android/os/ZygoteProcess.java
+++ b/core/java/android/os/ZygoteProcess.java
@@ -333,6 +333,7 @@
* started.
* @param pkgDataInfoMap Map from related package names to private data directory
* volume UUID and inode number.
+ * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data.
*
* @param zygoteArgs Additional arguments to supply to the Zygote process.
* @return An object that describes the result of the attempt to start the process.
@@ -354,6 +355,7 @@
@Nullable long[] disabledCompatChanges,
@Nullable Map<String, Pair<String, Long>>
pkgDataInfoMap,
+ boolean bindMountAppStorageDirs,
@Nullable String[] zygoteArgs) {
// TODO (chriswailes): Is there a better place to check this value?
if (fetchUsapPoolEnabledPropWithMinInterval()) {
@@ -365,7 +367,7 @@
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
packageName, zygotePolicyFlags, isTopApp, disabledCompatChanges,
- pkgDataInfoMap, zygoteArgs);
+ pkgDataInfoMap, bindMountAppStorageDirs, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
Log.e(LOG_TAG,
"Starting VM process through Zygote failed");
@@ -606,6 +608,7 @@
* @param disabledCompatChanges a list of disabled compat changes for the process being started.
* @param pkgDataInfoMap Map from related package names to private data directory volume UUID
* and inode number.
+ * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data.
* @param extraArgs Additional arguments to supply to the zygote process.
* @return An object that describes the result of the attempt to start the process.
* @throws ZygoteStartFailedEx if process start failed for any reason
@@ -628,6 +631,7 @@
@Nullable long[] disabledCompatChanges,
@Nullable Map<String, Pair<String, Long>>
pkgDataInfoMap,
+ boolean bindMountAppStorageDirs,
@Nullable String[] extraArgs)
throws ZygoteStartFailedEx {
ArrayList<String> argsForZygote = new ArrayList<>();
@@ -725,6 +729,10 @@
argsForZygote.add(sb.toString());
}
+ if (bindMountAppStorageDirs) {
+ argsForZygote.add(Zygote.BIND_MOUNT_APP_STORAGE_DIRS);
+ }
+
if (disabledCompatChanges != null && disabledCompatChanges.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("--disabled-compat-changes=");
@@ -1282,7 +1290,9 @@
abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
true /* startChildZygote */, null /* packageName */,
ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS /* zygotePolicyFlags */, false /* isTopApp */,
- null /* disabledCompatChanges */, null /* pkgDataInfoMap */, extraArgs);
+ null /* disabledCompatChanges */, null /* pkgDataInfoMap */,
+ /* bindMountAppStorageDirs */ false, extraArgs);
+
} catch (ZygoteStartFailedEx ex) {
throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
}
diff --git a/core/java/android/os/incremental/IncrementalNewFileParams.aidl b/core/java/android/os/incremental/IncrementalNewFileParams.aidl
index 182732c..8faf158 100644
--- a/core/java/android/os/incremental/IncrementalNewFileParams.aidl
+++ b/core/java/android/os/incremental/IncrementalNewFileParams.aidl
@@ -16,8 +16,6 @@
package android.os.incremental;
-import android.os.incremental.IncrementalSignature;
-
/**
* All the parameters to create a new file on IncFS
* FileId is a 16 byte-long identifier.
@@ -27,5 +25,5 @@
long size;
byte[] fileId;
byte[] metadata;
- @nullable IncrementalSignature signature;
+ @nullable byte[] signature;
}
diff --git a/core/java/android/os/incremental/IncrementalSignature.aidl b/core/java/android/os/incremental/IncrementalSignature.aidl
deleted file mode 100644
index 729e8e5..0000000
--- a/core/java/android/os/incremental/IncrementalSignature.aidl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2020 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.os.incremental;
-
-/** {@hide} */
-parcelable IncrementalSignature {
- /*
- * Stable AIDL doesn't support constants, but here's the possible values
- * const int HASH_ALGO_NONE = 0;
- * const int HASH_ALGO_SHA256 = 1;
- */
-
- int hashAlgorithm = 0;
- byte[] rootHash;
- byte[] additionalData;
- byte[] signature;
-}
diff --git a/core/java/android/os/incremental/IncrementalStorage.java b/core/java/android/os/incremental/IncrementalStorage.java
index bf31bc2..7092751 100644
--- a/core/java/android/os/incremental/IncrementalStorage.java
+++ b/core/java/android/os/incremental/IncrementalStorage.java
@@ -20,8 +20,6 @@
import android.annotation.Nullable;
import android.os.RemoteException;
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -180,11 +178,12 @@
if (id == null && metadata == null) {
throw new IOException("File ID and metadata cannot both be null");
}
+ validateV4Signature(v4signatureBytes);
final IncrementalNewFileParams params = new IncrementalNewFileParams();
params.size = size;
params.metadata = (metadata == null ? new byte[0] : metadata);
params.fileId = idToBytes(id);
- params.signature = parseV4Signature(v4signatureBytes);
+ params.signature = v4signatureBytes;
int res = mService.makeFile(mId, path, params);
if (res != 0) {
throw new IOException("makeFile() failed with errno " + -res);
@@ -415,27 +414,23 @@
return new UUID(msb, lsb);
}
- private static final int INCFS_HASH_SHA256 = 1;
private static final int INCFS_MAX_HASH_SIZE = 32; // SHA256
private static final int INCFS_MAX_ADD_DATA_SIZE = 128;
/**
* Deserialize and validate v4 signature bytes.
*/
- private static IncrementalSignature parseV4Signature(@Nullable byte[] v4signatureBytes)
+ private static void validateV4Signature(@Nullable byte[] v4signatureBytes)
throws IOException {
if (v4signatureBytes == null || v4signatureBytes.length == 0) {
- return null;
+ return;
}
final V4Signature signature;
- try (DataInputStream input = new DataInputStream(
- new ByteArrayInputStream(v4signatureBytes))) {
- try {
- signature = V4Signature.readFrom(input);
- } catch (IOException e) {
- throw new IOException("Failed to read v4 signature:", e);
- }
+ try {
+ signature = V4Signature.readFrom(v4signatureBytes);
+ } catch (IOException e) {
+ throw new IOException("Failed to read v4 signature:", e);
}
if (!signature.isVersionSupported()) {
@@ -443,25 +438,27 @@
+ " is not supported");
}
- final byte[] rootHash = signature.verityRootHash;
- final byte[] additionalData = signature.v3Digest;
- final byte[] pkcs7Signature = signature.pkcs7SignatureBlock;
+ final V4Signature.HashingInfo hashingInfo = V4Signature.HashingInfo.fromByteArray(
+ signature.hashingInfo);
+ final V4Signature.SigningInfo signingInfo = V4Signature.SigningInfo.fromByteArray(
+ signature.signingInfo);
- if (rootHash.length != INCFS_MAX_HASH_SIZE) {
- throw new IOException("rootHash has to be " + INCFS_MAX_HASH_SIZE + " bytes");
+ if (hashingInfo.hashAlgorithm != V4Signature.HASHING_ALGORITHM_SHA256) {
+ throw new IOException("Unsupported hashAlgorithm: " + hashingInfo.hashAlgorithm);
}
- if (additionalData.length > INCFS_MAX_ADD_DATA_SIZE) {
+ if (hashingInfo.log2BlockSize != V4Signature.LOG2_BLOCK_SIZE_4096_BYTES) {
+ throw new IOException("Unsupported log2BlockSize: " + hashingInfo.log2BlockSize);
+ }
+ if (hashingInfo.salt != null && hashingInfo.salt.length > 0) {
+ throw new IOException("Unsupported salt: " + hashingInfo.salt);
+ }
+ if (hashingInfo.rawRootHash.length != INCFS_MAX_HASH_SIZE) {
+ throw new IOException("rawRootHash has to be " + INCFS_MAX_HASH_SIZE + " bytes");
+ }
+ if (signingInfo.additionalData.length > INCFS_MAX_ADD_DATA_SIZE) {
throw new IOException(
"additionalData has to be at most " + INCFS_MAX_ADD_DATA_SIZE + " bytes");
}
-
- IncrementalSignature result = new IncrementalSignature();
- result.hashAlgorithm = INCFS_HASH_SHA256;
- result.rootHash = rootHash;
- result.additionalData = additionalData;
- result.signature = pkcs7Signature;
-
- return result;
}
/**
diff --git a/core/java/android/os/incremental/V4Signature.java b/core/java/android/os/incremental/V4Signature.java
index 6d334f5..71f931d 100644
--- a/core/java/android/os/incremental/V4Signature.java
+++ b/core/java/android/os/incremental/V4Signature.java
@@ -20,9 +20,12 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
+import java.io.EOFException;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
/**
* V4 signature fields.
@@ -31,30 +34,95 @@
*/
public class V4Signature {
public static final String EXT = ".idsig";
- public static final int SUPPORTED_VERSION = 1;
+ public static final int SUPPORTED_VERSION = 2;
- public final int version;
- public final byte[] verityRootHash;
- public final byte[] v3Digest;
- public final byte[] pkcs7SignatureBlock;
+ public static final int HASHING_ALGORITHM_SHA256 = 1;
+ public static final byte LOG2_BLOCK_SIZE_4096_BYTES = 12;
+
+ /**
+ * IncFS hashing data.
+ */
+ public static class HashingInfo {
+ public final int hashAlgorithm; // only 1 == SHA256 supported
+ public final byte log2BlockSize; // only 12 (block size 4096) supported now
+ public final byte[] salt; // used exactly as in fs-verity, 32 bytes max
+ public final byte[] rawRootHash; // salted digest of the first Merkle tree page
+
+ HashingInfo(int hashAlgorithm, byte log2BlockSize, byte[] salt, byte[] rawRootHash) {
+ this.hashAlgorithm = hashAlgorithm;
+ this.log2BlockSize = log2BlockSize;
+ this.salt = salt;
+ this.rawRootHash = rawRootHash;
+ }
+
+ /**
+ * Constructs HashingInfo from byte array.
+ */
+ public static HashingInfo fromByteArray(byte[] bytes) throws IOException {
+ ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
+ final int hashAlgorithm = buffer.getInt();
+ final byte log2BlockSize = buffer.get();
+ byte[] salt = readBytes(buffer);
+ byte[] rawRootHash = readBytes(buffer);
+ return new HashingInfo(hashAlgorithm, log2BlockSize, salt, rawRootHash);
+ }
+ }
+
+ /**
+ * V4 signature data.
+ */
+ public static class SigningInfo {
+ public final byte[] v3Digest; // used to match with the corresponding APK
+ public final byte[] certificate; // ASN.1 DER form
+ public final byte[] additionalData; // a free-form binary data blob
+ public final byte[] publicKey; // ASN.1 DER, must match the certificate
+ public final int signatureAlgorithmId; // see the APK v2 doc for the list
+ public final byte[] signature;
+
+ SigningInfo(byte[] v3Digest, byte[] certificate, byte[] additionalData,
+ byte[] publicKey, int signatureAlgorithmId, byte[] signature) {
+ this.v3Digest = v3Digest;
+ this.certificate = certificate;
+ this.additionalData = additionalData;
+ this.publicKey = publicKey;
+ this.signatureAlgorithmId = signatureAlgorithmId;
+ this.signature = signature;
+ }
+
+ /**
+ * Constructs SigningInfo from byte array.
+ */
+ public static SigningInfo fromByteArray(byte[] bytes) throws IOException {
+ ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
+ byte[] v3Digest = readBytes(buffer);
+ byte[] certificate = readBytes(buffer);
+ byte[] additionalData = readBytes(buffer);
+ byte[] publicKey = readBytes(buffer);
+ int signatureAlgorithmId = buffer.getInt();
+ byte[] signature = readBytes(buffer);
+ return new SigningInfo(v3Digest, certificate, additionalData, publicKey,
+ signatureAlgorithmId, signature);
+ }
+ }
+
+ public final int version; // Always 2 for now.
+ public final byte[] hashingInfo;
+ public final byte[] signingInfo; // Passed as-is to the kernel. Can be retrieved later.
/**
* Construct a V4Signature from .idsig file.
*/
public static V4Signature readFrom(ParcelFileDescriptor pfd) throws IOException {
- final ParcelFileDescriptor dupedFd = pfd.dup();
- final ParcelFileDescriptor.AutoCloseInputStream fdInputStream =
- new ParcelFileDescriptor.AutoCloseInputStream(dupedFd);
- try (DataInputStream stream = new DataInputStream(fdInputStream)) {
+ try (InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(pfd.dup())) {
return readFrom(stream);
}
}
/**
- * Construct a V4Signature from .idsig file.
+ * Construct a V4Signature from a byte array.
*/
public static V4Signature readFrom(byte[] bytes) throws IOException {
- try (DataInputStream stream = new DataInputStream(new ByteArrayInputStream(bytes))) {
+ try (InputStream stream = new ByteArrayInputStream(bytes)) {
return readFrom(stream);
}
}
@@ -63,51 +131,131 @@
* Store the V4Signature to a byte-array.
*/
public byte[] toByteArray() {
- try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
- try (DataOutputStream steam = new DataOutputStream(byteArrayOutputStream)) {
- this.writeTo(steam);
- steam.flush();
- }
- return byteArrayOutputStream.toByteArray();
+ try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
+ this.writeTo(stream);
+ return stream.toByteArray();
} catch (IOException e) {
return null;
}
}
- boolean isVersionSupported() {
+ /**
+ * Combines necessary data to a signed data blob.
+ * The blob can be validated against signingInfo.signature.
+ *
+ * @param fileSize - size of the signed file (APK)
+ */
+ public static byte[] getSigningData(long fileSize, HashingInfo hashingInfo,
+ SigningInfo signingInfo) {
+ final int size =
+ 4/*size*/ + 8/*fileSize*/ + 4/*hash_algorithm*/ + 1/*log2_blocksize*/ + bytesSize(
+ hashingInfo.salt) + bytesSize(hashingInfo.rawRootHash) + bytesSize(
+ signingInfo.v3Digest) + bytesSize(signingInfo.certificate) + bytesSize(
+ signingInfo.additionalData);
+ ByteBuffer buffer = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN);
+ buffer.putInt(size);
+ buffer.putLong(fileSize);
+ buffer.putInt(hashingInfo.hashAlgorithm);
+ buffer.put(hashingInfo.log2BlockSize);
+ writeBytes(buffer, hashingInfo.salt);
+ writeBytes(buffer, hashingInfo.rawRootHash);
+ writeBytes(buffer, signingInfo.v3Digest);
+ writeBytes(buffer, signingInfo.certificate);
+ writeBytes(buffer, signingInfo.additionalData);
+ return buffer.array();
+ }
+
+ public boolean isVersionSupported() {
return this.version == SUPPORTED_VERSION;
}
- static V4Signature readFrom(DataInputStream stream) throws IOException {
- final int version = stream.readInt();
- byte[] verityRootHash = readBytes(stream);
- byte[] v3Digest = readBytes(stream);
- byte[] pkcs7SignatureBlock = readBytes(stream);
- return new V4Signature(version, verityRootHash, v3Digest, pkcs7SignatureBlock);
- }
-
- V4Signature(int version, byte[] verityRootHash, byte[] v3Digest, byte[] pkcs7SignatureBlock) {
+ private V4Signature(int version, byte[] hashingInfo, byte[] signingInfo) {
this.version = version;
- this.verityRootHash = verityRootHash;
- this.v3Digest = v3Digest;
- this.pkcs7SignatureBlock = pkcs7SignatureBlock;
+ this.hashingInfo = hashingInfo;
+ this.signingInfo = signingInfo;
}
- void writeTo(DataOutputStream stream) throws IOException {
- stream.writeInt(this.version);
- writeBytes(stream, this.verityRootHash);
- writeBytes(stream, this.v3Digest);
- writeBytes(stream, this.pkcs7SignatureBlock);
+ private static V4Signature readFrom(InputStream stream) throws IOException {
+ final int version = readIntLE(stream);
+ final byte[] hashingInfo = readBytes(stream);
+ final byte[] signingInfo = readBytes(stream);
+ return new V4Signature(version, hashingInfo, signingInfo);
}
- private static byte[] readBytes(DataInputStream stream) throws IOException {
- byte[] result = new byte[stream.readInt()];
- stream.read(result);
- return result;
+ private void writeTo(OutputStream stream) throws IOException {
+ writeIntLE(stream, this.version);
+ writeBytes(stream, this.hashingInfo);
+ writeBytes(stream, this.signingInfo);
}
- private static void writeBytes(DataOutputStream stream, byte[] bytes) throws IOException {
- stream.writeInt(bytes.length);
+ // Utility methods.
+ private static int bytesSize(byte[] bytes) {
+ return 4/*length*/ + (bytes == null ? 0 : bytes.length);
+ }
+
+ private static void readFully(InputStream stream, byte[] buffer) throws IOException {
+ int len = buffer.length;
+ int n = 0;
+ while (n < len) {
+ int count = stream.read(buffer, n, len - n);
+ if (count < 0) {
+ throw new EOFException();
+ }
+ n += count;
+ }
+ }
+
+ private static int readIntLE(InputStream stream) throws IOException {
+ final byte[] buffer = new byte[4];
+ readFully(stream, buffer);
+ return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
+ }
+
+ private static void writeIntLE(OutputStream stream, int v) throws IOException {
+ final byte[] buffer = ByteBuffer.wrap(new byte[4]).order(ByteOrder.LITTLE_ENDIAN).putInt(
+ v).array();
+ stream.write(buffer);
+ }
+
+ private static byte[] readBytes(InputStream stream) throws IOException {
+ try {
+ final int size = readIntLE(stream);
+ final byte[] bytes = new byte[size];
+ readFully(stream, bytes);
+ return bytes;
+ } catch (EOFException ignored) {
+ return null;
+ }
+ }
+
+ private static byte[] readBytes(ByteBuffer buffer) throws IOException {
+ if (buffer.remaining() < 4) {
+ throw new EOFException();
+ }
+ final int size = buffer.getInt();
+ if (buffer.remaining() < size) {
+ throw new EOFException();
+ }
+ final byte[] bytes = new byte[size];
+ buffer.get(bytes);
+ return bytes;
+ }
+
+ private static void writeBytes(OutputStream stream, byte[] bytes) throws IOException {
+ if (bytes == null) {
+ writeIntLE(stream, 0);
+ return;
+ }
+ writeIntLE(stream, bytes.length);
stream.write(bytes);
}
+
+ private static void writeBytes(ByteBuffer buffer, byte[] bytes) {
+ if (bytes == null) {
+ buffer.putInt(0);
+ return;
+ }
+ buffer.putInt(bytes.length);
+ buffer.put(bytes);
+ }
}
diff --git a/core/java/android/os/storage/StorageManagerInternal.java b/core/java/android/os/storage/StorageManagerInternal.java
index a2def7f..f43a252 100644
--- a/core/java/android/os/storage/StorageManagerInternal.java
+++ b/core/java/android/os/storage/StorageManagerInternal.java
@@ -100,10 +100,11 @@
}
/**
- * Check if fuse is running in target user, if it's running then setup its obb directories.
- * TODO: System server should store a list of active pids that obb is not mounted and use it.
+ * Create storage directories if it does not exist.
+ * Return true if the directories were setup correctly, otherwise false.
*/
- public abstract void prepareObbDirs(int userId, Set<String> packageList, String processName);
+ public abstract boolean prepareStorageDirs(int userId, Set<String> packageList,
+ String processName);
/**
* Add a listener to listen to reset event in StorageManagerService.
diff --git a/core/java/android/permission/IPermissionController.aidl b/core/java/android/permission/IPermissionController.aidl
index 0483514..f011395 100644
--- a/core/java/android/permission/IPermissionController.aidl
+++ b/core/java/android/permission/IPermissionController.aidl
@@ -42,6 +42,6 @@
void setRuntimePermissionGrantStateByDeviceAdmin(String callerPackageName, String packageName,
String permission, int grantState, in AndroidFuture callback);
void grantOrUpgradeDefaultRuntimePermissions(in AndroidFuture callback);
- void updateUserSensitive(in AndroidFuture callback);
void notifyOneTimePermissionSessionTimeout(String packageName);
+ void updateUserSensitiveForApp(int uid, in AndroidFuture callback);
}
diff --git a/core/java/android/permission/IPermissionManager.aidl b/core/java/android/permission/IPermissionManager.aidl
index 2615c98..09df72c 100644
--- a/core/java/android/permission/IPermissionManager.aidl
+++ b/core/java/android/permission/IPermissionManager.aidl
@@ -106,4 +106,12 @@
int importanceToResetTimer, int importanceToKeepSessionAlive);
void stopOneTimePermissionSession(String packageName, int userId);
+
+ List<String> getAutoRevokeExemptionRequestedPackages(int userId);
+
+ List<String> getAutoRevokeExemptionGrantedPackages(int userId);
+
+ boolean setAutoRevokeWhitelisted(String packageName, boolean whitelisted, int userId);
+
+ boolean isAutoRevokeWhitelisted(String packageName, int userId);
}
diff --git a/core/java/android/permission/PermissionControllerManager.java b/core/java/android/permission/PermissionControllerManager.java
index 2a1857f..f08e3d25 100644
--- a/core/java/android/permission/PermissionControllerManager.java
+++ b/core/java/android/permission/PermissionControllerManager.java
@@ -46,6 +46,7 @@
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
+import android.os.Process;
import android.os.UserHandle;
import android.util.ArrayMap;
import android.util.Log;
@@ -626,14 +627,26 @@
}
/**
- * @see PermissionControllerService#onUpdateUserSensitive()
+ * @see PermissionControllerManager#updateUserSensitiveForApp
* @hide
*/
public void updateUserSensitive() {
+ updateUserSensitiveForApp(Process.INVALID_UID);
+ }
+
+ /**
+ * @see PermissionControllerService#onUpdateUserSensitiveForApp
+ * @hide
+ */
+ public void updateUserSensitiveForApp(int uid) {
mRemoteService.postAsync(service -> {
AndroidFuture<Void> future = new AndroidFuture<>();
- service.updateUserSensitive(future);
+ service.updateUserSensitiveForApp(uid, future);
return future;
+ }).whenComplete((res, err) -> {
+ if (err != null) {
+ Log.e(TAG, "Error updating user_sensitive flags for uid " + uid, err);
+ }
});
}
diff --git a/core/java/android/permission/PermissionControllerService.java b/core/java/android/permission/PermissionControllerService.java
index 263b2c7..4a42230 100644
--- a/core/java/android/permission/PermissionControllerService.java
+++ b/core/java/android/permission/PermissionControllerService.java
@@ -218,11 +218,14 @@
* Called by system to update the
* {@link PackageManager}{@code .FLAG_PERMISSION_USER_SENSITIVE_WHEN_*} flags for permissions.
* <p>
- * This is typically when creating a new user or upgrading either system or
- * permission controller package.
+ *
+ * If uid is -1, updates the permission flags for all packages.
+ *
+ * Typically called by the system when a new app is installed or updated or when creating a
+ * new user or upgrading either system or permission controller package.
*/
@BinderThread
- public void onUpdateUserSensitivePermissionFlags() {
+ public void onUpdateUserSensitivePermissionFlags(int uid, @NonNull Runnable callback) {
throw new AbstractMethodError("Must be overridden in implementing class");
}
@@ -459,11 +462,14 @@
}
@Override
- public void updateUserSensitive(AndroidFuture callback) {
+ public void updateUserSensitiveForApp(int uid, @NonNull AndroidFuture callback) {
Preconditions.checkNotNull(callback, "callback cannot be null");
- onUpdateUserSensitivePermissionFlags();
- callback.complete(null);
+ try {
+ onUpdateUserSensitivePermissionFlags(uid, () -> callback.complete(null));
+ } catch (Exception e) {
+ callback.completeExceptionally(e);
+ }
}
@Override
diff --git a/core/java/android/permission/PermissionManager.java b/core/java/android/permission/PermissionManager.java
index 0bd211d..8308bb3 100644
--- a/core/java/android/permission/PermissionManager.java
+++ b/core/java/android/permission/PermissionManager.java
@@ -40,11 +40,13 @@
import android.util.Slog;
import com.android.internal.annotations.Immutable;
+import com.android.internal.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
@@ -299,6 +301,46 @@
}
}
+ /**
+ * Gets the list of packages that have permissions that specified
+ * {@code requestDontAutoRevokePermissions=true} in their
+ * {@code application} manifest declaration.
+ *
+ * @return the list of packages for current user
+ * @hide
+ */
+ @SystemApi
+ @NonNull
+ @RequiresPermission(Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY)
+ public Set<String> getAutoRevokeExemptionRequestedPackages() {
+ try {
+ return CollectionUtils.toSet(mPermissionManager.getAutoRevokeExemptionRequestedPackages(
+ mContext.getUser().getIdentifier()));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Gets the list of packages that have permissions that specified
+ * {@code allowDontAutoRevokePermissions=true} in their
+ * {@code application} manifest declaration.
+ *
+ * @return the list of packages for current user
+ * @hide
+ */
+ @SystemApi
+ @NonNull
+ @RequiresPermission(Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY)
+ public Set<String> getAutoRevokeExemptionGrantedPackages() {
+ try {
+ return CollectionUtils.toSet(mPermissionManager.getAutoRevokeExemptionGrantedPackages(
+ mContext.getUser().getIdentifier()));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
private List<SplitPermissionInfo> splitPermissionInfoListToNonParcelableList(
List<SplitPermissionInfoParcelable> parcelableList) {
final int size = parcelableList.size();
diff --git a/core/java/android/permission/Permissions.md b/core/java/android/permission/Permissions.md
new file mode 100644
index 0000000..e62bd0a
--- /dev/null
+++ b/core/java/android/permission/Permissions.md
@@ -0,0 +1,832 @@
+<!--
+ Copyright (C) 2020 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
+ -->
+
+# Android permissions for system developers
+
+This document targets system developers. App developers should refer to the [public
+ documentation](https://developer.android.com/guide/topics/permissions/overview).
+
+## Definitions
+
+Each app (often called package) has a unique name called package name. Each package has a manifest
+file describing properties of the package. The android system server is in a special package named
+"android".
+
+When a package gets installed the package is (usually) assigned a unique identifier called [uid
+](../os/Users.md#int-uid).
+This is the same as a uid in Linux, but this often leads to confusion. It is easiest to see a uid
+as a unique identifier for a package.
+
+Usually an app is running in a container called a process. Each process has a unique id called
+pid, but unlike the uid the pid changes each time the process is restarted and app that are not
+currently running don't have a pid. The process container makes sure that other apps cannot
+negatively interact with an app. Processes can only interact via controlled interactions called
+remote procedure calls (RPCs). Android’s RPC mechanism is called _Binder_.
+
+As no app code can be trusted the permission need to be checked on the receiving side of the
+Binder call.
+
+For more details please take a look at [Android's security model](../os/Users.md#security-model).
+
+## Permissions for regular apps
+
+### Install time permissions
+
+The purpose of install time permissions is to control access to APIs where it does not makes sense
+to involve the user. This can be either because the API is not sensitive, or because additional
+checks exist.
+
+#### Defining a permission
+
+Any package can define a permission. For that it simply adds an entry in the manifest file
+`<permission android:name="com.example.myapp.myfirstpermission" />`
+
+Any package can do this, including the system package. When talking about [permissions for system
+ apps](#permissions-for-system-apps) we will see that it is important which package defines a
+permission.
+
+It is common good practice to prefix the permission name with the package name to avoid collisions.
+
+#### Requesting a permission
+
+Any app can request any permission via adding an entry in the manifest file like
+`<uses-permission android:name="com.example.myapp.myfirstpermission" />`
+
+A requested permission does not necessarily mean that the permission is granted. When and how a
+permission is granted depends on the protection level of the permission. If no protection level is
+set, the permission will always be granted. Such "normal" permissions can still be useful as it
+will be easy to find apps using a certain functionality on app stores and by checking `dumpsys
+package`.
+
+#### Checking a permission
+
+`Context.checkPermission(permission, pid, uid)` returns if the pid/uid has the permission. By far
+the most common case is to check the permission on the receiving end of a binder call. In this case
+the pid can be read as `Binder.callingPid()` and the uid as `Binder.callingUid()`. The uid is a
+mandatory argument as permissions are maintained per uid. The pid can be set to -1
+if not pid is available. The context class contains handy wrappers for `checkPermission`, such as
+`enforeCallingPermission` which calls checkPermission with `Binder.callingPid`/`Binder.callingUid`
+and throws a SecurityException when the permission is not granted.
+
+#### Verifying an app has an install time permission
+
+In `dumpsys package my.package.name` there are two sections. In requested permissions all
+permissions of the `uses-permission` tags are listed. In install permission the permissions with
+their grant state are listed. If an install time permission is not listed here, it is not granted.
+
+```
+Packages:
+ Package [com.android.packageinstaller] (2eb7062):
+ userId=10071
+ [...]
+ requested permissions:
+ android.permission.MANAGE_USERS
+ android.permission.INSTALL_PACKAGES
+ android.permission.DELETE_PACKAGES
+ android.permission.READ_INSTALL_SESSIONS
+ android.permission.RECEIVE_BOOT_COMPLETED
+ android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS
+ android.permission.USE_RESERVED_DISK
+ android.permission.UPDATE_APP_OPS_STATS
+ android.permission.MANAGE_APP_OPS_MODES
+ android.permission.INTERACT_ACROSS_USERS_FULL
+ android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME
+ android.permission.PACKAGE_USAGE_STATS
+ install permissions:
+ android.permission.USE_RESERVED_DISK: granted=true
+ android.permission.INSTALL_PACKAGES: granted=true
+ android.permission.RECEIVE_BOOT_COMPLETED: granted=true
+ android.permission.INTERACT_ACROSS_USERS_FULL: granted=true
+ android.permission.PACKAGE_USAGE_STATS: granted=true
+ android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME: granted=true
+ android.permission.READ_INSTALL_SESSIONS: granted=true
+ android.permission.MANAGE_USERS: granted=true
+ android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS: granted=true
+ android.permission.MANAGE_APP_OPS_MODES: granted=true
+ android.permission.UPDATE_APP_OPS_STATS: granted=true
+ android.permission.DELETE_PACKAGES: granted=true
+```
+
+#### End-to-end: Protecting an RPC call via a permission
+
+##### Service Manifest
+
+```xml
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.example.myservice">
+ <!-- Define a permission -->
+ <permission android:name="com.android.example.myservice.MY_PERMISSION" />
+ <application>
+ <service android:name=".MyService" android:exported="true" />
+ </application>
+</manifest>
+```
+
+##### Service code
+
+```kotlin
+class MyService : Service() {
+ override fun onBind(intent: Intent?): IBinder? {
+ return object : IMyService.Stub() {
+ override fun doSomething() {
+ // Verify that calling UID has the permission
+ enforceCallingPermission(
+ "com.android.example.myservice.MY_PERMISSION",
+ "Need to hold permission"
+ )
+ // do something
+ }
+ }.asBinder()
+ }
+}
+```
+
+##### Caller Manifest
+
+```xml
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.example.myapp">
+ <!-- request a permission -->
+ <uses-permission android:name="com.android.example.myservice.MY_PERMISSION" />
+ <application />
+</manifest>
+```
+
+### Runtime permissions
+
+Runtime permission must be granted by the user during runtime. This is needed if the API protects
+data or functionality that is sensitive for the user. E.g. the users current location is protected
+by a runtime permission.
+
+Users want a system that is secure and privacy focused by default. User can also often not make a
+good choice when asked at the wrong time without enough context. Hence in general runtime
+permissions should be avoided and the API should be built in a way where no private data needs to be
+leaked.
+
+#### Defining a runtime permission
+
+Runtime permissions are defined in the same way as install time permissions. To tag them as runtime
+permissions the `protectionLevel` needs to be set to dangerous. Dangerous is a synonym for
+runtime permissions in the Android platform.
+
+```xml
+<uses-permission android:name="com.example.myapp.myfirstruntimepermission"
+ android:protectionLevel="dangerous" />
+```
+
+#### Requesting a runtime permission
+
+Similar to install time permissions any app can request a runtime permission by adding the
+`<uses-permission android:name="com.example.myapp.myfirstruntimepermission" />`
+to the manifest.
+
+By default runtime permissions are not granted. The app needs to call `Activity.requestPermissions`
+during runtime to ask the user for the permission. The user might then grant or deny and once the
+decision is made the activity is called by via `Activity.onPermissionGranted`.
+
+During development and testing a runtime permission can be granted via the `pm` shell command or by
+using the `UiAutomator.grantRuntimePermission` API call. Please note that this does _not_ grant the
+[app-op](#runtime-permissions-and-app-ops) synchronously. Unless the app needs to test the actual
+permission grant flow it is recommended to grant the runtime permissions during install using
+`adb install -g /my/package.apk`.
+
+#### Checking a runtime permission
+
+For runtime permissions defined by a 3rd party apps it is fine to check a runtime
+permission like an install time permission. For system defined permissions you need to check all
+runtime permissions by using the `PermissionChecker` utility. It is good practice to use the tool
+anywhere possible.
+
+The permission checker might return `PERMISSION_DENIED_APP_OP` which should lead to a silent
+failure. This can only happen for system defined runtime permissions.
+
+##### Runtime permissions and app-ops
+
+> See [App-ops](../app/AppOps.md).
+
+The PermissionChecker code fundamentally looks like this:
+
+```kotlin
+class PermissionChecker {
+ fun checkCallingPermission(context: Context, permission: String) {
+ if (isRuntimePermission(permission)) {
+ if (context.checkPermission(uid, permission) == DENIED) {
+ return PERMISSION_DENIED
+ }
+
+ val appOpOfPermission = AppOpsManager.permissionToOp(permission)
+ if (appOpOfPermission == null) {
+ // not platform defined
+ return PERMISSION_GRANTED
+ }
+
+ val appOpMode = appOpsManager.noteOp(appOpOfPermission)
+ if (appOpMode == AppOpsManager.MODE_ALLOWED) {
+ return PERMISSION_GRANTED
+ } else {
+ return PERMISSION_DENIED_APP_OP
+ }
+ } else {
+ return PERMISSION_DENIED
+ }
+ }
+}
+```
+
+For each platform defined runtime permission there is a matching app-op. When calling
+`AppOpsManager.noteOp` this returns either `MODE_ALLOWED` or `MODE_IGNORED`.
+
+This value is then used to decide between `PERMISSION_DENIED_APP_OP` and `PERMISSION_GRANTED`.
+
+The primary purpose of the special `PERMISSION_DENIED_APP_OP` state was to support apps targeting an
+SDK lower than 23. These apps do not understand the concept of denied runtime permissions. Hence
+they would crash when getting a `SecurityException`. To protect the users' privacy while still not
+crashing the app the special `PERMISSION_DENIED_APP_OP` mandates that the API should somehow
+silently fail.
+
+A secondary use case of the `AppOpsManager.noteOp` calls is to
+[track](../app/AppOps.md#Appops-for-tracking) which apps perform what runtime protected actions.
+
+#### Verifying an app has a runtime time permission
+
+In `dumpsys package my.package.name` the runtime permissions are listed per uid. I.e. different
+users might have different runtime permission grants and shared uids share a grant-set. If a runtime
+permission is listed as requested but not in the runtime permission section it is in it’s initial
+state, i.e. not granted.
+
+```
+Packages:
+ Package [com.google.android.GoogleCamera] (ccb6af):
+ userId=10181
+ [...]
+ requested permissions:
+ android.permission.ACCESS_COARSE_LOCATION
+ android.permission.ACCESS_FINE_LOCATION
+ android.permission.ACCESS_NETWORK_STATE
+ android.permission.ACCESS_NOTIFICATION_POLICY
+ android.permission.ACCESS_WIFI_STATE
+ android.permission.BIND_WALLPAPER
+ android.permission.CAMERA
+ android.permission.CHANGE_WIFI_STATE
+ android.permission.INTERNET
+ android.permission.GET_PACKAGE_SIZE
+ android.permission.NFC
+ android.permission.READ_SYNC_SETTINGS
+ android.permission.RECEIVE_BOOT_COMPLETED
+ android.permission.RECORD_AUDIO
+ android.permission.SET_WALLPAPER
+ android.permission.USE_CREDENTIALS
+ android.permission.VIBRATE
+ android.permission.WAKE_LOCK
+ android.permission.WRITE_EXTERNAL_STORAGE [ ... ]
+ android.permission.WRITE_SETTINGS
+ android.permission.WRITE_SYNC_SETTINGS
+ com.google.android.elmyra.permission.CONFIGURE_ASSIST_GESTURE
+ com.google.android.providers.gsf.permission.READ_GSERVICES
+ android.permission.FOREGROUND_SERVICE
+ com.google.android.googlequicksearchbox.permission.LENSVIEW_BROADCAST
+ android.permission.READ_EXTERNAL_STORAGE [ ... ]
+ [...]
+ User 0: [ ... ]
+ overlay paths:
+ runtime permissions:
+ android.permission.ACCESS_FINE_LOCATION: granted=false [ ... ]
+ android.permission.READ_EXTERNAL_STORAGE: granted=true [ ... ]
+ android.permission.ACCESS_COARSE_LOCATION: granted=false [ ... ]
+ android.permission.CAMERA: granted=true [ ... ]
+ android.permission.WRITE_EXTERNAL_STORAGE: granted=true [ ... ]
+ android.permission.RECORD_AUDIO: granted=true[ ... ]
+```
+
+#### End-to-end: Protecting an RPC call via a runtime permission
+
+##### Service Manifest
+
+```xml
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.example.myservice">
+ <!-- Define a runtime permission -->
+ <permission android:name="com.android.example.myservice.MY_RUNTIME_PERMISSION"
+ android:protectionLevel="dangerous" />
+ <application>
+ <service android:name=".MyService" android:exported="true" />
+ </application>
+</manifest>
+```
+
+##### Service code
+
+```kotlin
+class MyService : Service() {
+ override fun onBind(intent: Intent?): IBinder? {
+ return object : IMyService.Stub() {
+ override fun doSomething(callingPackage: String?, callingFeatureId: String?) {
+ Objects.requireNonNull(callingPackageName)
+
+ // Verify that calling UID has the permission
+ when (run {
+ PermissionChecker.checkCallingPermission(
+ this@MyService,
+ "com.android.example.myservice.MY_RUNTIME_PERMISSION",
+ callingPackageName,
+ callingFeatureId,
+ "Did something"
+ )
+ }) {
+ PERMISSION_GRANTED -> /* do something */
+ PERMISSION_DENIED_APP_OP -> /* silent failure, do nothing */
+ else -> throw SecurityException(
+ "Cannot do something as caller is missing "
+ + "com.android.example.myservice.MY_RUNTIME_PERMISSION"
+ )
+ }
+ }
+ }.asBinder()
+ }
+}
+```
+
+##### Caller Manifest
+
+```xml
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.example.myapp">
+ <!-- request a permission -->
+ <uses-permission android:name="com.android.example.myservice.MY_RUNTIME_PERMISSION" />
+ <application />
+</manifest>
+```
+
+##### Caller code
+
+```kotlin
+class MyActivity : Activity {
+ fun callDoSomething() {
+ if (checkSelfPermission("com.android.example.myservice.MY_RUNTIME_PERMISSION") == PERMISSION_DENIED) {
+ // Interrupt operation and request permission
+ requestPermissions(arrayOf("com.android.example.myservice.MY_RUNTIME_PERMISSION"), 23)
+ } else {
+ myService.doSomething(this@MyActivity.opPackageName, this@MyActivity.featureId)
+ }
+ }
+
+ override fun onRequestPermissionsResult(
+ requestCode: Int,
+ permissions: Array<String>,
+ grantResults: IntArray
+ ) {
+ if (requestCode == 23 && grantResults[0] == PERMISSION_GRANTED) {
+ // Finish operation
+ callDoSomething()
+ }
+ }
+}
+```
+
+#### Restricted permissions
+
+Some runtime permissions are restricted. They are annotated in the platforms `AndroidManifest.xml`
+has `hardRestricted` or `softRestricted`.
+
+Restricted permissions behave uncommon when not whitelisted. When whitelisted the permissions
+behave normally. What uncommon means depends on the whether they are hard or soft restricted.
+
+They can either be whitelisted during upgrade P->Q, but the system or need to be whitelisted by the
+installer via `PackageInstaller.SessionParams.setWhitelistedRestrictedPermissions`. If this method
+is not used all permissions will be whitelisted.
+
+Afterwards the app that originally installed the app can change the whitelisting state via
+`PackageManager.addWhitelistedRestrictedPermission` and
+`PackageManager.removeWhitelistedRestrictedPermission`.
+
+The system tracks the source of the whitelisting by having three different flags
+ `RESTRICTION_SYSTEM_EXEMPT`, `RESTRICTION_UPGRADE_EXEMPT`, and `RESTRICTION_INSTALLER_EXEMPT`,
+
+The flags can be checked in `dumpsys package my.package.name`
+
+```
+User 0:
+ [...]
+ runtime permissions:
+ android.permission.READ_EXTERNAL_STORAGE: granted=false, flags=[ RESTRICTION_UPGRADE_EXEMPT ]
+ android.permission.ACCESS_FINE_LOCATION: granted=true, flags=[ RESTRICTION_SYSTEM_EXEMPT|RESTRICTION_UPGRADE_EXEMPT ]
+```
+
+##### Hard restricted
+
+Hard restricted permissions need to be whitelisted to be grant-able.
+
+##### Soft restricted
+
+The behavior of non-whitelisted soft restricted permissions is not uniform. The behavior is
+defined in the `SoftRestrictedPermissionPolicy`.
+
+#### System fixed permission
+
+Some runtime permissions are required for normal operation of the device. In this case the system
+can grant the permission as `SYSTEM_FIXED`. In this case the permission can be seen in the
+[permission management settings](#settings) but cannot be revoked by the user.
+
+The flag can be checked in `dumpsys package my.package.name`
+```
+User 0:
+ [...]
+ runtime permissions:
+ android.permission.READ_EXTERNAL_STORAGE: granted=true, flags=[ SYSTEM_FIXED|GRANTED_BY_DEFAULT ]
+```
+
+#### Background access
+
+Whether the app is currently visible to the user is reflected in the `ActivityManager`'s proc state.
+There is a lot of granularity to this, but runtime permissions are using the [app-ops services'
+](../app/AppOps.md) definition of foreground and background.
+
+Most runtime permissions are not affected by foreground/background-ness. Microphone and Camera are
+foreground-only while Location is usually foreground-only, but background access can be added by
+granting the `ACCESS_BACKGROUND_LOCATION` modifier runtime permission.
+
+##### Microphone and Camera
+
+Currently these only allow access while in the app is in foreground. There is a manual whitelist
+for e.g. the voice interaction service.
+
+This is currently (Mar 2020) reworked and will behave like [location](#location) soon.
+
+##### Location
+
+As described [above](#runtime-permissions-and-app-ops) the app-op mode for granted permissions is
+`MODE_ALLOWED` to allow access or `MODE_IGNORED` to suppress access.
+
+The important case is the case where the permission is granted and the app-op is `MODE_IGNORED`. In
+the case of location this state causes the `LocationManagerService` to stop delivering locations to
+the app. This is not a breaking behavior as the same scenarios happens if e.g. no satellites
+could be found.
+
+This behavior is used to implement the foregound/background behavior for location. If the app is
+in the foreground the app-op mode is `MODE_ALLOWED` and works normally. If the app goes into
+background the app-op mode changes to `MODE_IGNORED`. This means that locations are delivered while
+the app is in foreground and while the app is background, the app won't get any locations.
+
+The automatic switching between `MODE_ALLOWED` and `MODE_IGNORED` is done inside of
+ [`AppOpsManager`](../app/AppOps.md#foreground).
+
+Background access can be enabled by also granting the `ACCESS_BACKGROUND_LOCATION` to the app. In
+this case the app-op mode will always be `MODE_ALLOWED`.
+
+#### UI
+
+##### Granting
+
+An app following the best practices does not ask for any runtime permissions until absolutely
+needed. Once needed the request should be made in context. I.e. the user should understand from the
+current state of the app and the user's action why the request is made. E.g. if the user presses
+a "show me the next ATM"-button the user is most likely expecting a request for the location
+permission.
+
+This is central premise to the runtime permission UI. It is the app's responsibility to avoid
+showing permission requests dialogs to the user which might get denied. These dialogs are not
+meant to be user-choices, they are meant to be user-confirmations.
+
+Hence any denied permission dialog is probably due to the app asking for permissions the user
+does not expect. If too many permission requests get denied the app is apparently trying to get
+more than the user wants to give to the app. In this case the permission gets permanently denied
+and all future requests will be denied automatically without showing a UI.
+
+`Context.requestPermission` calls for more than one permission are allowed and might result in
+multiple dialogs in sequence. This might make sense for e.g. getting microphone and camera
+permission when starting a video call.
+
+Each time the the user makes a choice (either to grant or the deny) a permission request the
+permission is marked as `USER_SET`. If a permission gets permanently denied the permission is marked
+as `USER_FIXED`.
+
+This can be found in `dumpsys package my.package.name`
+```
+User 0:
+ [...]
+ runtime permissions:
+ android.permission.READ_EXTERNAL_STORAGE: granted=false, flags=[ USER_SET|USER_FIXED ]
+ android.permission.ACCESS_FINE_LOCATION: granted=true, flags=[ USER_SET ]
+```
+
+##### Settings
+
+By far most interactions with the permission system are via the [permission grant flow](#granting).
+The main purpose of the permission settings is to show the user the previous choices and allow
+the user to revisit previous choices. In reality few users do that.
+
+##### Grouping
+
+There are too many runtime permissions for the user to individually manage. Hence the UI bundles the
+permissions into groups. **Apps should never assume the grouping**. The grouping might change
+with SDK updates, but also at any other time. Certain form factors or locales might use other
+permission models and sometimes some of the permissions of a group cannot be granted for various
+reasons. The grouping is defined inside the permission controller app.
+
+If two permissions belong to a group and the first permission is already granted the second one
+will be granted on request of the app without user interaction. For that reason a permission
+group with at least one individual permission granted will show up as granted in the UI.
+
+##### Alternate permission management
+
+It is not allowed to build alternate permission management UIs. While restricting innovation is not
+a good choice this is a required one to enforce a consistent, predictable, but flexible permission
+model for users and app developers.
+
+Further some data needed for permission management (e.g. the grouping) is not available outside
+the permission controller app.
+
+Hence all permission management UI needs to be integrated with AOSP.
+
+#### Pre granting
+
+Runtime permissions protect user private data. It is a violation of user trust to give the data
+to an app without explicit user consent (i.e. the user [granting](#granting) the permission
+). Still the user expects certain functionality (e.g. receiving a phone call) to work out of the
+box.
+
+Hence the `DefaultPermissionGrantPolicy` and roles allow to grant permission without the user
+. The default permission grant policy grants permissions for three categories of apps
+- Apps running in well defined [uids](../os/Users.md#int-uid) as they are considered as part of
+ the platform
+- Apps that are in certain predefined categories, e.g. the browser and the SMS app. This is
+ meant for the most basic phone functionality, not for all pre-installed apps.
+- Apps that are explicitly mentioned as a pre-grant-exceptions. This is meant to be used for setup
+ and other highly critical use cases, not to improve the user experience. The exceptions are listed
+ in xml files in `etc/` and follow the following syntax
+```xml
+<exceptions>
+ <exception package="my.package.name">
+ <permission name="android.permission.ACCESS_FINE_LOCATION" fixed="false"/>
+ </exception>
+</exceptions>
+```
+
+Pre-granted runtime permissions can still be revoked by the user in [settings](#settings) unless
+they are granted as `SYSTEM_FIXED`.
+
+Whether a permission was granted by the default can be checked in the permission flags of
+`dumpsys package my.package.name`
+
+```
+User 0:
+ [...]
+ runtime permissions:
+ android.permission.ACCESS_FINE_LOCATION: granted=true, flags=[ GRANTED_BY_DEFAULT ]
+```
+
+### Permission restricted components
+
+As [publicly documented](https://developer.android.com/guide/topics/permissions/overview#permission_enforcement)
+it is possible to restrict starting an activity/binding to a service by using permission. It is
+a common pattern to
+
+- define a permission in the platform as `signature`
+- protect a service in an app by this permission using the `android:permission` attribute of the
+ `<service>` tag
+
+Then it is guaranteed that only the system can bind to such service. This is used for services
+that provide extensions to platform functionality, such as auto-fill services, print services, and
+accessibility services.
+
+This does not work for app-op or runtime permissions as the way to check these permissions is
+more complex than install time permissions.
+
+## Permissions for system apps
+
+System apps need to integrate deeper with the system than regular apps. Hence they need to be
+able to call APIs not available to other apps. This is implemented by granting permissions to
+these system apps and then enforcing the permissions in the API similar to other [install time
+permissions](#checking-a-permission).
+
+System apps are not different from regular apps, but the protection levels (e.g.
+[privileged](#privileged-permissions), [preinstalled](#preinstalled-permissions)) mentioned in this
+section are more commonly used by system apps.
+
+### Multiple permission levels
+
+It is possible to assign multiple protection levels to a permission. Very common combinations are
+for example adding `signature` to all permissions to make sure the platform signed apps can be
+granted the permission, e.g. `privileged|signature`.
+
+The permission will be granted if the app qualifies for _any_ of the permission levels.
+
+### App-op permissions
+
+> See [App-ops](../app/AppOps.md).
+
+App-op permissions are user-switchable permissions that are not runtime permissions. This should
+be used for permissions that are really only meant to be ever granted to a very small amount of
+apps. Traditionally granting these permissions is intentionally very heavy weight so that the
+user really needs to understand the use case. For example one use case is the
+`INTERACT_ACROSS_PROFILES` permission that allows apps of different
+[user profiles](../os/Users.md#user-profile) to interact. Of course this is breaking a very basic
+security container and hence should only every be granted with a lot of care.
+
+**Warning:** Most app-op permissions follow this logic, but most of them also have exceptions
+and special behavior. Hence this section is a guideline, not a rule.
+
+#### Defining an app-op permission
+
+Only the platform can reasonably define an app-op permission. The permission is defined in the
+platforms manifest using the `appop` protection level
+
+```xml
+<manifest package="android">
+ <permission android:name="android.permission.MY_APPOP_PERMISSION"
+ android:protectionLevel="appop|signature" />
+</manifest>
+```
+
+Almost always the protection level is app-op | something else, like
+[signature](#signature-permissions) (in the case above) or [privileged](#privileged-permissions).
+
+#### Checking a app-op permission
+
+The `PermissionChecker` utility can check app-op permissions with the [same syntax as runtime
+permissions](#checking-a-runtime-permission).
+
+The permission checker internally follows this flow
+
+```kotlin
+class PermissionChecker {
+ fun checkCallingPermission(context: Context, permission: String) {
+ if (isAppOpPermission(permission)) {
+ val appopOfPermission = AppOpsManager.permissionToOp(permission)
+ if (appopOfPermission == null) {
+ // not platform defined
+ return PERMISSION_DENIED
+ }
+
+ val appopMode = appOpsManager.noteOp(appopOfPermission)
+ when (appopMode) {
+ AppOpsManager.MODE_ALLOWED -> return PERMISSION_GRANTED
+ AppOpsManager.MODE_IGNORED -> return PERMISSION_DENIED
+ AppOpsManager.MODE_DEFAULT -> {
+ if (context.checkPermission(uid, permission) == GRANTED) {
+ return PERMISSION_GRANTED
+ } else {
+ return PERMISSION_DENIED
+ }
+ }
+ }
+ } else {
+ return PERMISSION_DENIED
+ }
+ }
+}
+```
+
+#### Granting a app-op permission
+
+The permission's grant state is only considered if the app-op's mode is `MODE_DEFAULT`. This
+allows to have default grants while still being overridden by the app-op.
+
+The permission is then granted by setting the app-op mode. This is usually done via dedicated APIs
+for each use cases. Similarly whether and how an app can request the permission is different for
+each app-op permission.
+
+When implementing a new app-op permission, make sure to set the app-op mode using `AppOpsManager
+.setUidMode` to make sure the permission is granted on the uid as this is the security domain.
+
+During development app-ops can be grated to app via the `appops set` shell command. E.g.
+
+```
+adb shell appops set 10187 INTERACT_ACROSS_PROFILES allow
+```
+
+sets the `INTERACT_ACROSS_PROFILES` app-op for uid 10187 to allow thereby granting apps in this
+uid the ability to interact across profiles.
+
+##### UI
+
+Most UIs for app-op permissions are in the "Special app access" section of the settings app.
+
+In most cases the permission should only be granted with the user's explicit agreement, usually by
+allowing the app to directly open the "Special app access" page for this permission and app.
+
+To repeat: this is a guideline for app-op permissions and there are many exceptions.
+
+### Signature permissions
+
+Only apps signed with the defining app's certificate will be granted the permission. This is
+used to restrict APIs to apps of the same developer.
+
+This is frequently used to restrict permissions defined by the platform to apps also signed with
+the platform's certificate. As this is a very tight restriction this is recommended for
+permissions that are only used by apps built out of AOSP which are signed with the platform
+certificate.
+
+Please note that OEMs sign their platform them self. I.e. OEMs can implement new apps using these
+permissions. It is unlikely that 3rd party apps will be able to use APIs protected by signature
+permissions as they are usually not signed with the platform certificate.
+
+Such permissions are defined and checked like an install time permission.
+
+### Preinstalled permissions
+
+This means that the app has to be pre-installed. There is no restriction what apps are pre-installed
+on a particular device install there. Hence it can be really any app including 3rd party apps.
+
+Hence this permission level is discouraged unless there are
+[further restrictions](#restricted-by-tests).
+
+Such permissions are defined and checked like an install time permission.
+
+### Privileged permissions
+
+This means that the app has to be pre-installed and in the `system/priv` directory in the
+filesystem. There is no restriction what apps are in this directory on a particular device
+install there. Hence it can be really any app including 3rd party apps.
+
+An app is only ever granted privileged permissions requested by the pre-installed apk. I.e.
+privileged permissions added in updates will never be granted.
+
+Hence this permission level is discouraged unless there are
+[further restrictions](#restricted-by-tests).
+
+Such permissions are defined and checked like an install time permission.
+
+#### Restricted by tests
+
+As all apps that might get preinstalled or privilidged permissions need to be pre-installed and new
+images need to pass compliance tests it is possible to use a test to whitelist the apps that can
+request the permission.
+
+Example of such a test:
+```kotlin
+/* Add new whitelisted packages to this list */
+private val whitelistedPkgs = listOf("my.whitelisted.package")
+
+@Test
+fun onlySomeAppsAreAllowedToHavePermissionGranted() {
+ assertThat(whitelistedPkgs).containsAllIn(
+ context.packageManager.getInstalledPackages(MATCH_ALL)
+ .filter { pkg ->
+ context.checkPermission(android.Manifest.permission.MY_PRIVILEGED_PERMISSION, -1,
+ pkg.applicationInfo.uid) == PERMISSION_GRANTED
+ /* The permission is defined by the system and hence granted to it */
+ }.filter { pkg -> pkg.applicationInfo.uid != SYSTEM_UID }
+ .map { it.packageName }
+ )
+}
+```
+
+#### Whitelist
+
+As mentioned above it is not suggested, but still common practice to install 3rd party apps as
+privilidged. To verify and restrict which privilidged permissions those apps get granted all
+privilidged permissions need to be explicitly whitelisted in a file `/etc`.
+
+```xml
+<permissions>
+ <privapp-permissions package="my.privileged.package">
+ <!-- allow the app to request a permission -->
+ <permission name="android.permission.MY_PRIVILEGED_PERMISSION"/>
+
+ <!-- Even though the app requests the permission, do not grant it -->
+ <deny-permission name="android.permission.MY_OTHER_PRIVILEGED_PERMISSION"/>
+ </privapp-permissions>
+</permissions>
+```
+
+If the pre-installed apk of app requests a privileged permission that is not mentioned in any
+whitelist or that is not denied the system will refuse to boot. As mentioned above privileged
+permissions added in updates to the pre-installed app will never be granted.
+
+### Limited permissions
+
+E.g. installer, wellbeing, documenter, etc... This allows the system to restrict the permission to a
+well defined app or set of apps. It is possible to add new types in `PackageManagerService`.
+
+Which apps qualify for such a permission level is flexible and custom for each such level. Usually
+they refer to a single or small set of apps, usually - but not always - apps defined in AOSP.
+
+These permissions are defined and checked like an install time permission.
+
+### Development permissions
+
+> Not recommended
+
+By adding the `development` protection level to any permissions the permission can be granted via
+the `pm grant` shell command. This appears to be useful for development and testing, but it is very
+highly discouraged. Any user can grant them permanently via adb, hence adding this tag removes
+all guarantees the permission might otherwise provide.
+
+### Other protection levels
+
+There are other levels (such as `runtime`) but they are for special purposes on should not be
+used by platform developers.
diff --git a/core/java/android/provider/BlockedNumberContract.java b/core/java/android/provider/BlockedNumberContract.java
index 1eb7664..dd2ea81 100644
--- a/core/java/android/provider/BlockedNumberContract.java
+++ b/core/java/android/provider/BlockedNumberContract.java
@@ -16,7 +16,6 @@
package android.provider;
import android.annotation.IntDef;
-import android.annotation.SystemApi;
import android.annotation.WorkerThread;
import android.content.Context;
import android.net.Uri;
@@ -240,7 +239,6 @@
* blocked.
* @hide
*/
- @SystemApi
public static final int STATUS_NOT_BLOCKED = 0;
/**
@@ -248,7 +246,6 @@
* because it is in the list of blocked numbers maintained by the provider.
* @hide
*/
- @SystemApi
public static final int STATUS_BLOCKED_IN_LIST = 1;
/**
@@ -256,7 +253,6 @@
* because it is from a restricted number.
* @hide
*/
- @SystemApi
public static final int STATUS_BLOCKED_RESTRICTED = 2;
/**
@@ -264,7 +260,6 @@
* because it is from an unknown number.
* @hide
*/
- @SystemApi
public static final int STATUS_BLOCKED_UNKNOWN_NUMBER = 3;
/**
@@ -272,7 +267,6 @@
* because it is from a pay phone.
* @hide
*/
- @SystemApi
public static final int STATUS_BLOCKED_PAYPHONE = 4;
/**
@@ -280,14 +274,12 @@
* because it is from a number not in the users contacts.
* @hide
*/
- @SystemApi
public static final int STATUS_BLOCKED_NOT_IN_CONTACTS = 5;
/**
* Integer reason indicating whether a call was blocked, and if so why.
* @hide
*/
- @SystemApi
public static final String RES_BLOCK_STATUS = "block_status";
/** @hide */
@@ -298,31 +290,6 @@
"can_current_user_block_numbers";
/** @hide */
- @SystemApi
- public static final String METHOD_NOTIFY_EMERGENCY_CONTACT = "notify_emergency_contact";
-
- /** @hide */
- public static final String METHOD_END_BLOCK_SUPPRESSION = "end_block_suppression";
-
- /** @hide */
- @SystemApi
- public static final String METHOD_SHOULD_SYSTEM_BLOCK_NUMBER = "should_system_block_number";
-
- /** @hide */
- public static final String METHOD_GET_BLOCK_SUPPRESSION_STATUS =
- "get_block_suppression_status";
-
- /** @hide */
- public static final String METHOD_SHOULD_SHOW_EMERGENCY_CALL_NOTIFICATION =
- "should_show_emergency_call_notification";
-
- /** @hide */
- public static final String METHOD_GET_ENHANCED_BLOCK_SETTING = "get_enhanced_block_setting";
-
- /** @hide */
- public static final String METHOD_SET_ENHANCED_BLOCK_SETTING = "set_enhanced_block_setting";
-
- /** @hide */
public static final String RES_CAN_BLOCK_NUMBERS = "can_block";
/** @hide */
@@ -439,11 +406,26 @@
public static final String ACTION_BLOCK_SUPPRESSION_STATE_CHANGED =
"android.provider.action.BLOCK_SUPPRESSION_STATE_CHANGED";
+ public static final String METHOD_NOTIFY_EMERGENCY_CONTACT = "notify_emergency_contact";
+
+ public static final String METHOD_END_BLOCK_SUPPRESSION = "end_block_suppression";
+
+ public static final String METHOD_SHOULD_SYSTEM_BLOCK_NUMBER = "should_system_block_number";
+
+ public static final String METHOD_GET_BLOCK_SUPPRESSION_STATUS =
+ "get_block_suppression_status";
+
+ public static final String METHOD_SHOULD_SHOW_EMERGENCY_CALL_NOTIFICATION =
+ "should_show_emergency_call_notification";
+
public static final String RES_IS_BLOCKING_SUPPRESSED = "blocking_suppressed";
public static final String RES_BLOCKING_SUPPRESSED_UNTIL_TIMESTAMP =
"blocking_suppressed_until_timestamp";
+ public static final String METHOD_GET_ENHANCED_BLOCK_SETTING = "get_enhanced_block_setting";
+ public static final String METHOD_SET_ENHANCED_BLOCK_SETTING = "set_enhanced_block_setting";
+
/* Preference key of block numbers not in contacts setting. */
public static final String ENHANCED_SETTING_KEY_BLOCK_UNREGISTERED =
"block_numbers_not_in_contacts_setting";
diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java
index 505d4ca..fb81d67 100644
--- a/core/java/android/provider/DeviceConfig.java
+++ b/core/java/android/provider/DeviceConfig.java
@@ -111,6 +111,14 @@
public static final String NAMESPACE_AUTOFILL = "autofill";
/**
+ * Namespace for blobstore feature that allows apps to share data blobs.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static final String NAMESPACE_BLOBSTORE = "blobstore";
+
+ /**
* Namespace for all networking connectivity related features.
*
* @hide
@@ -391,6 +399,13 @@
public static final String NAMESPACE_CONNECTIVITY_THERMAL_POWER_MANAGER =
"connectivity_thermal_power_manager";
+ /**
+ * Namespace for configuration related features.
+ *
+ * @hide
+ */
+ public static final String NAMESPACE_CONFIGURATION = "configuration";
+
private static final Object sLock = new Object();
@GuardedBy("sLock")
private static ArrayMap<OnPropertiesChangedListener, Pair<String, Executor>> sListeners =
diff --git a/core/java/android/provider/DocumentsContract.java b/core/java/android/provider/DocumentsContract.java
index 47f2461..a10a456 100644
--- a/core/java/android/provider/DocumentsContract.java
+++ b/core/java/android/provider/DocumentsContract.java
@@ -22,6 +22,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
+import android.annotation.TestApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentInterface;
import android.content.ContentProvider;
@@ -1303,6 +1304,7 @@
* {@hide}
*/
@SystemApi
+ @TestApi
public static @NonNull Uri setManageMode(@NonNull Uri uri) {
Preconditions.checkNotNull(uri, "uri can not be null");
return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build();
@@ -1314,6 +1316,7 @@
* {@hide}
*/
@SystemApi
+ @TestApi
public static boolean isManageMode(@NonNull Uri uri) {
Preconditions.checkNotNull(uri, "uri can not be null");
return uri.getBooleanQueryParameter(PARAM_MANAGE, false);
diff --git a/core/java/android/provider/DocumentsProvider.java b/core/java/android/provider/DocumentsProvider.java
index a80153d..327bca2 100644
--- a/core/java/android/provider/DocumentsProvider.java
+++ b/core/java/android/provider/DocumentsProvider.java
@@ -1081,7 +1081,7 @@
// signed with platform signature can hold MANAGE_DOCUMENTS, we are going to check for
// MANAGE_DOCUMENTS or associated URI permission here instead
final Uri rootUri = extras.getParcelable(DocumentsContract.EXTRA_URI);
- enforceWritePermissionInner(rootUri, getCallingPackage(), getCallingFeatureId(),
+ enforceWritePermissionInner(rootUri, getCallingPackage(), getCallingAttributionTag(),
null);
final String rootId = DocumentsContract.getRootId(rootUri);
@@ -1103,8 +1103,8 @@
enforceTree(documentUri);
if (METHOD_IS_CHILD_DOCUMENT.equals(method)) {
- enforceReadPermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceReadPermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
final Uri childUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI);
final String childAuthority = childUri.getAuthority();
@@ -1116,8 +1116,8 @@
&& isChildDocument(documentId, childId));
} else if (METHOD_CREATE_DOCUMENT.equals(method)) {
- enforceWritePermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceWritePermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
final String mimeType = extras.getString(Document.COLUMN_MIME_TYPE);
final String displayName = extras.getString(Document.COLUMN_DISPLAY_NAME);
@@ -1131,8 +1131,8 @@
out.putParcelable(DocumentsContract.EXTRA_URI, newDocumentUri);
} else if (METHOD_CREATE_WEB_LINK_INTENT.equals(method)) {
- enforceWritePermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceWritePermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
final Bundle options = extras.getBundle(DocumentsContract.EXTRA_OPTIONS);
final IntentSender intentSender = createWebLinkIntent(documentId, options);
@@ -1140,8 +1140,8 @@
out.putParcelable(DocumentsContract.EXTRA_RESULT, intentSender);
} else if (METHOD_RENAME_DOCUMENT.equals(method)) {
- enforceWritePermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceWritePermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
final String displayName = extras.getString(Document.COLUMN_DISPLAY_NAME);
final String newDocumentId = renameDocument(documentId, displayName);
@@ -1165,8 +1165,8 @@
}
} else if (METHOD_DELETE_DOCUMENT.equals(method)) {
- enforceWritePermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceWritePermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
deleteDocument(documentId);
// Document no longer exists, clean up any grants.
@@ -1176,9 +1176,9 @@
final Uri targetUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI);
final String targetId = DocumentsContract.getDocumentId(targetUri);
- enforceReadPermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
- enforceWritePermissionInner(targetUri, getCallingPackage(), getCallingFeatureId(),
+ enforceReadPermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
+ enforceWritePermissionInner(targetUri, getCallingPackage(), getCallingAttributionTag(),
null);
final String newDocumentId = copyDocument(documentId, targetId);
@@ -1202,11 +1202,11 @@
final Uri targetUri = extras.getParcelable(DocumentsContract.EXTRA_TARGET_URI);
final String targetId = DocumentsContract.getDocumentId(targetUri);
- enforceWritePermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
- enforceReadPermissionInner(parentSourceUri, getCallingPackage(), getCallingFeatureId(),
- null);
- enforceWritePermissionInner(targetUri, getCallingPackage(), getCallingFeatureId(),
+ enforceWritePermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
+ enforceReadPermissionInner(parentSourceUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
+ enforceWritePermissionInner(targetUri, getCallingPackage(), getCallingAttributionTag(),
null);
final String newDocumentId = moveDocument(documentId, parentSourceId, targetId);
@@ -1228,10 +1228,10 @@
final Uri parentSourceUri = extras.getParcelable(DocumentsContract.EXTRA_PARENT_URI);
final String parentSourceId = DocumentsContract.getDocumentId(parentSourceUri);
- enforceReadPermissionInner(parentSourceUri, getCallingPackage(), getCallingFeatureId(),
- null);
- enforceWritePermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceReadPermissionInner(parentSourceUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
+ enforceWritePermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
removeDocument(documentId, parentSourceId);
// It's responsibility of the provider to revoke any grants, as the document may be
@@ -1240,8 +1240,8 @@
final boolean isTreeUri = isTreeUri(documentUri);
if (isTreeUri) {
- enforceReadPermissionInner(documentUri, getCallingPackage(), getCallingFeatureId(),
- null);
+ enforceReadPermissionInner(documentUri, getCallingPackage(),
+ getCallingAttributionTag(), null);
} else {
getContext().enforceCallingPermission(Manifest.permission.MANAGE_DOCUMENTS, null);
}
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 83a304f..d8679b2 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -98,7 +98,8 @@
* The Settings provider contains global system-level device preferences.
*/
public final class Settings {
- private static final boolean DEFAULT_OVERRIDEABLE_BY_RESTORE = false;
+ /** @hide */
+ public static final boolean DEFAULT_OVERRIDEABLE_BY_RESTORE = false;
// Intent actions for Settings
@@ -703,13 +704,15 @@
* Weak or above, as defined by the CDD. Only biometrics that meet or exceed Strong, as defined
* in the CDD are allowed to participate in Keystore operations.
* <p>
- * Input: extras {@link #EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED} as an integer, with
+ * Input: extras {@link #EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED} as an integer, with
* constants defined in {@link android.hardware.biometrics.BiometricManager.Authenticators},
* e.g. {@link android.hardware.biometrics.BiometricManager.Authenticators#BIOMETRIC_STRONG}.
* If not specified, the default behavior is
* {@link android.hardware.biometrics.BiometricManager.Authenticators#BIOMETRIC_WEAK}.
* <p>
- * Output: Nothing.
+ * Output: Nothing. Note that callers should still check
+ * {@link android.hardware.biometrics.BiometricManager#canAuthenticate(int)}
+ * afterwards to ensure that the user actually completed enrollment.
*/
@SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
public static final String ACTION_BIOMETRIC_ENROLL =
@@ -719,12 +722,12 @@
* Activity Extra: The minimum strength to request enrollment for.
* <p>
* This can be passed as an extra field to the {@link #ACTION_BIOMETRIC_ENROLL} intent to
- * indicate that only enrollment for sensors that meet this strength should be shown. The
- * value should be one of the biometric strength constants defined in
+ * indicate that only enrollment for sensors that meet these requirements should be shown. The
+ * value should be a combination of the constants defined in
* {@link android.hardware.biometrics.BiometricManager.Authenticators}.
*/
- public static final String EXTRA_BIOMETRIC_MINIMUM_STRENGTH_REQUIRED =
- "android.provider.extra.BIOMETRIC_MINIMUM_STRENGTH_REQUIRED";
+ public static final String EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED =
+ "android.provider.extra.BIOMETRIC_AUTHENTICATORS_ALLOWED";
/**
* Activity Action: Show settings to allow configuration of cast endpoints.
@@ -2621,7 +2624,7 @@
arg.putBoolean(CALL_METHOD_OVERRIDEABLE_BY_RESTORE_KEY, true);
}
IContentProvider cp = mProviderHolder.getProvider(cr);
- cp.call(cr.getPackageName(), cr.getFeatureId(),
+ cp.call(cr.getPackageName(), cr.getAttributionTag(),
mProviderHolder.mUri.getAuthority(), mCallSetCommand, name, arg);
} catch (RemoteException e) {
Log.w(TAG, "Can't set key " + name + " in " + mUri, e);
@@ -2641,7 +2644,7 @@
args.putString(CALL_METHOD_PREFIX_KEY, prefix);
args.putSerializable(CALL_METHOD_FLAGS_KEY, keyValues);
IContentProvider cp = mProviderHolder.getProvider(cr);
- Bundle bundle = cp.call(cr.getPackageName(), cr.getFeatureId(),
+ Bundle bundle = cp.call(cr.getPackageName(), cr.getAttributionTag(),
mProviderHolder.mUri.getAuthority(),
mCallSetAllCommand, null, args);
return bundle.getBoolean(KEY_CONFIG_SET_RETURN);
@@ -2716,14 +2719,14 @@
if (Settings.isInSystemServer() && Binder.getCallingUid() != Process.myUid()) {
final long token = Binder.clearCallingIdentity();
try {
- b = cp.call(cr.getPackageName(), cr.getFeatureId(),
+ b = cp.call(cr.getPackageName(), cr.getAttributionTag(),
mProviderHolder.mUri.getAuthority(), mCallGetCommand, name,
args);
} finally {
Binder.restoreCallingIdentity(token);
}
} else {
- b = cp.call(cr.getPackageName(), cr.getFeatureId(),
+ b = cp.call(cr.getPackageName(), cr.getAttributionTag(),
mProviderHolder.mUri.getAuthority(), mCallGetCommand, name, args);
}
if (b != null) {
@@ -2793,13 +2796,13 @@
if (Settings.isInSystemServer() && Binder.getCallingUid() != Process.myUid()) {
final long token = Binder.clearCallingIdentity();
try {
- c = cp.query(cr.getPackageName(), cr.getFeatureId(), mUri,
+ c = cp.query(cr.getPackageName(), cr.getAttributionTag(), mUri,
SELECT_VALUE_PROJECTION, queryArgs, null);
} finally {
Binder.restoreCallingIdentity(token);
}
} else {
- c = cp.query(cr.getPackageName(), cr.getFeatureId(), mUri,
+ c = cp.query(cr.getPackageName(), cr.getAttributionTag(), mUri,
SELECT_VALUE_PROJECTION, queryArgs, null);
}
if (c == null) {
@@ -2892,7 +2895,7 @@
}
// Fetch all flags for the namespace at once for caching purposes
- Bundle b = cp.call(cr.getPackageName(), cr.getFeatureId(),
+ Bundle b = cp.call(cr.getPackageName(), cr.getAttributionTag(),
mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args);
if (b == null) {
// Invalid response, return an empty map
@@ -5537,7 +5540,7 @@
}
arg.putInt(CALL_METHOD_RESET_MODE_KEY, mode);
IContentProvider cp = sProviderHolder.getProvider(resolver);
- cp.call(resolver.getPackageName(), resolver.getFeatureId(),
+ cp.call(resolver.getPackageName(), resolver.getAttributionTag(),
sProviderHolder.mUri.getAuthority(), CALL_METHOD_RESET_SECURE, null, arg);
} catch (RemoteException e) {
Log.w(TAG, "Can't reset do defaults for " + CONTENT_URI, e);
@@ -6087,10 +6090,7 @@
* device is removed from this mode.
* <p>
* Type: int (0 for false, 1 for true)
- *
- * @hide
*/
- @SystemApi
public static final String SECURE_FRP_MODE = "secure_frp_mode";
/**
@@ -8497,7 +8497,6 @@
*
* @hide
*/
- @SystemApi
public static final String CARRIER_APPS_HANDLED = "carrier_apps_handled";
/**
@@ -13383,7 +13382,7 @@
}
arg.putInt(CALL_METHOD_RESET_MODE_KEY, mode);
IContentProvider cp = sProviderHolder.getProvider(resolver);
- cp.call(resolver.getPackageName(), resolver.getFeatureId(),
+ cp.call(resolver.getPackageName(), resolver.getAttributionTag(),
sProviderHolder.mUri.getAuthority(), CALL_METHOD_RESET_GLOBAL, null, arg);
} catch (RemoteException e) {
Log.w(TAG, "Can't reset do defaults for " + CONTENT_URI, e);
@@ -14358,7 +14357,7 @@
arg.putString(Settings.CALL_METHOD_PREFIX_KEY, createPrefix(namespace));
}
IContentProvider cp = sProviderHolder.getProvider(resolver);
- cp.call(resolver.getPackageName(), resolver.getFeatureId(),
+ cp.call(resolver.getPackageName(), resolver.getAttributionTag(),
sProviderHolder.mUri.getAuthority(), CALL_METHOD_RESET_CONFIG, null, arg);
} catch (RemoteException e) {
Log.w(TAG, "Can't reset to defaults for " + DeviceConfig.CONTENT_URI, e);
@@ -14387,7 +14386,7 @@
arg.putInt(CALL_METHOD_USER_KEY, userHandle);
arg.putParcelable(CALL_METHOD_MONITOR_CALLBACK_KEY, callback);
IContentProvider cp = sProviderHolder.getProvider(resolver);
- cp.call(resolver.getPackageName(), resolver.getFeatureId(),
+ cp.call(resolver.getPackageName(), resolver.getAttributionTag(),
sProviderHolder.mUri.getAuthority(),
CALL_METHOD_REGISTER_MONITOR_CALLBACK_CONFIG, null, arg);
} catch (RemoteException e) {
diff --git a/core/java/android/provider/Telephony.java b/core/java/android/provider/Telephony.java
index 97f7533..e7b360d 100644
--- a/core/java/android/provider/Telephony.java
+++ b/core/java/android/provider/Telephony.java
@@ -25,6 +25,7 @@
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledAfter;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.ContentResolver;
@@ -3550,7 +3551,6 @@
* can manage DPC-owned APNs.
* @hide
*/
- @SystemApi
public static final @NonNull Uri DPC_URI = Uri.parse("content://telephony/carriers/dpc");
/**
@@ -3734,7 +3734,6 @@
* @deprecated this column is no longer supported, use {@link #NETWORK_TYPE_BITMASK} instead
*/
@Deprecated
- @SystemApi
public static final String BEARER_BITMASK = "bearer_bitmask";
/**
@@ -3784,7 +3783,6 @@
* <p>Type: INTEGER</p>
*@hide
*/
- @SystemApi
public static final String PROFILE_ID = "profile_id";
/**
@@ -3865,7 +3863,6 @@
* Integer value denoting an invalid APN id
* @hide
*/
- @SystemApi
public static final int INVALID_APN_ID = -1;
/**
@@ -3985,7 +3982,6 @@
*
* @hide
*/
- @SystemApi
public static final String SKIP_464XLAT = "skip_464xlat";
/**
@@ -3994,7 +3990,6 @@
*
* @hide
*/
- @SystemApi
public static final int SKIP_464XLAT_DEFAULT = -1;
/**
@@ -4003,7 +3998,6 @@
*
* @hide
*/
- @SystemApi
public static final int SKIP_464XLAT_DISABLE = 0;
/**
@@ -4012,7 +4006,6 @@
*
* @hide
*/
- @SystemApi
public static final int SKIP_464XLAT_ENABLE = 1;
@@ -4036,6 +4029,7 @@
* @hide
*/
@ChangeId
+ @EnabledAfter(targetSdkVersion = android.os.Build.VERSION_CODES.Q)
public static final long APN_READING_PERMISSION_CHANGE_ID = 124107808L;
}
@@ -4390,6 +4384,7 @@
* Indicates that whether the message has been broadcasted to the application.
* <P>Type: BOOLEAN</P>
*/
+ // TODO: deprecate this in S.
public static final String MESSAGE_BROADCASTED = "message_broadcasted";
/**
diff --git a/core/java/android/service/autofill/Dataset.java b/core/java/android/service/autofill/Dataset.java
index 886b433..08aa534 100644
--- a/core/java/android/service/autofill/Dataset.java
+++ b/core/java/android/service/autofill/Dataset.java
@@ -232,22 +232,6 @@
* Creates a new builder.
*
* @param presentation The presentation used to visualize this dataset.
- * @param inlinePresentation The {@link InlinePresentation} used to visualize this dataset
- * as inline suggestions. If the dataset supports inline suggestions,
- * this should not be null.
- */
- public Builder(@NonNull RemoteViews presentation,
- @NonNull InlinePresentation inlinePresentation) {
- Preconditions.checkNotNull(presentation, "presentation must be non-null");
- Preconditions.checkNotNull(inlinePresentation, "inlinePresentation must be non-null");
- mPresentation = presentation;
- mInlinePresentation = inlinePresentation;
- }
-
- /**
- * Creates a new builder.
- *
- * @param presentation The presentation used to visualize this dataset.
*/
public Builder(@NonNull RemoteViews presentation) {
Preconditions.checkNotNull(presentation, "presentation must be non-null");
@@ -282,6 +266,22 @@
}
/**
+ * Sets the {@link InlinePresentation} used to visualize this dataset as inline suggestions.
+ * If the dataset supports inline suggestions this should not be null.
+ *
+ * @throws IllegalStateException if {@link #build()} was already called.
+ *
+ * @return this builder.
+ */
+ public @NonNull Builder setInlinePresentation(
+ @NonNull InlinePresentation inlinePresentation) {
+ throwIfDestroyed();
+ Preconditions.checkNotNull(inlinePresentation, "inlinePresentation must be non-null");
+ mInlinePresentation = inlinePresentation;
+ return this;
+ }
+
+ /**
* Triggers a custom UI before before autofilling the screen with the contents of this
* dataset.
*
@@ -600,7 +600,7 @@
*/
@SystemApi
@TestApi
- public @NonNull Builder setInlinePresentation(@NonNull AutofillId id,
+ public @NonNull Builder setFieldInlinePresentation(@NonNull AutofillId id,
@Nullable AutofillValue value, @Nullable Pattern filter,
@NonNull InlinePresentation inlinePresentation) {
throwIfDestroyed();
@@ -700,7 +700,7 @@
final Builder builder = presentation != null
? inlinePresentation == null
? new Builder(presentation)
- : new Builder(presentation, inlinePresentation)
+ : new Builder(presentation).setInlinePresentation(inlinePresentation)
: inlinePresentation == null
? new Builder()
: new Builder(inlinePresentation);
diff --git a/core/java/android/service/autofill/FillRequest.java b/core/java/android/service/autofill/FillRequest.java
index 72e9ad0..8f858d5 100644
--- a/core/java/android/service/autofill/FillRequest.java
+++ b/core/java/android/service/autofill/FillRequest.java
@@ -77,6 +77,15 @@
*/
public static final @RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST = 0x2;
+ /**
+ * Indicates the request came from a password field.
+ *
+ * (TODO: b/141703197) Temporary fix for augmented autofill showing passwords.
+ *
+ * @hide
+ */
+ public static final @RequestFlags int FLAG_PASSWORD_INPUT_TYPE = 0x4;
+
/** @hide */
public static final int INVALID_REQUEST_ID = Integer.MIN_VALUE;
@@ -149,7 +158,8 @@
/** @hide */
@IntDef(flag = true, prefix = "FLAG_", value = {
FLAG_MANUAL_REQUEST,
- FLAG_COMPATIBILITY_MODE_REQUEST
+ FLAG_COMPATIBILITY_MODE_REQUEST,
+ FLAG_PASSWORD_INPUT_TYPE
})
@Retention(RetentionPolicy.SOURCE)
@DataClass.Generated.Member
@@ -169,6 +179,8 @@
return "FLAG_MANUAL_REQUEST";
case FLAG_COMPATIBILITY_MODE_REQUEST:
return "FLAG_COMPATIBILITY_MODE_REQUEST";
+ case FLAG_PASSWORD_INPUT_TYPE:
+ return "FLAG_PASSWORD_INPUT_TYPE";
default: return Integer.toHexString(value);
}
}
@@ -223,7 +235,8 @@
Preconditions.checkFlagsArgument(
mFlags,
FLAG_MANUAL_REQUEST
- | FLAG_COMPATIBILITY_MODE_REQUEST);
+ | FLAG_COMPATIBILITY_MODE_REQUEST
+ | FLAG_PASSWORD_INPUT_TYPE);
this.mInlineSuggestionsRequest = inlineSuggestionsRequest;
onConstructed();
@@ -352,7 +365,8 @@
Preconditions.checkFlagsArgument(
mFlags,
FLAG_MANUAL_REQUEST
- | FLAG_COMPATIBILITY_MODE_REQUEST);
+ | FLAG_COMPATIBILITY_MODE_REQUEST
+ | FLAG_PASSWORD_INPUT_TYPE);
this.mInlineSuggestionsRequest = inlineSuggestionsRequest;
onConstructed();
@@ -373,10 +387,10 @@
};
@DataClass.Generated(
- time = 1575928271155L,
+ time = 1583196707026L,
codegenVersion = "1.0.14",
sourceFile = "frameworks/base/core/java/android/service/autofill/FillRequest.java",
- inputSignatures = "public static final @android.service.autofill.FillRequest.RequestFlags int FLAG_MANUAL_REQUEST\npublic static final @android.service.autofill.FillRequest.RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST\npublic static final int INVALID_REQUEST_ID\nprivate final int mId\nprivate final @android.annotation.NonNull java.util.List<android.service.autofill.FillContext> mFillContexts\nprivate final @android.annotation.Nullable android.os.Bundle mClientState\nprivate final @android.service.autofill.FillRequest.RequestFlags int mFlags\nprivate final @android.annotation.Nullable android.view.inputmethod.InlineSuggestionsRequest mInlineSuggestionsRequest\nprivate void onConstructed()\nclass FillRequest extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genHiddenConstructor=true, genHiddenConstDefs=true)")
+ inputSignatures = "public static final @android.service.autofill.FillRequest.RequestFlags int FLAG_MANUAL_REQUEST\npublic static final @android.service.autofill.FillRequest.RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST\npublic static final @android.service.autofill.FillRequest.RequestFlags int FLAG_PASSWORD_INPUT_TYPE\npublic static final int INVALID_REQUEST_ID\nprivate final int mId\nprivate final @android.annotation.NonNull java.util.List<android.service.autofill.FillContext> mFillContexts\nprivate final @android.annotation.Nullable android.os.Bundle mClientState\nprivate final @android.service.autofill.FillRequest.RequestFlags int mFlags\nprivate final @android.annotation.Nullable android.view.inputmethod.InlineSuggestionsRequest mInlineSuggestionsRequest\nprivate void onConstructed()\nclass FillRequest extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genHiddenConstructor=true, genHiddenConstDefs=true)")
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/service/autofill/FillResponse.java b/core/java/android/service/autofill/FillResponse.java
index e8e1223..06b5fa0 100644
--- a/core/java/android/service/autofill/FillResponse.java
+++ b/core/java/android/service/autofill/FillResponse.java
@@ -89,7 +89,7 @@
private final @Nullable int[] mCancelIds;
private final boolean mSupportsInlineSuggestions;
// TODO(b/149240554): revert back to use ParceledListSlice after the bug is resolved.
- private final @Nullable ArrayList<InlinePresentation> mInlineActions;
+ private final @Nullable ArrayList<InlineAction> mInlineActions;
private FillResponse(@NonNull Builder builder) {
mDatasets = (builder.mDatasets != null) ? new ParceledListSlice<>(builder.mDatasets) : null;
@@ -213,7 +213,7 @@
}
/** @hide */
- public @Nullable List<InlinePresentation> getInlineActions() {
+ public @Nullable List<InlineAction> getInlineActions() {
return mInlineActions;
}
@@ -239,7 +239,7 @@
private UserData mUserData;
private int[] mCancelIds;
private boolean mSupportsInlineSuggestions;
- private ArrayList<InlinePresentation> mInlineActions;
+ private ArrayList<InlineAction> mInlineActions;
/**
* Triggers a custom UI before before autofilling the screen with any data set in this
@@ -656,15 +656,12 @@
}
/**
- * Adds a new {@link InlinePresentation} to this response representing an action UI.
- *
- * <p> For example, the UI can be associated with an intent which can open an activity for
- * the user to manage the Autofill provider settings.
+ * Adds a new {@link InlineAction} to this response representing an action UI.
*
* @return This builder.
*/
@NonNull
- public Builder addInlineAction(@NonNull InlinePresentation inlineAction) {
+ public Builder addInlineAction(@NonNull InlineAction inlineAction) {
throwIfDestroyed();
throwIfAuthenticationCalled();
if (mInlineActions == null) {
@@ -881,10 +878,10 @@
final int[] cancelIds = parcel.createIntArray();
builder.setPresentationCancelIds(cancelIds);
- final List<InlinePresentation> inlineActions = parcel.createTypedArrayList(
- InlinePresentation.CREATOR);
+ final List<InlineAction> inlineActions = parcel.createTypedArrayList(
+ InlineAction.CREATOR);
if (inlineActions != null) {
- for (InlinePresentation inlineAction : inlineActions) {
+ for (InlineAction inlineAction : inlineActions) {
builder.addInlineAction(inlineAction);
}
}
diff --git a/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl b/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl
index 1011651..1bcc76b 100644
--- a/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl
+++ b/core/java/android/service/autofill/IInlineSuggestionUiCallback.aidl
@@ -25,7 +25,8 @@
* @hide
*/
oneway interface IInlineSuggestionUiCallback {
- void onAutofill();
+ void onClick();
+ void onLongClick();
void onContent(in SurfaceControlViewHost.SurfacePackage surface);
void onError();
void onTransferTouchFocusToImeWindow(in IBinder sourceInputToken, int displayId);
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/core/java/android/service/autofill/InlineAction.aidl
similarity index 71%
copy from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
copy to core/java/android/service/autofill/InlineAction.aidl
index d691f41..7f85118 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/core/java/android/service/autofill/InlineAction.aidl
@@ -14,16 +14,6 @@
* limitations under the License.
*/
-package android.net.wifi;
+package android.service.autofill;
-/**
- * Interface for Wi-Fi score callback.
- *
- * @hide
- */
-oneway interface IScoreChangeCallback
-{
- void onScoreChange(int sessionId, int score);
-
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
-}
+parcelable InlineAction;
diff --git a/core/java/android/service/autofill/InlineAction.java b/core/java/android/service/autofill/InlineAction.java
new file mode 100644
index 0000000..17c4b33
--- /dev/null
+++ b/core/java/android/service/autofill/InlineAction.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2020 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.service.autofill;
+
+import android.annotation.NonNull;
+import android.content.IntentSender;
+import android.os.Parcelable;
+
+import com.android.internal.util.DataClass;
+
+/**
+ * Represents an inline action as part of the autofill/augmented autofill response.
+ *
+ * <p> It includes both the action intent and the UI presentation. For example, the UI can be
+ * associated with an intent which can open an activity for the user to manage the Autofill provider
+ * settings.
+ */
+@DataClass(
+ genToString = true,
+ genHiddenConstDefs = true,
+ genEqualsHashCode = true)
+public final class InlineAction implements Parcelable {
+
+ /**
+ * Representation of the inline action.
+ */
+ private final @NonNull InlinePresentation mInlinePresentation;
+
+ /**
+ * The associated intent which will be triggered when the action is selected. It will only be
+ * called by the OS.
+ */
+ private final @NonNull IntentSender mAction;
+
+
+
+ // Code below generated by codegen v1.0.15.
+ //
+ // DO NOT MODIFY!
+ // CHECKSTYLE:OFF Generated code
+ //
+ // To regenerate run:
+ // $ codegen $ANDROID_BUILD_TOP/frameworks/base/core/java/android/service/autofill/InlineAction.java
+ //
+ // To exclude the generated code from IntelliJ auto-formatting enable (one-time):
+ // Settings > Editor > Code Style > Formatter Control
+ //@formatter:off
+
+
+ /**
+ * Creates a new InlineAction.
+ *
+ * @param inlinePresentation
+ * Representation of the inline action.
+ * @param action
+ * The associated intent which will be triggered when the action is selected. It will only be
+ * invoked by the OS.
+ */
+ @DataClass.Generated.Member
+ public InlineAction(
+ @NonNull InlinePresentation inlinePresentation,
+ @NonNull IntentSender action) {
+ this.mInlinePresentation = inlinePresentation;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, mInlinePresentation);
+ this.mAction = action;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, mAction);
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ /**
+ * Representation of the inline action.
+ */
+ @DataClass.Generated.Member
+ public @NonNull InlinePresentation getInlinePresentation() {
+ return mInlinePresentation;
+ }
+
+ /**
+ * The associated intent which will be triggered when the action is selected. It will only be
+ * invoked by the OS.
+ */
+ @DataClass.Generated.Member
+ public @NonNull IntentSender getAction() {
+ return mAction;
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public String toString() {
+ // You can override field toString logic by defining methods like:
+ // String fieldNameToString() { ... }
+
+ return "InlineAction { " +
+ "inlinePresentation = " + mInlinePresentation + ", " +
+ "action = " + mAction +
+ " }";
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public boolean equals(@android.annotation.Nullable Object o) {
+ // You can override field equality logic by defining either of the methods like:
+ // boolean fieldNameEquals(InlineAction other) { ... }
+ // boolean fieldNameEquals(FieldType otherValue) { ... }
+
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ @SuppressWarnings("unchecked")
+ InlineAction that = (InlineAction) o;
+ //noinspection PointlessBooleanExpression
+ return true
+ && java.util.Objects.equals(mInlinePresentation, that.mInlinePresentation)
+ && java.util.Objects.equals(mAction, that.mAction);
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public int hashCode() {
+ // You can override field hashCode logic by defining methods like:
+ // int fieldNameHashCode() { ... }
+
+ int _hash = 1;
+ _hash = 31 * _hash + java.util.Objects.hashCode(mInlinePresentation);
+ _hash = 31 * _hash + java.util.Objects.hashCode(mAction);
+ return _hash;
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public void writeToParcel(@NonNull android.os.Parcel dest, int flags) {
+ // You can override field parcelling by defining methods like:
+ // void parcelFieldName(Parcel dest, int flags) { ... }
+
+ dest.writeTypedObject(mInlinePresentation, flags);
+ dest.writeTypedObject(mAction, flags);
+ }
+
+ @Override
+ @DataClass.Generated.Member
+ public int describeContents() { return 0; }
+
+ /** @hide */
+ @SuppressWarnings({"unchecked", "RedundantCast"})
+ @DataClass.Generated.Member
+ /* package-private */ InlineAction(@NonNull android.os.Parcel in) {
+ // You can override field unparcelling by defining methods like:
+ // static FieldType unparcelFieldName(Parcel in) { ... }
+
+ InlinePresentation inlinePresentation = (InlinePresentation) in.readTypedObject(InlinePresentation.CREATOR);
+ IntentSender action = (IntentSender) in.readTypedObject(IntentSender.CREATOR);
+
+ this.mInlinePresentation = inlinePresentation;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, mInlinePresentation);
+ this.mAction = action;
+ com.android.internal.util.AnnotationValidations.validate(
+ NonNull.class, null, mAction);
+
+ // onConstructed(); // You can define this method to get a callback
+ }
+
+ @DataClass.Generated.Member
+ public static final @NonNull Parcelable.Creator<InlineAction> CREATOR
+ = new Parcelable.Creator<InlineAction>() {
+ @Override
+ public InlineAction[] newArray(int size) {
+ return new InlineAction[size];
+ }
+
+ @Override
+ public InlineAction createFromParcel(@NonNull android.os.Parcel in) {
+ return new InlineAction(in);
+ }
+ };
+
+ @DataClass.Generated(
+ time = 1583798182424L,
+ codegenVersion = "1.0.15",
+ sourceFile = "frameworks/base/core/java/android/service/autofill/InlineAction.java",
+ inputSignatures = "private final @android.annotation.NonNull android.service.autofill.InlinePresentation mInlinePresentation\nprivate final @android.annotation.NonNull android.content.IntentSender mAction\nclass InlineAction extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genToString=true, genHiddenConstDefs=true, genEqualsHashCode=true)")
+ @Deprecated
+ private void __metadata() {}
+
+
+ //@formatter:on
+ // End of generated code
+
+}
diff --git a/core/java/android/service/autofill/InlineSuggestionRenderService.java b/core/java/android/service/autofill/InlineSuggestionRenderService.java
index ee15283..f0a72c5 100644
--- a/core/java/android/service/autofill/InlineSuggestionRenderService.java
+++ b/core/java/android/service/autofill/InlineSuggestionRenderService.java
@@ -94,15 +94,24 @@
final SurfaceControlViewHost host = new SurfaceControlViewHost(this, getDisplay(),
hostInputToken);
- host.addView(suggestionRoot, lp);
+ host.setView(suggestionRoot, lp);
suggestionRoot.setOnClickListener((v) -> {
try {
- callback.onAutofill();
+ callback.onClick();
} catch (RemoteException e) {
- Log.w(TAG, "RemoteException calling onAutofill()");
+ Log.w(TAG, "RemoteException calling onClick()");
}
});
+ suggestionRoot.setOnLongClickListener((v) -> {
+ try {
+ callback.onLongClick();
+ } catch (RemoteException e) {
+ Log.w(TAG, "RemoteException calling onLongClick()");
+ }
+ return true;
+ });
+
sendResult(callback, host.getSurfacePackage());
} finally {
updateDisplay(Display.DEFAULT_DISPLAY);
diff --git a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
index fe792b1..5b08ae2 100644
--- a/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
+++ b/core/java/android/service/autofill/augmented/AugmentedAutofillService.java
@@ -40,7 +40,7 @@
import android.os.SystemClock;
import android.service.autofill.Dataset;
import android.service.autofill.FillEventHistory;
-import android.service.autofill.InlinePresentation;
+import android.service.autofill.InlineAction;
import android.service.autofill.augmented.PresentationParams.SystemPopupPresentationParams;
import android.util.Log;
import android.util.Pair;
@@ -488,7 +488,8 @@
ids.add(pair.first);
values.add(pair.second);
}
- mClient.autofill(mSessionId, ids, values);
+ final boolean hideHighlight = size == 1 && ids.get(0).equals(mFocusedId);
+ mClient.autofill(mSessionId, ids, values, hideHighlight);
}
public void setFillWindow(@NonNull FillWindow fillWindow) {
@@ -559,7 +560,7 @@
}
void reportResult(@Nullable List<Dataset> inlineSuggestionsData,
- @Nullable List<InlinePresentation> inlineActions) {
+ @Nullable List<InlineAction> inlineActions) {
try {
mCallback.onSuccess(inlineSuggestionsData, inlineActions);
} catch (RemoteException e) {
diff --git a/core/java/android/service/autofill/augmented/FillResponse.java b/core/java/android/service/autofill/augmented/FillResponse.java
index b7fdf5a..f564b3b 100644
--- a/core/java/android/service/autofill/augmented/FillResponse.java
+++ b/core/java/android/service/autofill/augmented/FillResponse.java
@@ -21,7 +21,7 @@
import android.annotation.TestApi;
import android.os.Bundle;
import android.service.autofill.Dataset;
-import android.service.autofill.InlinePresentation;
+import android.service.autofill.InlineAction;
import com.android.internal.util.DataClass;
@@ -53,11 +53,10 @@
private @Nullable List<Dataset> mInlineSuggestions;
/**
- * The {@link InlinePresentation}s representing the inline actions. Defaults to null if no
- * inline actions are provided.
+ * Defaults to null if no inline actions are provided.
*/
@DataClass.PluralOf("inlineAction")
- private @Nullable List<InlinePresentation> mInlineActions;
+ private @Nullable List<InlineAction> mInlineActions;
/**
* The client state that {@link AugmentedAutofillService} implementation can put anything in to
@@ -74,7 +73,7 @@
return null;
}
- private static List<InlinePresentation> defaultInlineActions() {
+ private static List<InlineAction> defaultInlineActions() {
return null;
}
@@ -86,12 +85,12 @@
/** @hide */
abstract static class BaseBuilder {
abstract FillResponse.Builder addInlineSuggestion(@NonNull Dataset value);
- abstract FillResponse.Builder addInlineAction(@NonNull InlinePresentation value);
+ abstract FillResponse.Builder addInlineAction(@NonNull InlineAction value);
}
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -108,7 +107,7 @@
/* package-private */ FillResponse(
@Nullable FillWindow fillWindow,
@Nullable List<Dataset> inlineSuggestions,
- @Nullable List<InlinePresentation> inlineActions,
+ @Nullable List<InlineAction> inlineActions,
@Nullable Bundle clientState) {
this.mFillWindow = fillWindow;
this.mInlineSuggestions = inlineSuggestions;
@@ -140,13 +139,12 @@
}
/**
- * The {@link InlinePresentation}s representing the inline actions. Defaults to null if no
- * inline actions are provided.
+ * Defaults to null if no inline actions are provided.
*
* @hide
*/
@DataClass.Generated.Member
- public @Nullable List<InlinePresentation> getInlineActions() {
+ public @Nullable List<InlineAction> getInlineActions() {
return mInlineActions;
}
@@ -171,7 +169,7 @@
private @Nullable FillWindow mFillWindow;
private @Nullable List<Dataset> mInlineSuggestions;
- private @Nullable List<InlinePresentation> mInlineActions;
+ private @Nullable List<InlineAction> mInlineActions;
private @Nullable Bundle mClientState;
private long mBuilderFieldsSet = 0L;
@@ -183,7 +181,7 @@
* The {@link FillWindow} used to display the Autofill UI.
*/
@DataClass.Generated.Member
- public @NonNull Builder setFillWindow(@Nullable FillWindow value) {
+ public @NonNull Builder setFillWindow(@NonNull FillWindow value) {
checkNotUsed();
mBuilderFieldsSet |= 0x1;
mFillWindow = value;
@@ -195,7 +193,7 @@
* inline suggestions are available from the service.
*/
@DataClass.Generated.Member
- public @NonNull Builder setInlineSuggestions(@Nullable List<Dataset> value) {
+ public @NonNull Builder setInlineSuggestions(@NonNull List<Dataset> value) {
checkNotUsed();
mBuilderFieldsSet |= 0x2;
mInlineSuggestions = value;
@@ -212,11 +210,10 @@
}
/**
- * The {@link InlinePresentation}s representing the inline actions. Defaults to null if no
- * inline actions are provided.
+ * Defaults to null if no inline actions are provided.
*/
@DataClass.Generated.Member
- public @NonNull Builder setInlineActions(@Nullable List<InlinePresentation> value) {
+ public @NonNull Builder setInlineActions(@NonNull List<InlineAction> value) {
checkNotUsed();
mBuilderFieldsSet |= 0x4;
mInlineActions = value;
@@ -226,7 +223,7 @@
/** @see #setInlineActions */
@DataClass.Generated.Member
@Override
- @NonNull FillResponse.Builder addInlineAction(@NonNull InlinePresentation value) {
+ @NonNull FillResponse.Builder addInlineAction(@NonNull InlineAction value) {
if (mInlineActions == null) setInlineActions(new ArrayList<>());
mInlineActions.add(value);
return this;
@@ -238,7 +235,7 @@
* {@link AugmentedAutofillService#getFillEventHistory()}.
*/
@DataClass.Generated.Member
- public @NonNull Builder setClientState(@Nullable Bundle value) {
+ public @NonNull Builder setClientState(@NonNull Bundle value) {
checkNotUsed();
mBuilderFieldsSet |= 0x8;
mClientState = value;
@@ -279,10 +276,10 @@
}
@DataClass.Generated(
- time = 1582682935951L,
- codegenVersion = "1.0.14",
+ time = 1583793032373L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/core/java/android/service/autofill/augmented/FillResponse.java",
- inputSignatures = "private @android.annotation.Nullable android.service.autofill.augmented.FillWindow mFillWindow\nprivate @com.android.internal.util.DataClass.PluralOf(\"inlineSuggestion\") @android.annotation.Nullable java.util.List<android.service.autofill.Dataset> mInlineSuggestions\nprivate @com.android.internal.util.DataClass.PluralOf(\"inlineAction\") @android.annotation.Nullable java.util.List<android.service.autofill.InlinePresentation> mInlineActions\nprivate @android.annotation.Nullable android.os.Bundle mClientState\nprivate static android.service.autofill.augmented.FillWindow defaultFillWindow()\nprivate static java.util.List<android.service.autofill.Dataset> defaultInlineSuggestions()\nprivate static java.util.List<android.service.autofill.InlinePresentation> defaultInlineActions()\nprivate static android.os.Bundle defaultClientState()\nclass FillResponse extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genBuilder=true, genHiddenGetters=true)\nabstract android.service.autofill.augmented.FillResponse.Builder addInlineSuggestion(android.service.autofill.Dataset)\nabstract android.service.autofill.augmented.FillResponse.Builder addInlineAction(android.service.autofill.InlinePresentation)\nclass BaseBuilder extends java.lang.Object implements []")
+ inputSignatures = "private @android.annotation.Nullable android.service.autofill.augmented.FillWindow mFillWindow\nprivate @com.android.internal.util.DataClass.PluralOf(\"inlineSuggestion\") @android.annotation.Nullable java.util.List<android.service.autofill.Dataset> mInlineSuggestions\nprivate @com.android.internal.util.DataClass.PluralOf(\"inlineAction\") @android.annotation.Nullable java.util.List<android.service.autofill.InlineAction> mInlineActions\nprivate @android.annotation.Nullable android.os.Bundle mClientState\nprivate static android.service.autofill.augmented.FillWindow defaultFillWindow()\nprivate static java.util.List<android.service.autofill.Dataset> defaultInlineSuggestions()\nprivate static java.util.List<android.service.autofill.InlineAction> defaultInlineActions()\nprivate static android.os.Bundle defaultClientState()\nclass FillResponse extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genBuilder=true, genHiddenGetters=true)\nabstract android.service.autofill.augmented.FillResponse.Builder addInlineSuggestion(android.service.autofill.Dataset)\nabstract android.service.autofill.augmented.FillResponse.Builder addInlineAction(android.service.autofill.InlineAction)\nclass BaseBuilder extends java.lang.Object implements []")
@Deprecated
private void __metadata() {}
diff --git a/core/java/android/service/autofill/augmented/IFillCallback.aidl b/core/java/android/service/autofill/augmented/IFillCallback.aidl
index bf0adcd..545dab2 100644
--- a/core/java/android/service/autofill/augmented/IFillCallback.aidl
+++ b/core/java/android/service/autofill/augmented/IFillCallback.aidl
@@ -20,7 +20,7 @@
import android.os.ICancellationSignal;
import android.service.autofill.Dataset;
-import android.service.autofill.InlinePresentation;
+import android.service.autofill.InlineAction;
import java.util.List;
@@ -32,7 +32,7 @@
interface IFillCallback {
void onCancellable(in ICancellationSignal cancellation);
void onSuccess(in @nullable List<Dataset> inlineSuggestionsData,
- in @nullable List<InlinePresentation> inlineActions);
+ in @nullable List<InlineAction> inlineActions);
boolean isCompleted();
void cancel();
}
diff --git a/core/java/android/service/contentcapture/DataShareReadAdapter.java b/core/java/android/service/contentcapture/DataShareReadAdapter.java
index a481ec8..8cd9eea 100644
--- a/core/java/android/service/contentcapture/DataShareReadAdapter.java
+++ b/core/java/android/service/contentcapture/DataShareReadAdapter.java
@@ -20,6 +20,7 @@
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.os.ParcelFileDescriptor;
+import android.view.contentcapture.ContentCaptureManager.DataShareError;
/**
* Adapter class to be used for the Content Capture Service app to propagate the status of the
@@ -46,5 +47,5 @@
* these 2 events is not defined, and it's important that the service treats end of stream
* correctly in this situation.
**/
- void onError(int errorCode);
+ void onError(@DataShareError int errorCode);
}
diff --git a/core/java/android/service/controls/Control.java b/core/java/android/service/controls/Control.java
index dabd977..d01bc25 100644
--- a/core/java/android/service/controls/Control.java
+++ b/core/java/android/service/controls/Control.java
@@ -395,7 +395,7 @@
* {@link ControlsProviderService#createPublisherForAllAvailable}:
* <ul>
* <li> Status: {@link Status#STATUS_UNKNOWN}
- * <li> Control template: {@link ControlTemplate#NO_TEMPLATE}
+ * <li> Control template: {@link ControlTemplate#getNoTemplateObject}
* <li> Status text: {@code ""}
* </ul>
*/
@@ -593,7 +593,7 @@
* <li> Title: {@code ""}
* <li> Subtitle: {@code ""}
* <li> Status: {@link Status#STATUS_UNKNOWN}
- * <li> Control template: {@link ControlTemplate#NO_TEMPLATE}
+ * <li> Control template: {@link ControlTemplate#getNoTemplateObject}
* <li> Status text: {@code ""}
* </ul>
*/
diff --git a/core/java/android/service/controls/ControlsProviderService.java b/core/java/android/service/controls/ControlsProviderService.java
index 9debb37..9accf5b 100644
--- a/core/java/android/service/controls/ControlsProviderService.java
+++ b/core/java/android/service/controls/ControlsProviderService.java
@@ -239,7 +239,8 @@
private static boolean isStatelessControl(Control control) {
return (control.getStatus() == Control.STATUS_UNKNOWN
- && control.getControlTemplate().getTemplateType() == ControlTemplate.TYPE_NONE
+ && control.getControlTemplate().getTemplateType()
+ == ControlTemplate.TYPE_NO_TEMPLATE
&& TextUtils.isEmpty(control.getStatusText()));
}
diff --git a/core/java/android/service/controls/DeviceTypes.java b/core/java/android/service/controls/DeviceTypes.java
index 6594d2c..f973610 100644
--- a/core/java/android/service/controls/DeviceTypes.java
+++ b/core/java/android/service/controls/DeviceTypes.java
@@ -23,11 +23,23 @@
/**
* Device types for {@link Control}.
+ *
+ * Each {@link Control} declares a type for the device they represent. This type will be used to
+ * determine icons and colors.
+ * <p>
+ * The type of the device may change on status updates of the {@link Control}. For example, a
+ * device of {@link #TYPE_OUTLET} could be determined by the {@link ControlsProviderService} to be
+ * a {@link #TYPE_COFFEE_MAKER} and change the type for that {@link Control}, therefore possibly
+ * changing icon and color.
+ * <p>
+ * In case the device type is not know by the application but the basic function is, or there is no
+ * provided type, one of the generic types (those starting with {@code TYPE_GENERIC}) can be used.
+ * These will provide an identifiable icon based on the basic function of the device.
*/
public class DeviceTypes {
// Update this when adding new concrete types. Does not count TYPE_UNKNOWN
- private static final int NUM_CONCRETE_TYPES = 51;
+ private static final int NUM_CONCRETE_TYPES = 52;
public static final @DeviceType int TYPE_UNKNOWN = 0;
public static final @DeviceType int TYPE_AC_HEATER = 1;
@@ -87,6 +99,11 @@
public static final @DeviceType int TYPE_CAMERA = 50;
public static final @DeviceType int TYPE_DOORBELL = 51;
+ /*
+ * Also known as macros, routines can aggregate a series of actions across multiple devices
+ */
+ public static final @DeviceType int TYPE_ROUTINE = 52;
+
// Update this when adding new generic types.
private static final int NUM_GENERIC_TYPES = 7;
public static final @DeviceType int TYPE_GENERIC_ON_OFF = -1;
@@ -165,7 +182,8 @@
TYPE_REFRIGERATOR,
TYPE_THERMOSTAT,
TYPE_CAMERA,
- TYPE_DOORBELL
+ TYPE_DOORBELL,
+ TYPE_ROUTINE
})
public @interface DeviceType {}
diff --git a/core/java/android/service/controls/TokenProvider.aidl b/core/java/android/service/controls/TokenProvider.aidl
deleted file mode 100644
index 8f4b795..0000000
--- a/core/java/android/service/controls/TokenProvider.aidl
+++ /dev/null
@@ -1,7 +0,0 @@
-package android.service.controls;
-
-/** @hide */
-interface TokenProvider {
- void setAuthToken(String token);
- String getAccountName();
-}
\ No newline at end of file
diff --git a/core/java/android/service/controls/actions/ControlAction.java b/core/java/android/service/controls/actions/ControlAction.java
index 45e63d7..37a75f0 100644
--- a/core/java/android/service/controls/actions/ControlAction.java
+++ b/core/java/android/service/controls/actions/ControlAction.java
@@ -22,7 +22,7 @@
import android.annotation.Nullable;
import android.os.Bundle;
import android.service.controls.Control;
-import android.service.controls.IControlsActionCallback;
+import android.service.controls.ControlsProviderService;
import android.service.controls.templates.ControlTemplate;
import android.util.Log;
@@ -34,8 +34,15 @@
/**
* An abstract action indicating a user interaction with a {@link Control}.
*
- * The action may have a value to authenticate the input, when the provider has requested it to
- * complete the action.
+ * In some cases, an action needs to be validated by the user, using a password, PIN or simple
+ * acknowledgment. For those cases, an optional (nullable) parameter can be passed to send the user
+ * input. This <b>challenge value</b> will be requested from the user and sent as part
+ * of a {@link ControlAction} only if the service has responded to an action with one of:
+ * <ul>
+ * <li> {@link #RESPONSE_CHALLENGE_ACK}
+ * <li> {@link #RESPONSE_CHALLENGE_PIN}
+ * <li> {@link #RESPONSE_CHALLENGE_PASSPHRASE}
+ * </ul>
*/
public abstract class ControlAction {
@@ -53,7 +60,6 @@
TYPE_ERROR,
TYPE_BOOLEAN,
TYPE_FLOAT,
- TYPE_MULTI_FLOAT,
TYPE_MODE,
TYPE_COMMAND
})
@@ -61,6 +67,7 @@
/**
* Object returned when there is an unparcelling error.
+ * @hide
*/
public static final @NonNull ControlAction ERROR_ACTION = new ControlAction() {
@Override
@@ -70,7 +77,7 @@
};
/**
- * The identifier of {@link #ERROR_ACTION}
+ * The identifier of the action returned by {@link #getErrorAction}.
*/
public static final @ActionType int TYPE_ERROR = -1;
@@ -85,11 +92,6 @@
public static final @ActionType int TYPE_FLOAT = 2;
/**
- * The identifier of {@link MultiFloatAction}.
- */
- public static final @ActionType int TYPE_MULTI_FLOAT = 3;
-
- /**
* The identifier of {@link ModeAction}.
*/
public static final @ActionType int TYPE_MODE = 4;
@@ -121,28 +123,32 @@
public static final @ResponseResult int RESPONSE_UNKNOWN = 0;
/**
- * Response code for {@link IControlsActionCallback#accept} indicating that
- * the action has been performed. The action may still fail later and the state may not change.
+ * Response code for the {@code consumer} in
+ * {@link ControlsProviderService#performControlAction} indicating that the action has been
+ * performed. The action may still fail later and the state may not change.
*/
public static final @ResponseResult int RESPONSE_OK = 1;
/**
- * Response code for {@link IControlsActionCallback#accept} indicating that
- * the action has failed.
+ * Response code for the {@code consumer} in
+ * {@link ControlsProviderService#performControlAction} indicating that the action has failed.
*/
public static final @ResponseResult int RESPONSE_FAIL = 2;
/**
- * Response code for {@link IControlsActionCallback#accept} indicating that
- * in order for the action to be performed, acknowledgment from the user is required.
+ * Response code for the {@code consumer} in
+ * {@link ControlsProviderService#performControlAction} indicating that in order for the action
+ * to be performed, acknowledgment from the user is required.
*/
public static final @ResponseResult int RESPONSE_CHALLENGE_ACK = 3;
/**
- * Response code for {@link IControlsActionCallback#accept} indicating that
- * in order for the action to be performed, a PIN is required.
+ * Response code for the {@code consumer} in
+ * {@link ControlsProviderService#performControlAction} indicating that in order for the action
+ * to be performed, a PIN is required.
*/
public static final @ResponseResult int RESPONSE_CHALLENGE_PIN = 4;
/**
- * Response code for {@link IControlsActionCallback#accept} indicating that
- * in order for the action to be performed, an alphanumeric passphrase is required.
+ * Response code for the {@code consumer} in
+ * {@link ControlsProviderService#performControlAction} indicating that in order for the action
+ * to be performed, an alphanumeric passphrase is required.
*/
public static final @ResponseResult int RESPONSE_CHALLENGE_PASSPHRASE = 5;
@@ -228,8 +234,6 @@
return new BooleanAction(bundle);
case TYPE_FLOAT:
return new FloatAction(bundle);
- case TYPE_MULTI_FLOAT:
- return new MultiFloatAction(bundle);
case TYPE_MODE:
return new ModeAction(bundle);
case TYPE_COMMAND:
@@ -243,4 +247,12 @@
return ERROR_ACTION;
}
}
+
+ /**
+ * Returns a singleton {@link ControlAction} used for indicating an error in unparceling.
+ */
+ @NonNull
+ public static ControlAction getErrorAction() {
+ return ERROR_ACTION;
+ }
}
diff --git a/core/java/android/service/controls/actions/MultiFloatAction.java b/core/java/android/service/controls/actions/MultiFloatAction.java
deleted file mode 100644
index e574079..0000000
--- a/core/java/android/service/controls/actions/MultiFloatAction.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2019 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.service.controls.actions;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.os.Bundle;
-import android.util.Log;
-
-import com.android.internal.util.Preconditions;
-
-public final class MultiFloatAction extends ControlAction {
-
- private static final String TAG = "MultiFloatAction";
- private static final @ActionType int TYPE = TYPE_MULTI_FLOAT;
- private static final String KEY_VALUES = "key_values";
-
- private final @NonNull float[] mNewValues;
-
- @Override
- public int getActionType() {
- return TYPE;
- }
-
- public MultiFloatAction(@NonNull String templateId,
- @NonNull float[] newValues,
- @Nullable String challengeValue) {
- super(templateId, challengeValue);
- Preconditions.checkNotNull(newValues);
- if (newValues.length == 0) {
- throw new IllegalArgumentException("newValues array length 0");
- }
- if (newValues.length == 1) {
- Log.w(TAG, "newValues array length 1");
- }
- mNewValues = newValues.clone();
- }
-
- public MultiFloatAction(@NonNull String templateId, @NonNull float[] newValues) {
- this(templateId, newValues, null);
- }
-
- /**
- * @param b
- * @hide
- */
- MultiFloatAction(Bundle b) {
- super(b);
- mNewValues = b.getFloatArray(KEY_VALUES);
- }
-
- @NonNull
- public float[] getNewValues() {
- return mNewValues.clone();
- }
-
- /**
- * @return
- * @hide
- */
- @Override
- @NonNull
- Bundle getDataBundle() {
- Bundle b = super.getDataBundle();
- b.putFloatArray(KEY_VALUES, mNewValues);
- return b;
- }
-}
diff --git a/core/java/android/service/controls/templates/ControlTemplate.java b/core/java/android/service/controls/templates/ControlTemplate.java
index 30efd80..1e16273 100644
--- a/core/java/android/service/controls/templates/ControlTemplate.java
+++ b/core/java/android/service/controls/templates/ControlTemplate.java
@@ -49,18 +49,20 @@
/**
* Singleton representing a {@link Control} with no input.
+ * @hide
*/
public static final @NonNull ControlTemplate NO_TEMPLATE = new ControlTemplate("") {
@Override
public int getTemplateType() {
- return TYPE_NONE;
+ return TYPE_NO_TEMPLATE;
}
};
/**
* Object returned when there is an unparcelling error.
+ * @hide
*/
- public static final @NonNull ControlTemplate ERROR_TEMPLATE = new ControlTemplate("") {
+ private static final @NonNull ControlTemplate ERROR_TEMPLATE = new ControlTemplate("") {
@Override
public int getTemplateType() {
return TYPE_ERROR;
@@ -73,10 +75,9 @@
@Retention(RetentionPolicy.SOURCE)
@IntDef({
TYPE_ERROR,
- TYPE_NONE,
+ TYPE_NO_TEMPLATE,
TYPE_TOGGLE,
TYPE_RANGE,
- TYPE_THUMBNAIL,
TYPE_TOGGLE_RANGE,
TYPE_TEMPERATURE,
TYPE_STATELESS
@@ -84,14 +85,14 @@
public @interface TemplateType {}
/**
- * Type identifier of {@link #ERROR_TEMPLATE}.
+ * Type identifier of the template returned by {@link #getErrorTemplate()}.
*/
public static final @TemplateType int TYPE_ERROR = -1;
/**
- * Type identifier of {@link ControlTemplate#NO_TEMPLATE}.
+ * Type identifier of {@link ControlTemplate#getNoTemplateObject}.
*/
- public static final @TemplateType int TYPE_NONE = 0;
+ public static final @TemplateType int TYPE_NO_TEMPLATE = 0;
/**
* Type identifier of {@link ToggleTemplate}.
@@ -104,11 +105,6 @@
public static final @TemplateType int TYPE_RANGE = 2;
/**
- * Type identifier of {@link ThumbnailTemplate}.
- */
- public static final @TemplateType int TYPE_THUMBNAIL = 3;
-
- /**
* Type identifier of {@link ToggleRangeTemplate}.
*/
public static final @TemplateType int TYPE_TOGGLE_RANGE = 6;
@@ -191,15 +187,13 @@
return new ToggleTemplate(bundle);
case TYPE_RANGE:
return new RangeTemplate(bundle);
- case TYPE_THUMBNAIL:
- return new ThumbnailTemplate(bundle);
case TYPE_TOGGLE_RANGE:
return new ToggleRangeTemplate(bundle);
case TYPE_TEMPERATURE:
return new TemperatureControlTemplate(bundle);
case TYPE_STATELESS:
return new StatelessTemplate(bundle);
- case TYPE_NONE:
+ case TYPE_NO_TEMPLATE:
return NO_TEMPLATE;
case TYPE_ERROR:
default:
@@ -210,4 +204,27 @@
return ERROR_TEMPLATE;
}
}
+
+ /**
+ * @return a singleton {@link ControlTemplate} used for indicating an error in unparceling.
+ */
+ @NonNull
+ public static ControlTemplate getErrorTemplate() {
+ return ERROR_TEMPLATE;
+ }
+
+ /**
+ * Get a singleton {@link ControlTemplate} that has no features.
+ *
+ * This template has no distinctive field, not even an identifier. Used for a {@link Control}
+ * that accepts no type of input, or when there is no known state.
+ *
+ * @return a singleton {@link ControlTemplate} to indicate no specific template is used by
+ * this {@link Control}
+ */
+ @NonNull
+ public static ControlTemplate getNoTemplateObject() {
+ return NO_TEMPLATE;
+ }
+
}
diff --git a/core/java/android/service/controls/templates/TemperatureControlTemplate.java b/core/java/android/service/controls/templates/TemperatureControlTemplate.java
index 0818c7e..96be97a 100644
--- a/core/java/android/service/controls/templates/TemperatureControlTemplate.java
+++ b/core/java/android/service/controls/templates/TemperatureControlTemplate.java
@@ -60,16 +60,34 @@
private static final int NUM_MODES = 6;
+ /**
+ * Use when the current or active mode of the device is not known
+ */
public static final @Mode int MODE_UNKNOWN = 0;
+ /**
+ * Indicates that the current or active mode of the device is off.
+ */
public static final @Mode int MODE_OFF = 1;
+ /**
+ * Indicates that the current or active mode of the device is set to heat.
+ */
public static final @Mode int MODE_HEAT = 2;
+ /**
+ * Indicates that the current or active mode of the device is set to cool.
+ */
public static final @Mode int MODE_COOL = 3;
+ /**
+ * Indicates that the current or active mode of the device is set to heat-cool.
+ */
public static final @Mode int MODE_HEAT_COOL = 4;
+ /**
+ * Indicates that the current or active mode of the device is set to eco.
+ */
public static final @Mode int MODE_ECO = 5;
/**
@@ -85,10 +103,29 @@
})
public @interface ModeFlag {}
+ /**
+ * Flag to indicate that the device supports off mode.
+ */
public static final int FLAG_MODE_OFF = 1 << MODE_OFF;
+
+ /**
+ * Flag to indicate that the device supports heat mode.
+ */
public static final int FLAG_MODE_HEAT = 1 << MODE_HEAT;
+
+ /**
+ * Flag to indicate that the device supports cool mode.
+ */
public static final int FLAG_MODE_COOL = 1 << MODE_COOL;
+
+ /**
+ * Flag to indicate that the device supports heat-cool mode.
+ */
public static final int FLAG_MODE_HEAT_COOL = 1 << MODE_HEAT_COOL;
+
+ /**
+ * Flag to indicate that the device supports eco mode.
+ */
public static final int FLAG_MODE_ECO = 1 << MODE_ECO;
private static final int ALL_FLAGS =
FLAG_MODE_OFF |
diff --git a/core/java/android/service/controls/templates/ThumbnailTemplate.java b/core/java/android/service/controls/templates/ThumbnailTemplate.java
deleted file mode 100644
index 72179f4..0000000
--- a/core/java/android/service/controls/templates/ThumbnailTemplate.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2019 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.service.controls.templates;
-
-import android.annotation.NonNull;
-import android.graphics.drawable.Icon;
-import android.os.Bundle;
-import android.service.controls.Control;
-
-import com.android.internal.util.Preconditions;
-
-/**
- * A template for a {@link Control} that displays an image.
- */
-public final class ThumbnailTemplate extends ControlTemplate {
-
- private static final @TemplateType int TYPE = TYPE_THUMBNAIL;
- private static final String KEY_ICON = "key_icon";
- private static final String KEY_CONTENT_DESCRIPTION = "key_content_description";
-
- private final @NonNull Icon mThumbnail;
- private final @NonNull CharSequence mContentDescription;
-
- /**
- * @param templateId the identifier for this template object
- * @param thumbnail an image to display on the {@link Control}
- * @param contentDescription a description of the image for accessibility.
- */
- public ThumbnailTemplate(@NonNull String templateId, @NonNull Icon thumbnail,
- @NonNull CharSequence contentDescription) {
- super(templateId);
- Preconditions.checkNotNull(thumbnail);
- Preconditions.checkNotNull(contentDescription);
- mThumbnail = thumbnail;
- mContentDescription = contentDescription;
- }
-
- /**
- * @param b
- * @hide
- */
- ThumbnailTemplate(Bundle b) {
- super(b);
- mThumbnail = b.getParcelable(KEY_ICON);
- mContentDescription = b.getCharSequence(KEY_CONTENT_DESCRIPTION, "");
- }
-
- /**
- * The {@link Icon} (image) displayed by this template.
- */
- @NonNull
- public Icon getThumbnail() {
- return mThumbnail;
- }
-
- /**
- * The description of the image returned by {@link ThumbnailTemplate#getThumbnail()}
- */
- @NonNull
- public CharSequence getContentDescription() {
- return mContentDescription;
- }
-
- /**
- * @return {@link ControlTemplate#TYPE_THUMBNAIL}
- */
- @Override
- public int getTemplateType() {
- return TYPE;
- }
-
- /**
- * @return
- * @hide
- */
- @Override
- @NonNull
- Bundle getDataBundle() {
- Bundle b = super.getDataBundle();
- b.putObject(KEY_ICON, mThumbnail);
- b.putObject(KEY_CONTENT_DESCRIPTION, mContentDescription);
- return b;
- }
-}
diff --git a/core/java/android/service/dataloader/DataLoaderService.java b/core/java/android/service/dataloader/DataLoaderService.java
index 5bf1975..d4db79e 100644
--- a/core/java/android/service/dataloader/DataLoaderService.java
+++ b/core/java/android/service/dataloader/DataLoaderService.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.app.Service;
import android.content.Intent;
@@ -172,7 +173,7 @@
@Override
public void prepareImage(InstallationFileParcel[] addedFiles, String[] removedFiles) {
if (!nativePrepareImage(mId, addedFiles, removedFiles)) {
- Slog.w(TAG, "Failed to destroy loader: " + mId);
+ Slog.w(TAG, "Failed to prepare image for data loader: " + mId);
}
}
}
@@ -206,6 +207,7 @@
* @throws IOException if trouble opening the file for writing, such as lack of disk space
* or unavailable media.
*/
+ @RequiresPermission(android.Manifest.permission.INSTALL_PACKAGES)
public void writeData(@NonNull String name, long offsetBytes, long lengthBytes,
@NonNull ParcelFileDescriptor incomingFd) throws IOException {
try {
diff --git a/core/java/android/service/dreams/DreamService.java b/core/java/android/service/dreams/DreamService.java
index 002d4b8..e70311f 100644
--- a/core/java/android/service/dreams/DreamService.java
+++ b/core/java/android/service/dreams/DreamService.java
@@ -609,9 +609,7 @@
*
* @hide
*
- * TODO: Remove @UnsupportedAppUsage.
*/
- @UnsupportedAppUsage
public void setWindowless(boolean windowless) {
mWindowless = windowless;
}
diff --git a/core/java/android/service/notification/NotificationListenerService.java b/core/java/android/service/notification/NotificationListenerService.java
index 0cd96b8..c52b02b 100644
--- a/core/java/android/service/notification/NotificationListenerService.java
+++ b/core/java/android/service/notification/NotificationListenerService.java
@@ -55,7 +55,6 @@
import android.os.UserHandle;
import android.util.ArrayMap;
import android.util.Log;
-import android.util.Slog;
import android.widget.RemoteViews;
import com.android.internal.annotations.GuardedBy;
@@ -1570,6 +1569,7 @@
private boolean mVisuallyInterruptive;
private boolean mIsConversation;
private ShortcutInfo mShortcutInfo;
+ private boolean mIsBubble;
private static final int PARCEL_VERSION = 2;
@@ -1604,6 +1604,7 @@
out.writeBoolean(mVisuallyInterruptive);
out.writeBoolean(mIsConversation);
out.writeParcelable(mShortcutInfo, flags);
+ out.writeBoolean(mIsBubble);
}
/** @hide */
@@ -1639,6 +1640,7 @@
mVisuallyInterruptive = in.readBoolean();
mIsConversation = in.readBoolean();
mShortcutInfo = in.readParcelable(cl);
+ mIsBubble = in.readBoolean();
}
@@ -1844,6 +1846,14 @@
}
/**
+ * Returns whether this notification is actively a bubble.
+ * @hide
+ */
+ public boolean isBubble() {
+ return mIsBubble;
+ }
+
+ /**
* @hide
*/
public @Nullable ShortcutInfo getShortcutInfo() {
@@ -1862,7 +1872,8 @@
int userSentiment, boolean hidden, long lastAudiblyAlertedMs,
boolean noisy, ArrayList<Notification.Action> smartActions,
ArrayList<CharSequence> smartReplies, boolean canBubble,
- boolean visuallyInterruptive, boolean isConversation, ShortcutInfo shortcutInfo) {
+ boolean visuallyInterruptive, boolean isConversation, ShortcutInfo shortcutInfo,
+ boolean isBubble) {
mKey = key;
mRank = rank;
mIsAmbient = importance < NotificationManager.IMPORTANCE_LOW;
@@ -1886,6 +1897,7 @@
mVisuallyInterruptive = visuallyInterruptive;
mIsConversation = isConversation;
mShortcutInfo = shortcutInfo;
+ mIsBubble = isBubble;
}
/**
@@ -1913,7 +1925,8 @@
other.mCanBubble,
other.mVisuallyInterruptive,
other.mIsConversation,
- other.mShortcutInfo);
+ other.mShortcutInfo,
+ other.mIsBubble);
}
/**
@@ -1970,7 +1983,8 @@
&& Objects.equals(mIsConversation, other.mIsConversation)
// Shortcutinfo doesn't have equals either; use id
&& Objects.equals((mShortcutInfo == null ? 0 : mShortcutInfo.getId()),
- (other.mShortcutInfo == null ? 0 : other.mShortcutInfo.getId()));
+ (other.mShortcutInfo == null ? 0 : other.mShortcutInfo.getId()))
+ && Objects.equals(mIsBubble, other.mIsBubble);
}
}
diff --git a/core/java/android/service/notification/StatusBarNotification.java b/core/java/android/service/notification/StatusBarNotification.java
index 74b9136..1beeb65 100644
--- a/core/java/android/service/notification/StatusBarNotification.java
+++ b/core/java/android/service/notification/StatusBarNotification.java
@@ -237,16 +237,24 @@
public StatusBarNotification cloneLight() {
final Notification no = new Notification();
this.notification.cloneInto(no, false); // light copy
- return new StatusBarNotification(this.pkg, this.opPkg,
- this.id, this.tag, this.uid, this.initialPid,
- no, this.user, this.overrideGroupKey, this.postTime);
+ return cloneShallow(no);
}
@Override
public StatusBarNotification clone() {
- return new StatusBarNotification(this.pkg, this.opPkg,
+ return cloneShallow(this.notification.clone());
+ }
+
+ /**
+ * @param notification Some kind of clone of this.notification.
+ * @return A shallow copy of self, with notification in place of this.notification.
+ */
+ StatusBarNotification cloneShallow(Notification notification) {
+ StatusBarNotification result = new StatusBarNotification(this.pkg, this.opPkg,
this.id, this.tag, this.uid, this.initialPid,
- this.notification.clone(), this.user, this.overrideGroupKey, this.postTime);
+ notification, this.user, this.overrideGroupKey, this.postTime);
+ result.setInstanceId(this.mInstanceId);
+ return result;
}
@Override
diff --git a/core/java/android/service/quickaccesswallet/GetWalletCardsCallbackImpl.java b/core/java/android/service/quickaccesswallet/GetWalletCardsCallbackImpl.java
index d2494a5..ae67068 100644
--- a/core/java/android/service/quickaccesswallet/GetWalletCardsCallbackImpl.java
+++ b/core/java/android/service/quickaccesswallet/GetWalletCardsCallbackImpl.java
@@ -24,8 +24,6 @@
import android.text.TextUtils;
import android.util.Log;
-import java.util.List;
-
/**
* Handles response from the {@link QuickAccessWalletService} for {@link GetWalletCardsRequest}
*
@@ -56,7 +54,6 @@
* presented as the selected card.
*/
public void onSuccess(@NonNull GetWalletCardsResponse response) {
- Log.i(TAG, "onSuccess");
if (isValidResponse(response)) {
mHandler.post(() -> onSuccessInternal(response));
} else {
@@ -78,7 +75,6 @@
}
private void onSuccessInternal(GetWalletCardsResponse response) {
- Log.i(TAG, "onSuccessInternal");
if (mCalled) {
Log.w(TAG, "already called");
return;
@@ -86,7 +82,6 @@
mCalled = true;
try {
mCallback.onGetWalletCardsSuccess(response);
- Log.i(TAG, "onSuccessInternal: returned response");
} catch (RemoteException e) {
Log.w(TAG, "Error returning wallet cards", e);
}
@@ -106,29 +101,53 @@
}
private boolean isValidResponse(@NonNull GetWalletCardsResponse response) {
- return response != null
- && response.getWalletCards() != null
- && response.getSelectedIndex() >= 0
- && (response.getWalletCards().isEmpty() // selectedIndex may be 0 when list is empty
- || response.getSelectedIndex() < response.getWalletCards().size())
- && response.getWalletCards().size() < mRequest.getMaxCards()
- && areValidCards(response.getWalletCards());
- }
-
- private boolean areValidCards(List<WalletCard> walletCards) {
- for (WalletCard walletCard : walletCards) {
- if (walletCard == null
- || walletCard.getCardId() == null
- || walletCard.getCardImage() == null
- || TextUtils.isEmpty(walletCard.getContentDescription())
- || walletCard.getPendingIntent() == null) {
+ if (response == null) {
+ Log.w(TAG, "Invalid response: response is null");
+ return false;
+ }
+ if (response.getWalletCards() == null) {
+ Log.w(TAG, "Invalid response: walletCards is null");
+ return false;
+ }
+ if (response.getSelectedIndex() < 0) {
+ Log.w(TAG, "Invalid response: selectedIndex is negative");
+ return false;
+ }
+ if (!response.getWalletCards().isEmpty()
+ && response.getSelectedIndex() >= response.getWalletCards().size()) {
+ Log.w(TAG, "Invalid response: selectedIndex out of bounds");
+ return false;
+ }
+ if (response.getWalletCards().size() > mRequest.getMaxCards()) {
+ Log.w(TAG, "Invalid response: too many cards");
+ return false;
+ }
+ for (WalletCard walletCard : response.getWalletCards()) {
+ if (walletCard == null) {
+ Log.w(TAG, "Invalid response: card is null");
+ return false;
+ }
+ if (walletCard.getCardId() == null) {
+ Log.w(TAG, "Invalid response: cardId is null");
return false;
}
Icon cardImage = walletCard.getCardImage();
+ if (cardImage == null) {
+ Log.w(TAG, "Invalid response: cardImage is null");
+ return false;
+ }
if (cardImage.getType() == Icon.TYPE_BITMAP
- && walletCard.getCardImage().getBitmap().getConfig()
- != Bitmap.Config.HARDWARE) {
- Log.w(TAG, "WalletCard bitmaps should be hardware bitmaps");
+ && cardImage.getBitmap().getConfig() != Bitmap.Config.HARDWARE) {
+ Log.w(TAG, "Invalid response: cardImage bitmaps must be hardware bitmaps");
+ return false;
+ }
+ if (TextUtils.isEmpty(walletCard.getContentDescription())) {
+ Log.w(TAG, "Invalid response: contentDescription is null");
+ return false;
+ }
+ if (walletCard.getPendingIntent() == null) {
+ Log.w(TAG, "Invalid response: pendingIntent is null");
+ return false;
}
}
return true;
diff --git a/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java b/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java
index be9ab11..4f5b139 100644
--- a/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java
+++ b/core/java/android/service/quickaccesswallet/QuickAccessWalletClient.java
@@ -16,19 +16,23 @@
package android.service.quickaccesswallet;
+import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
import android.content.Context;
import android.content.Intent;
+import java.io.Closeable;
+import java.util.concurrent.Executor;
+
/**
* Facilitates accessing cards from the {@link QuickAccessWalletService}.
*
* @hide
*/
@TestApi
-public interface QuickAccessWalletClient {
+public interface QuickAccessWalletClient extends Closeable {
/**
* Create a client for accessing wallet cards from the {@link QuickAccessWalletService}. If the
@@ -92,6 +96,14 @@
@NonNull OnWalletCardsRetrievedCallback callback);
/**
+ * Get wallet cards from the {@link QuickAccessWalletService}.
+ */
+ void getWalletCards(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull GetWalletCardsRequest request,
+ @NonNull OnWalletCardsRetrievedCallback callback);
+
+ /**
* Callback for getWalletCards
*/
interface OnWalletCardsRetrievedCallback {
@@ -111,12 +123,19 @@
void notifyWalletDismissed();
/**
- * Unregister event listener.
+ * Register an event listener.
*/
void addWalletServiceEventListener(@NonNull WalletServiceEventListener listener);
/**
- * Unregister event listener
+ * Register an event listener.
+ */
+ void addWalletServiceEventListener(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull WalletServiceEventListener listener);
+
+ /**
+ * Unregister an event listener
*/
void removeWalletServiceEventListener(@NonNull WalletServiceEventListener listener);
diff --git a/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java b/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java
index 37a8703..e4dd082 100644
--- a/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java
+++ b/core/java/android/service/quickaccesswallet/QuickAccessWalletClientImpl.java
@@ -18,6 +18,7 @@
import static android.service.quickaccesswallet.QuickAccessWalletService.SERVICE_INTERFACE;
+import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.ActivityManager;
@@ -36,16 +37,19 @@
import com.android.internal.widget.LockPatternUtils;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
+import java.util.concurrent.Executor;
/**
* Implements {@link QuickAccessWalletClient}. The client connects, performs requests, waits for
- * responses, and disconnects automatically after a short period of time. The client may
+ * responses, and disconnects automatically one minute after the last call is performed.
+ *
* @hide
*/
public class QuickAccessWalletClientImpl implements QuickAccessWalletClient, ServiceConnection {
@@ -78,15 +82,14 @@
@Override
public boolean isWalletServiceAvailable() {
- boolean available = mServiceInfo != null;
- Log.i(TAG, "isWalletServiceAvailable: " + available);
- return available;
+ return mServiceInfo != null;
}
@Override
public boolean isWalletFeatureAvailable() {
int currentUser = ActivityManager.getCurrentUser();
- return checkUserSetupComplete()
+ return currentUser == UserHandle.USER_SYSTEM
+ && checkUserSetupComplete()
&& checkSecureSetting(Settings.Secure.GLOBAL_ACTIONS_PANEL_ENABLED)
&& !new LockPatternUtils(mContext).isUserInLockdown(currentUser);
}
@@ -101,23 +104,29 @@
public void getWalletCards(
@NonNull GetWalletCardsRequest request,
@NonNull OnWalletCardsRetrievedCallback callback) {
+ getWalletCards(mContext.getMainExecutor(), request, callback);
+ }
- Log.i(TAG, "getWalletCards");
-
+ @Override
+ public void getWalletCards(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull GetWalletCardsRequest request,
+ @NonNull OnWalletCardsRetrievedCallback callback) {
if (!isWalletServiceAvailable()) {
- callback.onWalletCardRetrievalError(new GetWalletCardsError(null, null));
+ executor.execute(
+ () -> callback.onWalletCardRetrievalError(new GetWalletCardsError(null, null)));
return;
}
BaseCallbacks serviceCallback = new BaseCallbacks() {
@Override
public void onGetWalletCardsSuccess(GetWalletCardsResponse response) {
- mHandler.post(() -> callback.onWalletCardsRetrieved(response));
+ executor.execute(() -> callback.onWalletCardsRetrieved(response));
}
@Override
public void onGetWalletCardsFailure(GetWalletCardsError error) {
- mHandler.post(() -> callback.onWalletCardRetrievalError(error));
+ executor.execute(() -> callback.onWalletCardRetrievalError(error));
}
};
@@ -132,11 +141,11 @@
serviceCallback.onGetWalletCardsFailure(new GetWalletCardsError(null, null));
}
});
+
}
@Override
public void selectWalletCard(@NonNull SelectWalletCardRequest request) {
- Log.i(TAG, "selectWalletCard");
if (!isWalletServiceAvailable()) {
return;
}
@@ -153,7 +162,6 @@
if (!isWalletServiceAvailable()) {
return;
}
- Log.i(TAG, "notifyWalletDismissed");
executeApiCall(new ApiCaller("onWalletDismissed") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
@@ -164,15 +172,20 @@
@Override
public void addWalletServiceEventListener(WalletServiceEventListener listener) {
+ addWalletServiceEventListener(mContext.getMainExecutor(), listener);
+ }
+
+ @Override
+ public void addWalletServiceEventListener(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull WalletServiceEventListener listener) {
if (!isWalletServiceAvailable()) {
return;
}
- Log.i(TAG, "registerWalletServiceEventListener");
BaseCallbacks callback = new BaseCallbacks() {
@Override
public void onWalletServiceEvent(WalletServiceEvent event) {
- Log.i(TAG, "onWalletServiceEvent");
- mHandler.post(() -> listener.onWalletServiceEvent(event));
+ executor.execute(() -> listener.onWalletServiceEvent(event));
}
};
@@ -193,7 +206,6 @@
if (!isWalletServiceAvailable()) {
return;
}
- Log.i(TAG, "unregisterWalletServiceEventListener");
executeApiCall(new ApiCaller("unregisterListener") {
@Override
public void performApiCall(IQuickAccessWalletService service) throws RemoteException {
@@ -209,8 +221,12 @@
}
@Override
+ public void close() throws IOException {
+ disconnect();
+ }
+
+ @Override
public void disconnect() {
- Log.i(TAG, "disconnect");
mHandler.post(() -> disconnectInternal(true));
}
@@ -241,18 +257,15 @@
}
private void connect() {
- Log.i(TAG, "connect");
mHandler.post(this::connectInternal);
}
private void connectInternal() {
- Log.i(TAG, "connectInternal");
if (mServiceInfo == null) {
Log.w(TAG, "Wallet service unavailable");
return;
}
if (mIsConnected) {
- Log.w(TAG, "already connected");
return;
}
mIsConnected = true;
@@ -264,23 +277,14 @@
}
private void onConnectedInternal(IQuickAccessWalletService service) {
- Log.i(TAG, "onConnectedInternal");
if (!mIsConnected) {
Log.w(TAG, "onConnectInternal but connection closed");
mService = null;
return;
}
mService = service;
- Log.i(TAG, "onConnectedInternal success: request queue size " + mRequestQueue.size());
for (ApiCaller apiCaller : new ArrayList<>(mRequestQueue)) {
- try {
- apiCaller.performApiCall(mService);
- } catch (RemoteException e) {
- Log.e(TAG, "onConnectedInternal error", e);
- apiCaller.onApiError();
- disconnect();
- break;
- }
+ performApiCallInternal(apiCaller, mService);
mRequestQueue.remove(apiCaller);
}
}
@@ -290,7 +294,6 @@
* posting a new delayed message.
*/
private void resetServiceConnectionTimeout() {
- Log.i(TAG, "resetServiceConnectionTimeout");
mHandler.removeMessages(MSG_TIMEOUT_SERVICE);
mHandler.postDelayed(
() -> disconnectInternal(true),
@@ -299,13 +302,11 @@
}
private void disconnectInternal(boolean clearEventListeners) {
- Log.i(TAG, "disconnectInternal: " + clearEventListeners);
if (!mIsConnected) {
Log.w(TAG, "already disconnected");
return;
}
if (clearEventListeners && !mEventListeners.isEmpty()) {
- Log.i(TAG, "disconnectInternal: clear event listeners");
for (WalletServiceEventListener listener : mEventListeners.keySet()) {
removeWalletServiceEventListener(listener);
}
@@ -320,29 +321,33 @@
}
private void executeApiCall(ApiCaller apiCaller) {
- Log.i(TAG, "execute: " + apiCaller.mDesc);
mHandler.post(() -> executeInternal(apiCaller));
}
- private void executeInternal(ApiCaller apiCall) {
- Log.i(TAG, "executeInternal: " + apiCall.mDesc);
+ private void executeInternal(ApiCaller apiCaller) {
if (mIsConnected && mService != null) {
- try {
- apiCall.performApiCall(mService);
- Log.i(TAG, "executeInternal success: " + apiCall.mDesc);
- resetServiceConnectionTimeout();
- } catch (RemoteException e) {
- Log.w(TAG, "executeInternal error: " + apiCall.mDesc, e);
- apiCall.onApiError();
- disconnect();
- }
+ performApiCallInternal(apiCaller, mService);
} else {
- Log.i(TAG, "executeInternal: queued" + apiCall.mDesc);
- mRequestQueue.add(apiCall);
+ mRequestQueue.add(apiCaller);
connect();
}
}
+ private void performApiCallInternal(ApiCaller apiCaller, IQuickAccessWalletService service) {
+ if (service == null) {
+ apiCaller.onApiError();
+ return;
+ }
+ try {
+ apiCaller.performApiCall(service);
+ resetServiceConnectionTimeout();
+ } catch (RemoteException e) {
+ Log.w(TAG, "executeInternal error: " + apiCaller.mDesc, e);
+ apiCaller.onApiError();
+ disconnect();
+ }
+ }
+
private abstract static class ApiCaller {
private final String mDesc;
@@ -350,7 +355,8 @@
this.mDesc = desc;
}
- abstract void performApiCall(IQuickAccessWalletService service) throws RemoteException;
+ abstract void performApiCall(IQuickAccessWalletService service)
+ throws RemoteException;
void onApiError() {
Log.w(TAG, "api error: " + mDesc);
@@ -359,7 +365,6 @@
@Override // ServiceConnection
public void onServiceConnected(ComponentName name, IBinder binder) {
- Log.i(TAG, "onServiceConnected: " + name);
IQuickAccessWalletService service = IQuickAccessWalletService.Stub.asInterface(binder);
mHandler.post(() -> onConnectedInternal(service));
}
@@ -367,19 +372,16 @@
@Override // ServiceConnection
public void onServiceDisconnected(ComponentName name) {
// Do not disconnect, as we may later be re-connected
- Log.w(TAG, "onServiceDisconnected");
}
@Override // ServiceConnection
public void onBindingDied(ComponentName name) {
// This is a recoverable error but the client will need to reconnect.
- Log.w(TAG, "onBindingDied");
disconnect();
}
@Override // ServiceConnection
public void onNullBinding(ComponentName name) {
- Log.w(TAG, "onNullBinding");
disconnect();
}
diff --git a/core/java/android/service/quickaccesswallet/QuickAccessWalletServiceInfo.java b/core/java/android/service/quickaccesswallet/QuickAccessWalletServiceInfo.java
index 23173a8..31e51bb 100644
--- a/core/java/android/service/quickaccesswallet/QuickAccessWalletServiceInfo.java
+++ b/core/java/android/service/quickaccesswallet/QuickAccessWalletServiceInfo.java
@@ -66,13 +66,11 @@
static QuickAccessWalletServiceInfo tryCreate(@NonNull Context context) {
ComponentName defaultPaymentApp = getDefaultPaymentApp(context);
if (defaultPaymentApp == null) {
- Log.d(TAG, "create: default payment app not set");
return null;
}
ServiceInfo serviceInfo = getWalletServiceInfo(context, defaultPaymentApp.getPackageName());
if (serviceInfo == null) {
- Log.d(TAG, "create: unable to resolve service intent");
return null;
}
diff --git a/core/java/android/service/quickaccesswallet/WalletCard.java b/core/java/android/service/quickaccesswallet/WalletCard.java
index e6ae0ab..b09d2e9 100644
--- a/core/java/android/service/quickaccesswallet/WalletCard.java
+++ b/core/java/android/service/quickaccesswallet/WalletCard.java
@@ -180,7 +180,7 @@
* GetWalletCardsRequest#getCardWidthPx()} and a height of {@link
* GetWalletCardsRequest#getCardHeightPx()}. If the card image
* does not have these dimensions, it may appear distorted when it
- * is scaled to fit these dimensions on screen. Bitmaps should be
+ * is scaled to fit these dimensions on screen. Bitmaps must be
* of type {@link android.graphics.Bitmap.Config#HARDWARE} for
* performance reasons.
* @param contentDescription The content description of the card image. This field is
diff --git a/core/java/android/service/textclassifier/TextClassifierService.java b/core/java/android/service/textclassifier/TextClassifierService.java
index 3ff6f54..9dfbc28 100644
--- a/core/java/android/service/textclassifier/TextClassifierService.java
+++ b/core/java/android/service/textclassifier/TextClassifierService.java
@@ -41,7 +41,6 @@
import android.view.textclassifier.ConversationActions;
import android.view.textclassifier.SelectionEvent;
import android.view.textclassifier.TextClassification;
-import android.view.textclassifier.TextClassificationConstants;
import android.view.textclassifier.TextClassificationContext;
import android.view.textclassifier.TextClassificationManager;
import android.view.textclassifier.TextClassificationSessionId;
@@ -405,27 +404,19 @@
*/
@NonNull
public static TextClassifier getDefaultTextClassifierImplementation(@NonNull Context context) {
- final TextClassificationManager tcm =
- context.getSystemService(TextClassificationManager.class);
- if (tcm == null) {
+ final String defaultTextClassifierPackageName =
+ context.getPackageManager().getDefaultTextClassifierPackageName();
+ if (TextUtils.isEmpty(defaultTextClassifierPackageName)) {
return TextClassifier.NO_OP;
}
- TextClassificationConstants settings = new TextClassificationConstants();
- if (settings.getUseDefaultTextClassifierAsDefaultImplementation()) {
- final String defaultTextClassifierPackageName =
- context.getPackageManager().getDefaultTextClassifierPackageName();
- if (TextUtils.isEmpty(defaultTextClassifierPackageName)) {
- return TextClassifier.NO_OP;
- }
- if (defaultTextClassifierPackageName.equals(context.getPackageName())) {
- throw new RuntimeException(
- "The default text classifier itself should not call the"
- + "getDefaultTextClassifierImplementation() method.");
- }
- return tcm.getTextClassifier(TextClassifier.DEFAULT_SERVICE);
- } else {
- return tcm.getTextClassifier(TextClassifier.LOCAL);
+ if (defaultTextClassifierPackageName.equals(context.getPackageName())) {
+ throw new RuntimeException(
+ "The default text classifier itself should not call the"
+ + "getDefaultTextClassifierImplementation() method.");
}
+ final TextClassificationManager tcm =
+ context.getSystemService(TextClassificationManager.class);
+ return tcm.getTextClassifier(TextClassifier.DEFAULT_SYSTEM);
}
/** @hide **/
diff --git a/core/java/android/service/voice/VoiceInteractionSession.java b/core/java/android/service/voice/VoiceInteractionSession.java
index 8e6f77b..4a0dd87 100644
--- a/core/java/android/service/voice/VoiceInteractionSession.java
+++ b/core/java/android/service/voice/VoiceInteractionSession.java
@@ -1314,7 +1314,8 @@
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(mContext);
int res = mSystemService.startVoiceActivity(mToken, intent,
- intent.resolveType(mContext.getContentResolver()), mContext.getFeatureId());
+ intent.resolveType(mContext.getContentResolver()),
+ mContext.getAttributionTag());
Instrumentation.checkStartActivityResult(res, intent);
} catch (RemoteException e) {
}
@@ -1342,7 +1343,8 @@
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(mContext);
int res = mSystemService.startAssistantActivity(mToken, intent,
- intent.resolveType(mContext.getContentResolver()), mContext.getFeatureId());
+ intent.resolveType(mContext.getContentResolver()),
+ mContext.getAttributionTag());
Instrumentation.checkStartActivityResult(res, intent);
} catch (RemoteException e) {
}
diff --git a/core/java/android/service/wallpaper/WallpaperService.java b/core/java/android/service/wallpaper/WallpaperService.java
index bf3c088..f531e12 100644
--- a/core/java/android/service/wallpaper/WallpaperService.java
+++ b/core/java/android/service/wallpaper/WallpaperService.java
@@ -124,8 +124,6 @@
private static final int MSG_REQUEST_WALLPAPER_COLORS = 10050;
private static final int MSG_SCALE = 10100;
- private static final float MAX_SCALE = 1.15f;
-
private static final int NOTIFY_COLORS_RATE_LIMIT_MS = 1000;
private final ArrayList<Engine> mActiveEngines
@@ -351,7 +349,7 @@
@Override
public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
- boolean sync) {
+ float zoom, boolean sync) {
synchronized (mLock) {
if (DEBUG) Log.v(TAG, "Dispatch wallpaper offsets: " + x + ", " + y);
mPendingXOffset = x;
@@ -366,6 +364,8 @@
Message msg = mCaller.obtainMessage(MSG_WALLPAPER_OFFSETS);
mCaller.sendMessage(msg);
}
+ Message msg = mCaller.obtainMessageI(MSG_SCALE, Float.floatToIntBits(zoom));
+ mCaller.sendMessage(msg);
}
}
@@ -462,6 +462,18 @@
}
/**
+ * This will be called when the wallpaper is first started. If true is returned, the system
+ * will zoom in the wallpaper by default and zoom it out as the user interacts,
+ * to create depth. Otherwise, zoom will have to be handled manually
+ * in {@link #onZoomChanged(float)}.
+ *
+ * @hide
+ */
+ public boolean shouldZoomOutWallpaper() {
+ return false;
+ }
+
+ /**
* Control whether this wallpaper will receive raw touch events
* from the window manager as the user interacts with the window
* that is currently displaying the wallpaper. By default they
@@ -870,6 +882,7 @@
Log.w(TAG, "Failed to add window while updating wallpaper surface.");
return;
}
+ mSession.setShouldZoomOutWallpaper(mWindow, shouldZoomOutWallpaper());
mCreated = true;
mInputEventReceiver = new WallpaperInputEventReceiver(
@@ -964,7 +977,6 @@
c.surfaceCreated(mSurfaceHolder);
}
}
- onZoomChanged(0f);
}
redrawNeeded |= creating || (relayoutResult
@@ -1125,7 +1137,6 @@
mIsInAmbientMode = inAmbientMode;
if (mCreated) {
onAmbientModeChanged(inAmbientMode, animationDuration);
- setZoom(0);
}
}
}
diff --git a/core/java/android/speech/SpeechRecognizer.java b/core/java/android/speech/SpeechRecognizer.java
index e93ba16..92f3538 100644
--- a/core/java/android/speech/SpeechRecognizer.java
+++ b/core/java/android/speech/SpeechRecognizer.java
@@ -342,7 +342,7 @@
}
try {
mService.startListening(recognizerIntent, mListener, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
if (DBG) Log.d(TAG, "service start listening command succeded");
} catch (final RemoteException e) {
Log.e(TAG, "startListening() failed", e);
@@ -357,7 +357,7 @@
}
try {
mService.stopListening(mListener, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
if (DBG) Log.d(TAG, "service stop listening command succeded");
} catch (final RemoteException e) {
Log.e(TAG, "stopListening() failed", e);
@@ -371,7 +371,7 @@
return;
}
try {
- mService.cancel(mListener, mContext.getOpPackageName(), mContext.getFeatureId());
+ mService.cancel(mListener, mContext.getOpPackageName(), mContext.getAttributionTag());
if (DBG) Log.d(TAG, "service cancel command succeded");
} catch (final RemoteException e) {
Log.e(TAG, "cancel() failed", e);
@@ -400,7 +400,8 @@
public void destroy() {
if (mService != null) {
try {
- mService.cancel(mListener, mContext.getOpPackageName(), mContext.getFeatureId());
+ mService.cancel(mListener, mContext.getOpPackageName(),
+ mContext.getAttributionTag());
} catch (final RemoteException e) {
// Not important
}
diff --git a/core/java/android/telephony/TelephonyRegistryManager.java b/core/java/android/telephony/TelephonyRegistryManager.java
index 7238b12..ab9df56 100644
--- a/core/java/android/telephony/TelephonyRegistryManager.java
+++ b/core/java/android/telephony/TelephonyRegistryManager.java
@@ -116,7 +116,7 @@
mSubscriptionChangedListenerMap.put(listener, callback);
try {
sRegistry.addOnSubscriptionsChangedListener(mContext.getOpPackageName(),
- mContext.getFeatureId(), callback);
+ mContext.getAttributionTag(), callback);
} catch (RemoteException ex) {
// system server crash
}
@@ -175,7 +175,7 @@
mOpportunisticSubscriptionChangedListenerMap.put(listener, callback);
try {
sRegistry.addOnOpportunisticSubscriptionsChangedListener(mContext.getOpPackageName(),
- mContext.getFeatureId(), callback);
+ mContext.getAttributionTag(), callback);
} catch (RemoteException ex) {
// system server crash
}
diff --git a/core/java/android/text/util/Linkify.java b/core/java/android/text/util/Linkify.java
index 2aca36a..82c7ea7 100644
--- a/core/java/android/text/util/Linkify.java
+++ b/core/java/android/text/util/Linkify.java
@@ -19,6 +19,7 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.app.ActivityThread;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.telephony.PhoneNumberUtils;
@@ -663,9 +664,11 @@
private static void gatherTelLinks(ArrayList<LinkSpec> links, Spannable s,
@Nullable Context context) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
+ final Context ctx = (context != null) ? context : ActivityThread.currentApplication();
+ final String regionCode = (ctx != null) ? ctx.getSystemService(TelephonyManager.class).
+ getSimCountryIso().toUpperCase(Locale.US) : Locale.getDefault().getCountry();
Iterable<PhoneNumberMatch> matches = phoneUtil.findNumbers(s.toString(),
- TelephonyManager.getDefaultSimCountryIso().toUpperCase(Locale.US),
- Leniency.POSSIBLE, Long.MAX_VALUE);
+ regionCode, Leniency.POSSIBLE, Long.MAX_VALUE);
for (PhoneNumberMatch match : matches) {
LinkSpec spec = new LinkSpec();
spec.url = "tel:" + PhoneNumberUtils.normalizeNumber(match.rawString());
diff --git a/core/java/android/timezone/CountryTimeZones.java b/core/java/android/timezone/CountryTimeZones.java
index ee3a8a7..a8db50e 100644
--- a/core/java/android/timezone/CountryTimeZones.java
+++ b/core/java/android/timezone/CountryTimeZones.java
@@ -140,7 +140,7 @@
@Override
public String toString() {
return "OffsetResult{"
- + "mTimeZone=" + mTimeZone
+ + "mTimeZone(ID)=" + mTimeZone.getID()
+ ", mIsOnlyMatch=" + mIsOnlyMatch
+ '}';
}
diff --git a/core/java/android/util/FeatureFlagUtils.java b/core/java/android/util/FeatureFlagUtils.java
index 6b87a10..cfbe393 100644
--- a/core/java/android/util/FeatureFlagUtils.java
+++ b/core/java/android/util/FeatureFlagUtils.java
@@ -71,7 +71,7 @@
// introduced in R and will be removed in the next release (b/148367230).
DEFAULT_FLAGS.put(SETTINGS_DO_NOT_RESTORE_PRESERVED, "false");
- DEFAULT_FLAGS.put("settings_tether_all_in_one", "true");
+ DEFAULT_FLAGS.put("settings_tether_all_in_one", "false");
DEFAULT_FLAGS.put(SETTINGS_SCHEDULES_FLAG, "false");
DEFAULT_FLAGS.put("settings_contextual_home2", "false");
}
diff --git a/core/java/android/util/apk/ApkSignatureSchemeV3Verifier.java b/core/java/android/util/apk/ApkSignatureSchemeV3Verifier.java
index abd04cc..79eb9f6 100644
--- a/core/java/android/util/apk/ApkSignatureSchemeV3Verifier.java
+++ b/core/java/android/util/apk/ApkSignatureSchemeV3Verifier.java
@@ -16,6 +16,8 @@
package android.util.apk;
+import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_CHUNKED_SHA256;
+import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_CHUNKED_SHA512;
import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_VERITY_CHUNKED_SHA256;
import static android.util.apk.ApkSigningBlockUtils.compareSignatureAlgorithm;
import static android.util.apk.ApkSigningBlockUtils.getContentDigestAlgorithmJcaDigestAlgorithm;
@@ -211,6 +213,12 @@
verityDigest, apk.length(), signatureInfo);
}
+ if (contentDigests.containsKey(CONTENT_DIGEST_CHUNKED_SHA512)) {
+ result.digest = contentDigests.get(CONTENT_DIGEST_CHUNKED_SHA512);
+ } else if (contentDigests.containsKey(CONTENT_DIGEST_CHUNKED_SHA256)) {
+ result.digest = contentDigests.get(CONTENT_DIGEST_CHUNKED_SHA256);
+ }
+
return result;
}
@@ -568,6 +576,7 @@
public final VerifiedProofOfRotation por;
public byte[] verityRootHash;
+ public byte[] digest;
public VerifiedSigner(X509Certificate[] certs, VerifiedProofOfRotation por) {
this.certs = certs;
diff --git a/core/java/android/util/apk/ApkSignatureSchemeV4Verifier.java b/core/java/android/util/apk/ApkSignatureSchemeV4Verifier.java
index b6b8089..8c240d9 100644
--- a/core/java/android/util/apk/ApkSignatureSchemeV4Verifier.java
+++ b/core/java/android/util/apk/ApkSignatureSchemeV4Verifier.java
@@ -16,13 +16,32 @@
package android.util.apk;
+import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaKeyAlgorithm;
+import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaSignatureAlgorithm;
+import static android.util.apk.ApkSigningBlockUtils.isSupportedSignatureAlgorithm;
+
import android.os.incremental.IncrementalManager;
+import android.os.incremental.V4Signature;
+import android.util.Pair;
+import java.io.ByteArrayInputStream;
import java.io.File;
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.SignatureException;
import java.security.cert.Certificate;
-
-import sun.security.pkcs.PKCS7;
-import sun.security.pkcs.ParsingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Arrays;
/**
* APK Signature Scheme v4 verifier.
@@ -30,24 +49,118 @@
* @hide for internal use only.
*/
public class ApkSignatureSchemeV4Verifier {
+ /**
+ * Extracts and verifies APK Signature Scheme v4 signatures of the provided APK and returns the
+ * certificates associated with each signer.
+ */
+ public static VerifiedSigner extractCertificates(String apkFile)
+ throws SignatureNotFoundException, SecurityException {
+ final File apk = new File(apkFile);
+ final byte[] signatureBytes = IncrementalManager.unsafeGetFileSignature(
+ apk.getAbsolutePath());
+ if (signatureBytes == null || signatureBytes.length == 0) {
+ throw new SignatureNotFoundException("Failed to obtain signature bytes from IncFS.");
+ }
+
+ final V4Signature signature;
+ final V4Signature.HashingInfo hashingInfo;
+ final V4Signature.SigningInfo signingInfo;
+ try {
+ signature = V4Signature.readFrom(signatureBytes);
+
+ if (!signature.isVersionSupported()) {
+ throw new SecurityException(
+ "v4 signature version " + signature.version + " is not supported");
+ }
+
+ hashingInfo = V4Signature.HashingInfo.fromByteArray(signature.hashingInfo);
+ signingInfo = V4Signature.SigningInfo.fromByteArray(signature.signingInfo);
+ } catch (IOException e) {
+ throw new SignatureNotFoundException("Failed to read V4 signature.", e);
+ }
+
+ final byte[] signedData = V4Signature.getSigningData(apk.length(), hashingInfo,
+ signingInfo);
+
+ return verifySigner(signingInfo, signedData);
+ }
+
+ private static VerifiedSigner verifySigner(V4Signature.SigningInfo signingInfo,
+ final byte[] signedData) throws SecurityException {
+ if (!isSupportedSignatureAlgorithm(signingInfo.signatureAlgorithmId)) {
+ throw new SecurityException("No supported signatures found");
+ }
+
+ final int signatureAlgorithmId = signingInfo.signatureAlgorithmId;
+ final byte[] signatureBytes = signingInfo.signature;
+ final byte[] publicKeyBytes = signingInfo.publicKey;
+ final byte[] encodedCert = signingInfo.certificate;
+
+ String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(signatureAlgorithmId);
+ Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams =
+ getSignatureAlgorithmJcaSignatureAlgorithm(signatureAlgorithmId);
+ String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
+ AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
+ boolean sigVerified;
+ try {
+ PublicKey publicKey =
+ KeyFactory.getInstance(keyAlgorithm)
+ .generatePublic(new X509EncodedKeySpec(publicKeyBytes));
+ Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
+ sig.initVerify(publicKey);
+ if (jcaSignatureAlgorithmParams != null) {
+ sig.setParameter(jcaSignatureAlgorithmParams);
+ }
+ sig.update(signedData);
+ sigVerified = sig.verify(signatureBytes);
+ } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException
+ | InvalidAlgorithmParameterException | SignatureException e) {
+ throw new SecurityException(
+ "Failed to verify " + jcaSignatureAlgorithm + " signature", e);
+ }
+ if (!sigVerified) {
+ throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
+ }
+
+ // Signature over signedData has verified.
+ CertificateFactory certFactory;
+ try {
+ certFactory = CertificateFactory.getInstance("X.509");
+ } catch (CertificateException e) {
+ throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
+ }
+
+ X509Certificate certificate;
+ try {
+ certificate = (X509Certificate)
+ certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
+ } catch (CertificateException e) {
+ throw new SecurityException("Failed to decode certificate", e);
+ }
+ certificate = new VerbatimX509Certificate(certificate, encodedCert);
+
+ byte[] certificatePublicKeyBytes = certificate.getPublicKey().getEncoded();
+ if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
+ throw new SecurityException(
+ "Public key mismatch between certificate and signature record");
+ }
+
+ return new VerifiedSigner(new Certificate[]{certificate}, signingInfo.v3Digest);
+ }
/**
- * Extracts APK Signature Scheme v4 signatures of the provided APK and returns the certificates
- * associated with each signer.
+ * Verified APK Signature Scheme v4 signer, including V3 digest.
+ *
+ * @hide for internal use only.
*/
- public static Certificate[] extractCertificates(String apkFile)
- throws SignatureNotFoundException, SecurityException {
- final byte[] rawSignature = IncrementalManager.unsafeGetFileSignature(
- new File(apkFile).getAbsolutePath());
- if (rawSignature == null || rawSignature.length == 0) {
- throw new SignatureNotFoundException("Failed to obtain raw signature from IncFS.");
+ public static class VerifiedSigner {
+ public final Certificate[] certs;
+ public byte[] v3Digest;
+
+ public VerifiedSigner(Certificate[] certs, byte[] v3Digest) {
+ this.certs = certs;
+ this.v3Digest = v3Digest;
}
- try {
- PKCS7 pkcs7 = new PKCS7(rawSignature);
- return pkcs7.getCertificates();
- } catch (ParsingException e) {
- throw new SecurityException("Failed to parse signature and extract certificates", e);
- }
}
}
diff --git a/core/java/android/util/apk/ApkSignatureVerifier.java b/core/java/android/util/apk/ApkSignatureVerifier.java
index f325c21..c1cee48 100644
--- a/core/java/android/util/apk/ApkSignatureVerifier.java
+++ b/core/java/android/util/apk/ApkSignatureVerifier.java
@@ -168,7 +168,7 @@
/**
* Verifies the provided APK using V4 schema.
*
- * @param verifyFull whether to verify all contents of this APK or just collect certificates.
+ * @param verifyFull whether to verify (V4 vs V3) or just collect certificates.
* @return the certificates associated with each signer.
* @throws SignatureNotFoundException if there are no V4 signatures in the APK
* @throws PackageParserException if there was a problem collecting certificates
@@ -178,30 +178,34 @@
throws SignatureNotFoundException, PackageParserException {
Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, verifyFull ? "verifyV4" : "certsOnlyV4");
try {
- Certificate[] certs = ApkSignatureSchemeV4Verifier.extractCertificates(apkPath);
- Certificate[][] signerCerts = new Certificate[][]{certs};
+ ApkSignatureSchemeV4Verifier.VerifiedSigner vSigner =
+ ApkSignatureSchemeV4Verifier.extractCertificates(apkPath);
+ Certificate[][] signerCerts = new Certificate[][]{vSigner.certs};
Signature[] signerSigs = convertToSignatures(signerCerts);
if (verifyFull) {
- // v4 is an add-on and requires v2/v3 signature to validate against its certificates
- final PackageParser.SigningDetails nonstreaming = verifyV3AndBelowSignatures(
- apkPath, minSignatureSchemeVersion, false);
- if (nonstreaming.signatureSchemeVersion <= SignatureSchemeVersion.JAR) {
+ // v4 is an add-on and requires v3 signature to validate against its certificates
+ ApkSignatureSchemeV3Verifier.VerifiedSigner nonstreaming =
+ ApkSignatureSchemeV3Verifier.unsafeGetCertsWithoutVerification(apkPath);
+ Certificate[][] nonstreamingCerts = new Certificate[][]{nonstreaming.certs};
+ Signature[] nonstreamingSigs = convertToSignatures(nonstreamingCerts);
+
+ if (nonstreamingSigs.length != signerSigs.length) {
throw new SecurityException(
- "V4 signing block can only be verified along with V2 and above.");
- }
- if (nonstreaming.signatures.length == 0
- || nonstreaming.signatures.length != signerSigs.length) {
- throw new SecurityException("Invalid number of signatures in "
- + nonstreaming.signatureSchemeVersion);
+ "Invalid number of certificates: " + nonstreaming.certs.length);
}
for (int i = 0, size = signerSigs.length; i < size; ++i) {
- if (!nonstreaming.signatures[i].equals(signerSigs[i])) {
- throw new SecurityException("V4 signature certificate does not match "
- + nonstreaming.signatureSchemeVersion);
+ if (!nonstreamingSigs[i].equals(signerSigs[i])) {
+ throw new SecurityException("V4 signature certificate does not match V3");
}
}
+
+ // TODO(b/151240006): add support for v2 digest and make it mandatory.
+ if (!ArrayUtils.isEmpty(vSigner.v3Digest) && !ArrayUtils.equals(vSigner.v3Digest,
+ nonstreaming.digest, vSigner.v3Digest.length)) {
+ throw new SecurityException("V3 digest in V4 signature does not match V3");
+ }
}
return new PackageParser.SigningDetails(signerSigs,
diff --git a/core/java/android/util/apk/SourceStampVerifier.java b/core/java/android/util/apk/SourceStampVerifier.java
index 759c864..a7ae32d 100644
--- a/core/java/android/util/apk/SourceStampVerifier.java
+++ b/core/java/android/util/apk/SourceStampVerifier.java
@@ -24,6 +24,7 @@
import static android.util.apk.ApkSigningBlockUtils.readLengthPrefixedByteArray;
import android.util.Pair;
+import android.util.Slog;
import android.util.jar.StrictJarFile;
import libcore.io.IoUtils;
@@ -43,6 +44,7 @@
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
+import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@@ -68,6 +70,8 @@
*/
public abstract class SourceStampVerifier {
+ private static final String TAG = "SourceStampVerifier";
+
private static final int APK_SIGNATURE_SCHEME_V2_BLOCK_ID = 0x7109871a;
private static final int APK_SIGNATURE_SCHEME_V3_BLOCK_ID = 0xf05368c0;
private static final int SOURCE_STAMP_BLOCK_ID = 0x2b09189e;
@@ -78,29 +82,59 @@
/** Hidden constructor to prevent instantiation. */
private SourceStampVerifier() {}
+ /** Verifies SourceStamp present in a list of APKs. */
+ public static SourceStampVerificationResult verify(List<String> apkFiles) {
+ Certificate stampCertificate = null;
+ for (String apkFile : apkFiles) {
+ SourceStampVerificationResult sourceStampVerificationResult = verify(apkFile);
+ if (!sourceStampVerificationResult.isPresent()
+ || !sourceStampVerificationResult.isVerified()) {
+ return sourceStampVerificationResult;
+ }
+ if (stampCertificate != null
+ && !stampCertificate.equals(sourceStampVerificationResult.getCertificate())) {
+ return SourceStampVerificationResult.notVerified();
+ }
+ stampCertificate = sourceStampVerificationResult.getCertificate();
+ }
+ return SourceStampVerificationResult.verified(stampCertificate);
+ }
+
/** Verifies SourceStamp present in the provided APK. */
public static SourceStampVerificationResult verify(String apkFile) {
+ StrictJarFile apkJar = null;
try (RandomAccessFile apk = new RandomAccessFile(apkFile, "r")) {
- return verify(apk);
- } catch (Exception e) {
- // Any exception in the SourceStamp verification returns a non-verified SourceStamp
- // outcome without affecting the outcome of any of the other signature schemes.
- return SourceStampVerificationResult.notVerified();
+ apkJar =
+ new StrictJarFile(
+ apkFile,
+ /* verify= */ false,
+ /* signatureSchemeRollbackProtectionsEnforced= */ false);
+ byte[] sourceStampCertificateDigest = getSourceStampCertificateDigest(apkJar);
+ if (sourceStampCertificateDigest == null) {
+ // SourceStamp certificate hash file not found, which means that there is not
+ // SourceStamp present.
+ return SourceStampVerificationResult.notPresent();
+ }
+ return verify(apk, sourceStampCertificateDigest);
+ } catch (IOException e) {
+ // Any exception in reading the APK returns a non-present SourceStamp outcome
+ // without affecting the outcome of any of the other signature schemes.
+ return SourceStampVerificationResult.notPresent();
+ } finally {
+ closeApkJar(apkJar);
}
}
- private static SourceStampVerificationResult verify(RandomAccessFile apk)
- throws IOException, SignatureNotFoundException {
- byte[] sourceStampCertificateDigest = getSourceStampCertificateDigest(apk);
- if (sourceStampCertificateDigest == null) {
- // SourceStamp certificate hash file not found, which means that there is not
- // SourceStamp present.
- return SourceStampVerificationResult.notPresent();
+ private static SourceStampVerificationResult verify(
+ RandomAccessFile apk, byte[] sourceStampCertificateDigest) {
+ try {
+ SignatureInfo signatureInfo =
+ ApkSigningBlockUtils.findSignature(apk, SOURCE_STAMP_BLOCK_ID);
+ Map<Integer, byte[]> apkContentDigests = getApkContentDigests(apk);
+ return verify(signatureInfo, apkContentDigests, sourceStampCertificateDigest);
+ } catch (IOException | SignatureNotFoundException e) {
+ return SourceStampVerificationResult.notVerified();
}
- SignatureInfo signatureInfo =
- ApkSigningBlockUtils.findSignature(apk, SOURCE_STAMP_BLOCK_ID);
- Map<Integer, byte[]> apkContentDigests = getApkContentDigests(apk);
- return verify(signatureInfo, apkContentDigests, sourceStampCertificateDigest);
}
private static SourceStampVerificationResult verify(
@@ -255,22 +289,17 @@
return apkContentDigests;
}
- private static byte[] getSourceStampCertificateDigest(RandomAccessFile apk) throws IOException {
- StrictJarFile apkJar =
- new StrictJarFile(
- apk.getFD(),
- /* verify= */ false,
- /* signatureSchemeRollbackProtectionsEnforced= */ false);
- ZipEntry zipEntry = apkJar.findEntry(SOURCE_STAMP_CERTIFICATE_HASH_ZIP_ENTRY_NAME);
- if (zipEntry == null) {
- // SourceStamp certificate hash file not found, which means that there is not
- // SourceStamp present.
- return null;
- }
+ private static byte[] getSourceStampCertificateDigest(StrictJarFile apkJar) throws IOException {
InputStream inputStream = null;
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
+ ZipEntry zipEntry = apkJar.findEntry(SOURCE_STAMP_CERTIFICATE_HASH_ZIP_ENTRY_NAME);
+ if (zipEntry == null) {
+ // SourceStamp certificate hash file not found, which means that there is not
+ // SourceStamp present.
+ return null;
+ }
inputStream = apkJar.getInputStream(zipEntry);
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// Trying to read the certificate digest, which should be less than 1024 bytes.
byte[] buffer = new byte[1024];
@@ -299,4 +328,15 @@
}
return result.array();
}
+
+ private static void closeApkJar(StrictJarFile apkJar) {
+ try {
+ if (apkJar == null) {
+ return;
+ }
+ apkJar.close();
+ } catch (IOException e) {
+ Slog.e(TAG, "Could not close APK jar", e);
+ }
+ }
}
diff --git a/core/java/android/view/ITaskOrganizer.aidl b/core/java/android/view/ITaskOrganizer.aidl
index 5ccdd30..565f694 100644
--- a/core/java/android/view/ITaskOrganizer.aidl
+++ b/core/java/android/view/ITaskOrganizer.aidl
@@ -27,7 +27,7 @@
*/
oneway interface ITaskOrganizer {
void taskAppeared(in ActivityManager.RunningTaskInfo taskInfo);
- void taskVanished(in IWindowContainer container);
+ void taskVanished(in ActivityManager.RunningTaskInfo taskInfo);
/**
* Called upon completion of
diff --git a/core/java/android/view/IWindow.aidl b/core/java/android/view/IWindow.aidl
index 3927ebf..9f2d36d 100644
--- a/core/java/android/view/IWindow.aidl
+++ b/core/java/android/view/IWindow.aidl
@@ -102,9 +102,9 @@
void closeSystemDialogs(String reason);
/**
- * Called for wallpaper windows when their offsets change.
+ * Called for wallpaper windows when their offsets or zoom level change.
*/
- void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, boolean sync);
+ void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, float zoom, boolean sync);
void dispatchWallpaperCommand(String action, int x, int y,
int z, in Bundle extras, boolean sync);
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 73601d9..84ac90b 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -724,11 +724,12 @@
/**
* Called to get the expected window insets.
- * TODO(window-context): Remove when new insets flag is available.
+ *
+ * @return {@code true} if system bars are always comsumed.
*/
- void getWindowInsets(in WindowManager.LayoutParams attrs, int displayId,
+ boolean getWindowInsets(in WindowManager.LayoutParams attrs, int displayId,
out Rect outContentInsets, out Rect outStableInsets,
- out DisplayCutout.ParcelableWrapper displayCutout);
+ out DisplayCutout.ParcelableWrapper outDisplayCutout, out InsetsState outInsetsState);
/**
* Called to show global actions.
diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl
index 91000a9..dfe89a3 100644
--- a/core/java/android/view/IWindowSession.aidl
+++ b/core/java/android/view/IWindowSession.aidl
@@ -221,6 +221,19 @@
*/
void setWallpaperPosition(IBinder windowToken, float x, float y, float xstep, float ystep);
+ /**
+ * For wallpaper windows, sets the scale of the wallpaper based on
+ * SystemUI behavior.
+ */
+ void setWallpaperZoomOut(IBinder windowToken, float scale);
+
+ /**
+ * For wallpaper windows, sets whether the wallpaper should actually be
+ * scaled when setWallpaperZoomOut is called. If set to false, the WallpaperService will
+ * receive the zoom out value but the surface won't be scaled.
+ */
+ void setShouldZoomOutWallpaper(IBinder windowToken, boolean shouldZoom);
+
@UnsupportedAppUsage
void wallpaperOffsetsComplete(IBinder window);
diff --git a/core/java/android/view/ImeFocusController.java b/core/java/android/view/ImeFocusController.java
index 74fac2b..6784cf7 100644
--- a/core/java/android/view/ImeFocusController.java
+++ b/core/java/android/view/ImeFocusController.java
@@ -165,10 +165,16 @@
if (!getImmDelegate().isCurrentRootView(view.getViewRootImpl())) {
return;
}
- if (mServedView == view || !view.hasImeFocus() || !view.hasWindowFocus()) {
+ if (!view.hasImeFocus() || !view.hasWindowFocus()) {
return;
}
- mNextServedView = hasFocus ? view : null;
+ if (DEBUG) Log.d(TAG, "onViewFocusChanged, view=" + view + ", mServedView=" + mServedView);
+
+ if (hasFocus) {
+ mNextServedView = view;
+ } else if (view == mServedView) {
+ mNextServedView = null;
+ }
mViewRootImpl.dispatchCheckFocus();
}
diff --git a/core/java/android/view/InsetsAnimationControlCallbacks.java b/core/java/android/view/InsetsAnimationControlCallbacks.java
index 5d5edec..4227f78 100644
--- a/core/java/android/view/InsetsAnimationControlCallbacks.java
+++ b/core/java/android/view/InsetsAnimationControlCallbacks.java
@@ -16,7 +16,6 @@
package android.view;
-import android.view.InsetsController.LayoutInsetsDuringAnimation;
import android.view.WindowInsetsAnimation.Bounds;
/**
@@ -37,7 +36,7 @@
void startAnimation(InsetsAnimationControlImpl controller,
WindowInsetsAnimationControlListener listener, int types,
WindowInsetsAnimation animation,
- Bounds bounds, @LayoutInsetsDuringAnimation int layoutDuringAnimation);
+ Bounds bounds);
/**
* Schedule the apply by posting the animation callback.
@@ -46,10 +45,10 @@
/**
* Finish the final steps after the animation.
- * @param controller The controller used to control the animation.
+ * @param runner The runner used to run the animation.
* @param shown {@code true} if the insets are shown.
*/
- void notifyFinished(InsetsAnimationControlImpl controller, boolean shown);
+ void notifyFinished(InsetsAnimationControlRunner runner, boolean shown);
/**
* Apply the new params to the surface.
@@ -57,4 +56,10 @@
* apply.
*/
void applySurfaceParams(SyncRtSurfaceTransactionApplier.SurfaceParams... params);
+
+ /**
+ * Post a message to release the Surface, guaranteed to happen after all
+ * previous calls to applySurfaceParams.
+ */
+ void releaseSurfaceControlFromRt(SurfaceControl sc);
}
diff --git a/core/java/android/view/InsetsAnimationControlImpl.java b/core/java/android/view/InsetsAnimationControlImpl.java
index ae509f3..baee412 100644
--- a/core/java/android/view/InsetsAnimationControlImpl.java
+++ b/core/java/android/view/InsetsAnimationControlImpl.java
@@ -31,9 +31,7 @@
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.util.SparseSetArray;
-import android.view.InsetsController.LayoutInsetsDuringAnimation;
import android.view.InsetsState.InternalInsetsSide;
-import android.view.InsetsState.InternalInsetsType;
import android.view.SyncRtSurfaceTransactionApplier.SurfaceParams;
import android.view.WindowInsets.Type.InsetsType;
import android.view.WindowInsetsAnimation.Bounds;
@@ -49,7 +47,8 @@
* @hide
*/
@VisibleForTesting
-public class InsetsAnimationControlImpl implements WindowInsetsAnimationController {
+public class InsetsAnimationControlImpl implements WindowInsetsAnimationController,
+ InsetsAnimationControlRunner {
private final Rect mTmpFrame = new Rect();
@@ -84,8 +83,7 @@
InsetsState state, WindowInsetsAnimationControlListener listener,
@InsetsType int types,
InsetsAnimationControlCallbacks controller, long durationMs, Interpolator interpolator,
- boolean fade, @LayoutInsetsDuringAnimation int layoutInsetsDuringAnimation,
- @AnimationType int animationType) {
+ boolean fade, @AnimationType int animationType) {
mControls = controls;
mListener = listener;
mTypes = types;
@@ -105,7 +103,7 @@
mAnimation.setAlpha(getCurrentAlpha());
mAnimationType = animationType;
mController.startAnimation(this, listener, types, mAnimation,
- new Bounds(mHiddenInsets, mShownInsets), layoutInsetsDuringAnimation);
+ new Bounds(mHiddenInsets, mShownInsets));
}
@Override
@@ -133,11 +131,8 @@
return mTypes;
}
- boolean controlsInternalType(@InternalInsetsType int type) {
- return InsetsState.toInternalType(mTypes).contains(type);
- }
-
- @AnimationType int getAnimationType() {
+ @Override
+ public @AnimationType int getAnimationType() {
return mAnimationType;
}
@@ -185,10 +180,19 @@
mAnimation.setAlpha(mPendingAlpha);
if (mFinished) {
mController.notifyFinished(this, mShownOnFinish);
+ releaseLeashes();
}
return mFinished;
}
+ private void releaseLeashes() {
+ for (int i = mControls.size() - 1; i >= 0; i--) {
+ final InsetsSourceControl c = mControls.valueAt(i);
+ if (c == null) continue;
+ c.release(mController::releaseSurfaceControlFromRt);
+ }
+ }
+
@Override
public void finish(boolean shown) {
if (mCancelled || mFinished) {
@@ -196,6 +200,7 @@
}
setInsetsAndAlpha(shown ? mShownInsets : mHiddenInsets, 1f /* alpha */, 1f /* fraction */);
mFinished = true;
+
mShownOnFinish = shown;
}
@@ -205,19 +210,23 @@
return mAnimation.getFraction();
}
- public void onCancelled() {
+ @Override
+ public void cancel() {
if (mFinished) {
return;
}
mCancelled = true;
mListener.onCancelled();
+
+ releaseLeashes();
}
public boolean isCancelled() {
return mCancelled;
}
- WindowInsetsAnimation getAnimation() {
+ @Override
+ public WindowInsetsAnimation getAnimation() {
return mAnimation;
}
@@ -225,6 +234,10 @@
return mListener;
}
+ SparseArray<InsetsSourceControl> getControls() {
+ return mControls;
+ }
+
private Insets calculateInsets(InsetsState state, Rect frame,
SparseArray<InsetsSourceControl> controls, boolean shown,
@Nullable @InternalInsetsSide SparseIntArray typeSideMap) {
diff --git a/core/java/android/view/InsetsAnimationControlRunner.java b/core/java/android/view/InsetsAnimationControlRunner.java
new file mode 100644
index 0000000..0711c3e
--- /dev/null
+++ b/core/java/android/view/InsetsAnimationControlRunner.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2020 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.view;
+
+import android.view.InsetsController.AnimationType;
+import android.view.InsetsState.InternalInsetsType;
+import android.view.WindowInsets.Type.InsetsType;
+
+/**
+ * Interface representing a runner for an insets animation.
+ *
+ * @hide
+ */
+public interface InsetsAnimationControlRunner {
+
+ /**
+ * @return The {@link InsetsType} the animation of this runner is controlling.
+ */
+ @InsetsType int getTypes();
+
+ /**
+ * Cancels the animation.
+ */
+ void cancel();
+
+ /**
+ * @return The animation this runner is running.
+ */
+ WindowInsetsAnimation getAnimation();
+
+ /**
+ * @return Whether {@link #getTypes()} maps to a specific {@link InternalInsetsType}.
+ */
+ default boolean controlsInternalType(@InternalInsetsType int type) {
+ return InsetsState.toInternalType(getTypes()).contains(type);
+ }
+
+ /**
+ * @return The animation type this runner is running.
+ */
+ @AnimationType int getAnimationType();
+}
diff --git a/core/java/android/view/InsetsAnimationThread.java b/core/java/android/view/InsetsAnimationThread.java
new file mode 100644
index 0000000..cdf9733
--- /dev/null
+++ b/core/java/android/view/InsetsAnimationThread.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2020 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.view;
+
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Trace;
+
+/**
+ * Thread to be used for inset animations to be running off the main thread.
+ * @hide
+ */
+public class InsetsAnimationThread extends HandlerThread {
+
+ private static InsetsAnimationThread sInstance;
+ private static Handler sHandler;
+
+ private InsetsAnimationThread() {
+ // TODO: Should this use higher priority?
+ super("InsetsAnimations");
+ }
+
+ private static void ensureThreadLocked() {
+ if (sInstance == null) {
+ sInstance = new InsetsAnimationThread();
+ sInstance.start();
+ sInstance.getLooper().setTraceTag(Trace.TRACE_TAG_VIEW);
+ sHandler = new Handler(sInstance.getLooper());
+ }
+ }
+
+ public static void release() {
+ synchronized (InsetsAnimationThread.class) {
+ if (sInstance == null) {
+ return;
+ }
+ sInstance.getLooper().quitSafely();
+ sInstance = null;
+ sHandler = null;
+ }
+ }
+
+ public static InsetsAnimationThread get() {
+ synchronized (InsetsAnimationThread.class) {
+ ensureThreadLocked();
+ return sInstance;
+ }
+ }
+
+ public static Handler getHandler() {
+ synchronized (InsetsAnimationThread.class) {
+ ensureThreadLocked();
+ return sHandler;
+ }
+ }
+}
diff --git a/core/java/android/view/InsetsAnimationThreadControlRunner.java b/core/java/android/view/InsetsAnimationThreadControlRunner.java
new file mode 100644
index 0000000..13b4cd8
--- /dev/null
+++ b/core/java/android/view/InsetsAnimationThreadControlRunner.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2020 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.view;
+
+import static android.view.SyncRtSurfaceTransactionApplier.applyParams;
+
+import android.annotation.UiThread;
+import android.graphics.Rect;
+import android.os.Handler;
+import android.util.SparseArray;
+import android.view.InsetsController.AnimationType;
+import android.view.SyncRtSurfaceTransactionApplier.SurfaceParams;
+import android.view.WindowInsets.Type.InsetsType;
+import android.view.WindowInsetsAnimation.Bounds;
+import android.view.animation.Interpolator;
+
+/**
+ * Insets animation runner that uses {@link InsetsAnimationThread} to run the animation off from the
+ * main thread.
+ *
+ * @hide
+ */
+public class InsetsAnimationThreadControlRunner implements InsetsAnimationControlRunner {
+
+ private final InsetsAnimationControlImpl mControl;
+ private final InsetsAnimationControlCallbacks mOuterCallbacks;
+ private final Handler mMainThreadHandler;
+ private final InsetsState mState = new InsetsState();
+ private final InsetsAnimationControlCallbacks mCallbacks =
+ new InsetsAnimationControlCallbacks() {
+
+ private final float[] mTmpFloat9 = new float[9];
+
+ @Override
+ @UiThread
+ public void startAnimation(InsetsAnimationControlImpl controller,
+ WindowInsetsAnimationControlListener listener, int types,
+ WindowInsetsAnimation animation, Bounds bounds) {
+ // Animation will be started in constructor already.
+ }
+
+ @Override
+ public void scheduleApplyChangeInsets() {
+ mControl.applyChangeInsets(mState);
+ }
+
+ @Override
+ public void notifyFinished(InsetsAnimationControlRunner runner, boolean shown) {
+ releaseControls(mControl.getControls());
+ mMainThreadHandler.post(() ->
+ mOuterCallbacks.notifyFinished(InsetsAnimationThreadControlRunner.this, shown));
+ }
+
+ @Override
+ public void applySurfaceParams(SurfaceParams... params) {
+ SurfaceControl.Transaction t = new SurfaceControl.Transaction();
+ for (int i = params.length - 1; i >= 0; i--) {
+ SyncRtSurfaceTransactionApplier.SurfaceParams surfaceParams = params[i];
+ applyParams(t, surfaceParams, mTmpFloat9);
+ }
+ t.apply();
+ t.close();
+ }
+
+ @Override
+ public void releaseSurfaceControlFromRt(SurfaceControl sc) {
+ // Since we don't push the SurfaceParams to the RT we can release directly
+ sc.release();
+ }
+ };
+
+ @UiThread
+ public InsetsAnimationThreadControlRunner(SparseArray<InsetsSourceControl> controls, Rect frame,
+ InsetsState state, WindowInsetsAnimationControlListener listener,
+ @InsetsType int types,
+ InsetsAnimationControlCallbacks controller, long durationMs, Interpolator interpolator,
+ boolean fade, @AnimationType int animationType, Handler mainThreadHandler) {
+ mMainThreadHandler = mainThreadHandler;
+ mOuterCallbacks = controller;
+ mControl = new InsetsAnimationControlImpl(copyControls(controls), frame, state, listener,
+ types, mCallbacks, durationMs, interpolator, fade, animationType);
+ InsetsAnimationThread.getHandler().post(() -> listener.onReady(mControl, types));
+ }
+
+ private void releaseControls(SparseArray<InsetsSourceControl> controls) {
+ for (int i = controls.size() - 1; i >= 0; i--) {
+ controls.valueAt(i).release(SurfaceControl::release);
+ }
+ }
+
+ private SparseArray<InsetsSourceControl> copyControls(
+ SparseArray<InsetsSourceControl> controls) {
+ SparseArray<InsetsSourceControl> copy = new SparseArray<>(controls.size());
+ for (int i = 0; i < controls.size(); i++) {
+ copy.append(controls.keyAt(i), new InsetsSourceControl(controls.valueAt(i)));
+ }
+ return copy;
+ }
+
+ @Override
+ @UiThread
+ public int getTypes() {
+ return mControl.getTypes();
+ }
+
+ @Override
+ @UiThread
+ public void cancel() {
+ InsetsAnimationThread.getHandler().post(mControl::cancel);
+ }
+
+ @Override
+ @UiThread
+ public WindowInsetsAnimation getAnimation() {
+ return mControl.getAnimation();
+ }
+
+ @Override
+ public int getAnimationType() {
+ return mControl.getAnimationType();
+ }
+}
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index 573d8fc..123b9db 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -23,6 +23,7 @@
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_APPEARANCE_CONTROLLED;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_BEHAVIOR_CONTROLLED;
+import android.animation.AnimationHandler;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
@@ -52,6 +53,7 @@
import android.view.animation.PathInterpolator;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.graphics.SfVsyncFrameCallbackProvider;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
@@ -59,6 +61,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.function.BiFunction;
/**
@@ -165,10 +168,22 @@
private WindowInsetsAnimationController mController;
private ObjectAnimator mAnimator;
- protected boolean mShow;
+ private final boolean mShow;
+ private final boolean mUseSfVsync;
- public InternalAnimationControlListener(boolean show) {
+ private ThreadLocal<AnimationHandler> mSfAnimationHandlerThreadLocal =
+ new ThreadLocal<AnimationHandler>() {
+ @Override
+ protected AnimationHandler initialValue() {
+ AnimationHandler handler = new AnimationHandler();
+ handler.setProvider(new SfVsyncFrameCallbackProvider());
+ return handler;
+ }
+ };
+
+ public InternalAnimationControlListener(boolean show, boolean useSfVsync) {
mShow = show;
+ mUseSfVsync = useSfVsync;
}
@Override
@@ -191,6 +206,9 @@
onAnimationFinish();
}
});
+ if (mUseSfVsync) {
+ mAnimator.setAnimationHandler(mSfAnimationHandlerThreadLocal.get());
+ }
mAnimator.start();
}
@@ -226,12 +244,12 @@
*/
private static class RunningAnimation {
- RunningAnimation(InsetsAnimationControlImpl control, int type) {
- this.control = control;
+ RunningAnimation(InsetsAnimationControlRunner runner, int type) {
+ this.runner = runner;
this.type = type;
}
- final InsetsAnimationControlImpl control;
+ final InsetsAnimationControlRunner runner;
final @AnimationType int type;
/**
@@ -250,7 +268,7 @@
PendingControlRequest(@InsetsType int types, WindowInsetsAnimationControlListener listener,
long durationMs, Interpolator interpolator, @AnimationType int animationType,
@LayoutInsetsDuringAnimation int layoutInsetsDuringAnimation,
- CancellationSignal cancellationSignal) {
+ CancellationSignal cancellationSignal, boolean useInsetsAnimationThread) {
this.types = types;
this.listener = listener;
this.durationMs = durationMs;
@@ -258,6 +276,7 @@
this.animationType = animationType;
this.layoutInsetsDuringAnimation = layoutInsetsDuringAnimation;
this.cancellationSignal = cancellationSignal;
+ this.useInsetsAnimationThread = useInsetsAnimationThread;
}
final @InsetsType int types;
@@ -267,6 +286,7 @@
final @AnimationType int animationType;
final @LayoutInsetsDuringAnimation int layoutInsetsDuringAnimation;
final CancellationSignal cancellationSignal;
+ final boolean useInsetsAnimationThread;
}
private final String TAG = "InsetsControllerImpl";
@@ -306,6 +326,11 @@
private SyncRtSurfaceTransactionApplier mApplier;
private Runnable mPendingControlTimeout = this::abortPendingImeControlRequest;
+ private final ArrayList<OnControllableInsetsChangedListener> mControllableInsetsChangedListeners
+ = new ArrayList<>();
+
+ /** Set of inset types for which an animation was started since last resetting this field */
+ private @InsetsType int mLastStartedAnimTypes;
public InsetsController(ViewRootImpl viewRoot) {
this(viewRoot, (controller, type) -> {
@@ -340,15 +365,20 @@
InsetsState state = new InsetsState(mState, true /* copySources */);
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
RunningAnimation runningAnimation = mRunningAnimations.get(i);
- InsetsAnimationControlImpl control = runningAnimation.control;
+ InsetsAnimationControlRunner runner = runningAnimation.runner;
+ if (runner instanceof InsetsAnimationControlImpl) {
+ InsetsAnimationControlImpl control = (InsetsAnimationControlImpl) runner;
- // Keep track of running animation to be dispatched. Aggregate it here such that if
- // it gets finished within applyChangeInsets we still dispatch it to onProgress.
- if (runningAnimation.startDispatched) {
- mTmpRunningAnims.add(control.getAnimation());
- }
- if (control.applyChangeInsets(state)) {
- mTmpFinishedControls.add(control);
+ // Keep track of running animation to be dispatched. Aggregate it here such that
+ // if it gets finished within applyChangeInsets we still dispatch it to
+ // onProgress.
+ if (runningAnimation.startDispatched) {
+ mTmpRunningAnims.add(control.getAnimation());
+ }
+
+ if (control.applyChangeInsets(state)) {
+ mTmpFinishedControls.add(control);
+ }
}
}
@@ -459,6 +489,13 @@
}
mTmpControlArray.clear();
+
+ // Do not override any animations that the app started in the OnControllableInsetsChanged
+ // listeners.
+ int animatingTypes = invokeControllableInsetsChangedListeners();
+ showTypes[0] &= ~animatingTypes;
+ hideTypes[0] &= ~animatingTypes;
+
if (showTypes[0] != 0) {
applyAnimation(showTypes[0], true /* show */, false /* fromIme */);
}
@@ -480,13 +517,13 @@
PendingControlRequest pendingRequest = mPendingImeControlRequest;
mPendingImeControlRequest = null;
mHandler.removeCallbacks(mPendingControlTimeout);
- CancellationSignal cancellationSignal = controlAnimationUnchecked(
- pendingRequest.types,
+ controlAnimationUnchecked(
+ pendingRequest.types, pendingRequest.cancellationSignal,
pendingRequest.listener, mFrame,
true /* fromIme */, pendingRequest.durationMs, pendingRequest.interpolator,
false /* fade */, pendingRequest.animationType,
- pendingRequest.layoutInsetsDuringAnimation);
- pendingRequest.cancellationSignal.setOnCancelListener(cancellationSignal::cancel);
+ pendingRequest.layoutInsetsDuringAnimation,
+ pendingRequest.useInsetsAnimationThread);
return;
}
@@ -532,41 +569,50 @@
}
@Override
- public CancellationSignal controlWindowInsetsAnimation(@InsetsType int types, long durationMs,
+ public void controlWindowInsetsAnimation(@InsetsType int types, long durationMillis,
@Nullable Interpolator interpolator,
+ @Nullable CancellationSignal cancellationSignal,
@NonNull WindowInsetsAnimationControlListener listener) {
- return controlWindowInsetsAnimation(types, listener, false /* fromIme */, durationMs,
- interpolator, ANIMATION_TYPE_USER);
+ controlWindowInsetsAnimation(types, cancellationSignal, listener,
+ false /* fromIme */, durationMillis, interpolator, ANIMATION_TYPE_USER);
}
- private CancellationSignal controlWindowInsetsAnimation(@InsetsType int types,
- WindowInsetsAnimationControlListener listener, boolean fromIme, long durationMs,
- @Nullable Interpolator interpolator, @AnimationType int animationType) {
+ private void controlWindowInsetsAnimation(@InsetsType int types,
+ @Nullable CancellationSignal cancellationSignal,
+ WindowInsetsAnimationControlListener listener,
+ boolean fromIme, long durationMs, @Nullable Interpolator interpolator,
+ @AnimationType int animationType) {
+ if (!checkDisplayFramesForControlling()) {
+ listener.onCancelled();
+ return;
+ }
+ controlAnimationUnchecked(types, cancellationSignal, listener, mFrame, fromIme, durationMs,
+ interpolator, false /* fade */, animationType,
+ getLayoutInsetsDuringAnimationMode(types),
+ false /* useInsetsAnimationThread */);
+ }
+
+ private boolean checkDisplayFramesForControlling() {
+
// If the frame of our window doesn't span the entire display, the control API makes very
// little sense, as we don't deal with negative insets. So just cancel immediately.
- if (!mState.getDisplayFrame().equals(mFrame)) {
- listener.onCancelled();
- CancellationSignal cancellationSignal = new CancellationSignal();
- cancellationSignal.cancel();
- return cancellationSignal;
- }
- return controlAnimationUnchecked(types, listener, mFrame, fromIme, durationMs, interpolator,
- false /* fade */, animationType, getLayoutInsetsDuringAnimationMode(types));
+ return mState.getDisplayFrame().equals(mFrame);
}
- private CancellationSignal controlAnimationUnchecked(@InsetsType int types,
+ private void controlAnimationUnchecked(@InsetsType int types,
+ @Nullable CancellationSignal cancellationSignal,
WindowInsetsAnimationControlListener listener, Rect frame, boolean fromIme,
long durationMs, Interpolator interpolator, boolean fade,
@AnimationType int animationType,
- @LayoutInsetsDuringAnimation int layoutInsetsDuringAnimation) {
- CancellationSignal cancellationSignal = new CancellationSignal();
+ @LayoutInsetsDuringAnimation int layoutInsetsDuringAnimation,
+ boolean useInsetsAnimationThread) {
if (types == 0) {
// nothing to animate.
listener.onCancelled();
- cancellationSignal.cancel();
- return cancellationSignal;
+ return;
}
cancelExistingControllers(types);
+ mLastStartedAnimTypes |= types;
final ArraySet<Integer> internalTypes = InsetsState.toInternalType(types);
final SparseArray<InsetsSourceControl> controls = new SparseArray<>();
@@ -580,29 +626,42 @@
abortPendingImeControlRequest();
final PendingControlRequest request = new PendingControlRequest(types,
listener, durationMs,
- interpolator, animationType, layoutInsetsDuringAnimation, cancellationSignal);
+ interpolator, animationType, layoutInsetsDuringAnimation, cancellationSignal,
+ useInsetsAnimationThread);
mPendingImeControlRequest = request;
mHandler.postDelayed(mPendingControlTimeout, PENDING_CONTROL_TIMEOUT_MS);
- cancellationSignal.setOnCancelListener(() -> {
- if (mPendingImeControlRequest == request) {
- abortPendingImeControlRequest();
- }
- });
- return cancellationSignal;
+ if (cancellationSignal != null) {
+ cancellationSignal.setOnCancelListener(() -> {
+ if (mPendingImeControlRequest == request) {
+ abortPendingImeControlRequest();
+ }
+ });
+ }
+ return;
}
if (typesReady == 0) {
listener.onCancelled();
- cancellationSignal.cancel();
- return cancellationSignal;
+ return;
}
- final InsetsAnimationControlImpl controller = new InsetsAnimationControlImpl(controls,
- frame, mState, listener, typesReady, this, durationMs, interpolator, fade,
- layoutInsetsDuringAnimation, animationType);
- mRunningAnimations.add(new RunningAnimation(controller, animationType));
- cancellationSignal.setOnCancelListener(controller::onCancelled);
- return cancellationSignal;
+
+ final InsetsAnimationControlRunner runner = useInsetsAnimationThread
+ ? new InsetsAnimationThreadControlRunner(controls,
+ frame, mState, listener, typesReady, this, durationMs, interpolator, fade,
+ animationType, mViewRoot.mHandler)
+ : new InsetsAnimationControlImpl(controls,
+ frame, mState, listener, typesReady, this, durationMs, interpolator, fade,
+ animationType);
+ mRunningAnimations.add(new RunningAnimation(runner, animationType));
+ if (cancellationSignal != null) {
+ cancellationSignal.setOnCancelListener(runner::cancel);
+ }
+ if (layoutInsetsDuringAnimation == LAYOUT_INSETS_DURING_ANIMATION_SHOWN) {
+ showDirectly(types);
+ } else {
+ hideDirectly(types, false /* animationFinished */, animationType);
+ }
}
/**
@@ -646,7 +705,7 @@
}
final InsetsSourceControl control = consumer.getControl();
if (control != null) {
- controls.put(consumer.getType(), control);
+ controls.put(consumer.getType(), new InsetsSourceControl(control));
typesReady |= toPublicType(consumer.getType());
} else if (animationType == ANIMATION_TYPE_SHOW) {
@@ -685,7 +744,7 @@
private void cancelExistingControllers(@InsetsType int types) {
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- InsetsAnimationControlImpl control = mRunningAnimations.get(i).control;
+ InsetsAnimationControlRunner control = mRunningAnimations.get(i).runner;
if ((control.getTypes() & types) != 0) {
cancelAnimation(control, true /* invokeCallback */);
}
@@ -705,13 +764,13 @@
@VisibleForTesting
@Override
- public void notifyFinished(InsetsAnimationControlImpl controller, boolean shown) {
- cancelAnimation(controller, false /* invokeCallback */);
+ public void notifyFinished(InsetsAnimationControlRunner runner, boolean shown) {
+ cancelAnimation(runner, false /* invokeCallback */);
if (shown) {
- showDirectly(controller.getTypes());
+ showDirectly(runner.getTypes());
} else {
- hideDirectly(controller.getTypes(), true /* animationFinished */,
- controller.getAnimationType());
+ hideDirectly(runner.getTypes(), true /* animationFinished */,
+ runner.getAnimationType());
}
}
@@ -724,18 +783,19 @@
mApplier = new SyncRtSurfaceTransactionApplier(mViewRoot.mView);
}
if (mViewRoot.mView.isHardwareAccelerated()) {
- mApplier.scheduleApply(params);
+ mApplier.scheduleApply(false /* earlyWakeup */, params);
} else {
// Window doesn't support hardware acceleration, no synchronization for now.
// TODO(b/149342281): use mViewRoot.mSurface.getNextFrameNumber() to sync on every
// frame instead.
- mApplier.applyParams(new Transaction(), -1 /* frame */, params);
+ mApplier.applyParams(new Transaction(), -1 /* frame */, false /* earlyWakeup */,
+ params);
}
}
void notifyControlRevoked(InsetsSourceConsumer consumer) {
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- InsetsAnimationControlImpl control = mRunningAnimations.get(i).control;
+ InsetsAnimationControlRunner control = mRunningAnimations.get(i).runner;
if ((control.getTypes() & toPublicType(consumer.getType())) != 0) {
cancelAnimation(control, true /* invokeCallback */);
}
@@ -745,12 +805,12 @@
}
}
- private void cancelAnimation(InsetsAnimationControlImpl control, boolean invokeCallback) {
+ private void cancelAnimation(InsetsAnimationControlRunner control, boolean invokeCallback) {
if (invokeCallback) {
- control.onCancelled();
+ control.cancel();
}
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- if (mRunningAnimations.get(i).control == control) {
+ if (mRunningAnimations.get(i).runner == control) {
mRunningAnimations.remove(i);
break;
}
@@ -823,7 +883,7 @@
@VisibleForTesting
public @AnimationType int getAnimationType(@InternalInsetsType int type) {
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- InsetsAnimationControlImpl control = mRunningAnimations.get(i).control;
+ InsetsAnimationControlRunner control = mRunningAnimations.get(i).runner;
if (control.controlsInternalType(type)) {
return mRunningAnimations.get(i).type;
}
@@ -857,15 +917,25 @@
return;
}
+ boolean useInsetsAnimationThread = canUseInsetsAnimationThread();
final InternalAnimationControlListener listener =
- new InternalAnimationControlListener(show);
+ new InternalAnimationControlListener(show, useInsetsAnimationThread);
// Show/hide animations always need to be relative to the display frame, in order that shown
// and hidden state insets are correct.
controlAnimationUnchecked(
- types, listener, mState.getDisplayFrame(), fromIme, listener.getDurationMs(),
+ types, null /* cancellationSignal */, listener, mState.getDisplayFrame(), fromIme,
+ listener.getDurationMs(),
INTERPOLATOR, true /* fade */, show ? ANIMATION_TYPE_SHOW : ANIMATION_TYPE_HIDE,
show ? LAYOUT_INSETS_DURING_ANIMATION_SHOWN
- : LAYOUT_INSETS_DURING_ANIMATION_HIDDEN);
+ : LAYOUT_INSETS_DURING_ANIMATION_HIDDEN,
+ useInsetsAnimationThread);
+ }
+
+ private boolean canUseInsetsAnimationThread() {
+ if (mViewRoot.mView == null) {
+ return true;
+ }
+ return !mViewRoot.mView.hasWindowInsetsAnimationCallback();
}
private void hideDirectly(
@@ -900,13 +970,7 @@
@Override
public void startAnimation(InsetsAnimationControlImpl controller,
WindowInsetsAnimationControlListener listener, int types,
- WindowInsetsAnimation animation, Bounds bounds, int layoutDuringAnimation) {
- if (layoutDuringAnimation == LAYOUT_INSETS_DURING_ANIMATION_SHOWN) {
- showDirectly(types);
- } else {
- hideDirectly(types, false /* animationFinished */, controller.getAnimationType());
- }
-
+ WindowInsetsAnimation animation, Bounds bounds) {
if (mViewRoot.mView == null) {
return;
}
@@ -920,7 +984,7 @@
}
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
RunningAnimation runningAnimation = mRunningAnimations.get(i);
- if (runningAnimation.control == controller) {
+ if (runningAnimation.runner == controller) {
runningAnimation.startDispatched = true;
}
}
@@ -992,4 +1056,65 @@
}
return mViewRoot.mWindowAttributes.insetsFlags.behavior;
}
+
+ private @InsetsType int calculateControllableTypes() {
+ if (!checkDisplayFramesForControlling()) {
+ return 0;
+ }
+ @InsetsType int result = 0;
+ for (int i = mSourceConsumers.size() - 1; i >= 0; i--) {
+ InsetsSourceConsumer consumer = mSourceConsumers.valueAt(i);
+ if (consumer.getControl() != null) {
+ result |= toPublicType(consumer.mType);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * @return The types that are now animating due to a listener invoking control/show/hide
+ */
+ private @InsetsType int invokeControllableInsetsChangedListeners() {
+ mLastStartedAnimTypes = 0;
+ @InsetsType int types = calculateControllableTypes();
+ int size = mControllableInsetsChangedListeners.size();
+ for (int i = 0; i < size; i++) {
+ mControllableInsetsChangedListeners.get(i).onControllableInsetsChanged(this, types);
+ }
+ return mLastStartedAnimTypes;
+ }
+
+ @Override
+ public void addOnControllableInsetsChangedListener(
+ OnControllableInsetsChangedListener listener) {
+ Objects.requireNonNull(listener);
+ mControllableInsetsChangedListeners.add(listener);
+ listener.onControllableInsetsChanged(this, calculateControllableTypes());
+ }
+
+ @Override
+ public void removeOnControllableInsetsChangedListener(
+ OnControllableInsetsChangedListener listener) {
+ Objects.requireNonNull(listener);
+ mControllableInsetsChangedListeners.remove(listener);
+ }
+
+ /**
+ * At the time we receive new leashes (e.g. InsetsSourceConsumer is processing
+ * setControl) we need to release the old leash. But we may have already scheduled
+ * a SyncRtSurfaceTransaction applier to use it from the RenderThread. To avoid
+ * synchronization issues we also release from the RenderThread so this release
+ * happens after any existing items on the work queue.
+ */
+ public void releaseSurfaceControlFromRt(SurfaceControl sc) {
+ if (mViewRoot.mView != null && mViewRoot.mView.isHardwareAccelerated()) {
+ mViewRoot.registerRtFrameCallback(frame -> {
+ sc.release();
+ });
+ // Make sure a frame gets scheduled.
+ mViewRoot.mView.invalidate();
+ } else {
+ sc.release();
+ }
+ }
}
diff --git a/core/java/android/view/InsetsSourceConsumer.java b/core/java/android/view/InsetsSourceConsumer.java
index f07f1ce..3325734 100644
--- a/core/java/android/view/InsetsSourceConsumer.java
+++ b/core/java/android/view/InsetsSourceConsumer.java
@@ -117,7 +117,7 @@
}
}
if (lastControl != null) {
- lastControl.release();
+ lastControl.release(mController::releaseSurfaceControlFromRt);
}
}
diff --git a/core/java/android/view/InsetsSourceControl.java b/core/java/android/view/InsetsSourceControl.java
index 29ba56a..f3ec65f 100644
--- a/core/java/android/view/InsetsSourceControl.java
+++ b/core/java/android/view/InsetsSourceControl.java
@@ -22,6 +22,8 @@
import android.os.Parcelable;
import android.view.InsetsState.InternalInsetsType;
+import java.util.function.Consumer;
+
/**
* Represents a parcelable object to allow controlling a single {@link InsetsSource}.
* @hide
@@ -94,9 +96,9 @@
dest.writeParcelable(mSurfacePosition, 0 /* flags*/);
}
- public void release() {
+ public void release(Consumer<SurfaceControl> surfaceReleaseConsumer) {
if (mLeash != null) {
- mLeash.release();
+ surfaceReleaseConsumer.accept(mLeash);
}
}
diff --git a/core/java/android/view/InsetsState.java b/core/java/android/view/InsetsState.java
index e4aa410..c2ad74a 100644
--- a/core/java/android/view/InsetsState.java
+++ b/core/java/android/view/InsetsState.java
@@ -80,6 +80,12 @@
})
public @interface InternalInsetsType {}
+ /**
+ * Special value to be used to by methods returning an {@link InternalInsetsType} to indicate
+ * that the objects/parameters aren't associated with an {@link InternalInsetsType}
+ */
+ public static final int ITYPE_INVALID = -1;
+
static final int FIRST_TYPE = 0;
public static final int ITYPE_STATUS_BAR = FIRST_TYPE;
diff --git a/core/java/android/view/NotificationHeaderView.java b/core/java/android/view/NotificationHeaderView.java
index 8ec5df8..18e0132 100644
--- a/core/java/android/view/NotificationHeaderView.java
+++ b/core/java/android/view/NotificationHeaderView.java
@@ -35,6 +35,7 @@
import com.android.internal.R;
import com.android.internal.widget.CachingIconView;
+import com.android.internal.widget.NotificationExpandButton;
import java.util.ArrayList;
@@ -56,7 +57,7 @@
private OnClickListener mAppOpsListener;
private HeaderTouchListener mTouchListener = new HeaderTouchListener();
private LinearLayout mTransferChip;
- private ImageView mExpandButton;
+ private NotificationExpandButton mExpandButton;
private CachingIconView mIcon;
private View mProfileBadge;
private View mOverlayIcon;
@@ -65,7 +66,6 @@
private View mAppOps;
private View mAudiblyAlertedIcon;
private int mIconColor;
- private int mOriginalNotificationColor;
private boolean mExpanded;
private boolean mShowExpandButtonAtEnd;
private boolean mShowWorkBadgeAtEnd;
@@ -324,13 +324,8 @@
return mIconColor;
}
- @RemotableViewMethod
- public void setOriginalNotificationColor(int color) {
- mOriginalNotificationColor = color;
- }
-
public int getOriginalNotificationColor() {
- return mOriginalNotificationColor;
+ return mExpandButton.getOriginalNotificationColor();
}
@RemotableViewMethod
@@ -371,7 +366,7 @@
contentDescriptionId = R.string.expand_button_content_description_collapsed;
}
mExpandButton.setImageDrawable(getContext().getDrawable(drawableId));
- mExpandButton.setColorFilter(mOriginalNotificationColor);
+ mExpandButton.setColorFilter(getOriginalNotificationColor());
mExpandButton.setContentDescription(mContext.getText(contentDescriptionId));
}
diff --git a/core/java/android/view/PendingInsetsController.java b/core/java/android/view/PendingInsetsController.java
index c0ed935..e8d9bb5 100644
--- a/core/java/android/view/PendingInsetsController.java
+++ b/core/java/android/view/PendingInsetsController.java
@@ -16,6 +16,8 @@
package android.view;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.os.CancellationSignal;
import android.view.WindowInsets.Type.InsetsType;
import android.view.animation.Interpolator;
@@ -38,6 +40,8 @@
private @Behavior int mBehavior = KEEP_BEHAVIOR;
private final InsetsState mDummyState = new InsetsState();
private InsetsController mReplayedInsetsController;
+ private ArrayList<OnControllableInsetsChangedListener> mControllableInsetsChangedListeners
+ = new ArrayList<>();
@Override
public void show(int types) {
@@ -58,21 +62,6 @@
}
@Override
- public CancellationSignal controlWindowInsetsAnimation(int types, long durationMillis,
- Interpolator interpolator,
- WindowInsetsAnimationControlListener listener) {
- if (mReplayedInsetsController != null) {
- return mReplayedInsetsController.controlWindowInsetsAnimation(types, durationMillis,
- interpolator, listener);
- } else {
- listener.onCancelled();
- CancellationSignal cancellationSignal = new CancellationSignal();
- cancellationSignal.cancel();
- return cancellationSignal;
- }
- }
-
- @Override
public void setSystemBarsAppearance(int appearance, int mask) {
if (mReplayedInsetsController != null) {
mReplayedInsetsController.setSystemBarsAppearance(appearance, mask);
@@ -112,6 +101,27 @@
return mDummyState;
}
+ @Override
+ public void addOnControllableInsetsChangedListener(
+ OnControllableInsetsChangedListener listener) {
+ if (mReplayedInsetsController != null) {
+ mReplayedInsetsController.addOnControllableInsetsChangedListener(listener);
+ } else {
+ mControllableInsetsChangedListeners.add(listener);
+ listener.onControllableInsetsChanged(this, 0);
+ }
+ }
+
+ @Override
+ public void removeOnControllableInsetsChangedListener(
+ OnControllableInsetsChangedListener listener) {
+ if (mReplayedInsetsController != null) {
+ mReplayedInsetsController.removeOnControllableInsetsChangedListener(listener);
+ } else {
+ mControllableInsetsChangedListeners.remove(listener);
+ }
+ }
+
/**
* Replays the commands on {@code controller} and attaches it to this instance such that any
* calls will be forwarded to the real instance in the future.
@@ -128,9 +138,15 @@
for (int i = 0; i < size; i++) {
mRequests.get(i).replay(controller);
}
+ size = mControllableInsetsChangedListeners.size();
+ for (int i = 0; i < size; i++) {
+ controller.addOnControllableInsetsChangedListener(
+ mControllableInsetsChangedListeners.get(i));
+ }
// Reset all state so it doesn't get applied twice just in case
mRequests.clear();
+ mControllableInsetsChangedListeners.clear();
mBehavior = KEEP_BEHAVIOR;
mAppearance = 0;
mAppearanceMask = 0;
@@ -147,6 +163,19 @@
mReplayedInsetsController = null;
}
+ @Override
+ public void controlWindowInsetsAnimation(@InsetsType int types, long durationMillis,
+ @Nullable Interpolator interpolator,
+ CancellationSignal cancellationSignal,
+ @NonNull WindowInsetsAnimationControlListener listener) {
+ if (mReplayedInsetsController != null) {
+ mReplayedInsetsController.controlWindowInsetsAnimation(types, durationMillis,
+ interpolator, cancellationSignal, listener);
+ } else {
+ listener.onCancelled();
+ }
+ }
+
private interface PendingRequest {
void replay(InsetsController controller);
}
diff --git a/core/java/android/view/RemoteAnimationTarget.java b/core/java/android/view/RemoteAnimationTarget.java
index b04372a..3c22ed8 100644
--- a/core/java/android/view/RemoteAnimationTarget.java
+++ b/core/java/android/view/RemoteAnimationTarget.java
@@ -20,9 +20,11 @@
import static android.view.RemoteAnimationTargetProto.CONTENT_INSETS;
import static android.view.RemoteAnimationTargetProto.IS_TRANSLUCENT;
import static android.view.RemoteAnimationTargetProto.LEASH;
+import static android.view.RemoteAnimationTargetProto.LOCAL_BOUNDS;
import static android.view.RemoteAnimationTargetProto.MODE;
import static android.view.RemoteAnimationTargetProto.POSITION;
import static android.view.RemoteAnimationTargetProto.PREFIX_ORDER_INDEX;
+import static android.view.RemoteAnimationTargetProto.SCREEN_SPACE_BOUNDS;
import static android.view.RemoteAnimationTargetProto.SOURCE_CONTAINER_BOUNDS;
import static android.view.RemoteAnimationTargetProto.START_BOUNDS;
import static android.view.RemoteAnimationTargetProto.START_LEASH;
@@ -130,19 +132,38 @@
* The source position of the app, in screen spaces coordinates. If the position of the leash
* is modified from the controlling app, any animation transform needs to be offset by this
* amount.
+ * @deprecated Use {@link #localBounds} instead.
*/
+ @Deprecated
@UnsupportedAppUsage
public final Point position;
/**
+ * Bounds of the target relative to its parent.
+ * When the app target animating on its parent, we need to use the local coordinates relative to
+ * its parent with {@code localBounds.left} & {@code localBounds.top} rather than using
+ * {@code position} in screen coordinates.
+ */
+ public final Rect localBounds;
+
+ /**
* The bounds of the source container the app lives in, in screen space coordinates. If the crop
* of the leash is modified from the controlling app, it needs to take the source container
* bounds into account when calculating the crop.
+ * @deprecated Renamed to {@link #screenSpaceBounds}
*/
+ @Deprecated
@UnsupportedAppUsage
public final Rect sourceContainerBounds;
/**
+ * Bounds of the target relative to the screen. If the crop of the leash is modified from the
+ * controlling app, it needs to take the screen space bounds into account when calculating the
+ * crop.
+ */
+ public final Rect screenSpaceBounds;
+
+ /**
* The starting bounds of the source container in screen space coordinates. This is {@code null}
* if the animation target isn't MODE_CHANGING. Since this is the starting bounds, it's size
* should be equivalent to the size of the starting thumbnail. Note that sourceContainerBounds
@@ -165,7 +186,8 @@
public RemoteAnimationTarget(int taskId, int mode, SurfaceControl leash, boolean isTranslucent,
Rect clipRect, Rect contentInsets, int prefixOrderIndex, Point position,
- Rect sourceContainerBounds, WindowConfiguration windowConfig, boolean isNotInRecents,
+ Rect localBounds, Rect screenSpaceBounds,
+ WindowConfiguration windowConfig, boolean isNotInRecents,
SurfaceControl startLeash, Rect startBounds) {
this.mode = mode;
this.taskId = taskId;
@@ -175,7 +197,9 @@
this.contentInsets = new Rect(contentInsets);
this.prefixOrderIndex = prefixOrderIndex;
this.position = new Point(position);
- this.sourceContainerBounds = new Rect(sourceContainerBounds);
+ this.localBounds = new Rect(localBounds);
+ this.sourceContainerBounds = new Rect(screenSpaceBounds);
+ this.screenSpaceBounds = new Rect(screenSpaceBounds);
this.windowConfiguration = windowConfig;
this.isNotInRecents = isNotInRecents;
this.startLeash = startLeash;
@@ -191,7 +215,9 @@
contentInsets = in.readParcelable(null);
prefixOrderIndex = in.readInt();
position = in.readParcelable(null);
+ localBounds = in.readParcelable(null);
sourceContainerBounds = in.readParcelable(null);
+ screenSpaceBounds = in.readParcelable(null);
windowConfiguration = in.readParcelable(null);
isNotInRecents = in.readBoolean();
startLeash = in.readParcelable(null);
@@ -213,7 +239,9 @@
dest.writeParcelable(contentInsets, 0 /* flags */);
dest.writeInt(prefixOrderIndex);
dest.writeParcelable(position, 0 /* flags */);
+ dest.writeParcelable(localBounds, 0 /* flags */);
dest.writeParcelable(sourceContainerBounds, 0 /* flags */);
+ dest.writeParcelable(screenSpaceBounds, 0 /* flags */);
dest.writeParcelable(windowConfiguration, 0 /* flags */);
dest.writeBoolean(isNotInRecents);
dest.writeParcelable(startLeash, 0 /* flags */);
@@ -229,6 +257,8 @@
pw.print(" prefixOrderIndex="); pw.print(prefixOrderIndex);
pw.print(" position="); position.printShortString(pw);
pw.print(" sourceContainerBounds="); sourceContainerBounds.printShortString(pw);
+ pw.print(" screenSpaceBounds="); screenSpaceBounds.printShortString(pw);
+ pw.print(" localBounds="); localBounds.printShortString(pw);
pw.println();
pw.print(prefix); pw.print("windowConfiguration="); pw.println(windowConfiguration);
pw.print(prefix); pw.print("leash="); pw.println(leash);
@@ -245,6 +275,8 @@
proto.write(PREFIX_ORDER_INDEX, prefixOrderIndex);
position.dumpDebug(proto, POSITION);
sourceContainerBounds.dumpDebug(proto, SOURCE_CONTAINER_BOUNDS);
+ screenSpaceBounds.dumpDebug(proto, SCREEN_SPACE_BOUNDS);
+ localBounds.dumpDebug(proto, LOCAL_BOUNDS);
windowConfiguration.dumpDebug(proto, WINDOW_CONFIGURATION);
if (startLeash != null) {
startLeash.dumpDebug(proto, START_LEASH);
diff --git a/core/java/android/view/SurfaceControlViewHost.java b/core/java/android/view/SurfaceControlViewHost.java
index a3b3f1f..41a3847 100644
--- a/core/java/android/view/SurfaceControlViewHost.java
+++ b/core/java/android/view/SurfaceControlViewHost.java
@@ -26,6 +26,8 @@
import android.os.Parcelable;
import android.view.accessibility.IAccessibilityEmbeddedConnection;
+import java.util.Objects;
+
/**
* Utility class for adding a View hierarchy to a {@link SurfaceControl}. The View hierarchy
* will render in to a root SurfaceControl, and receive input based on the SurfaceControl's
@@ -159,7 +161,8 @@
* @hide
*/
@TestApi
- public void addView(@NonNull View view, WindowManager.LayoutParams attrs) {
+ public void setView(@NonNull View view, @NonNull WindowManager.LayoutParams attrs) {
+ Objects.requireNonNull(view);
mViewRoot.setView(view, attrs, null);
}
@@ -172,11 +175,18 @@
* @param width The width to layout the View within, in pixels.
* @param height The height to layout the View within, in pixels.
*/
- public void addView(@NonNull View view, int width, int height) {
+ public void setView(@NonNull View view, int width, int height) {
final WindowManager.LayoutParams lp =
new WindowManager.LayoutParams(width, height,
WindowManager.LayoutParams.TYPE_APPLICATION, 0, PixelFormat.TRANSPARENT);
- addView(view, lp);
+ setView(view, lp);
+ }
+
+ /**
+ * @return The view passed to setView, or null if none has been passed.
+ */
+ public @Nullable View getView() {
+ return mViewRoot.getView();
}
/**
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index fb7c04a..1f7c3504 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -605,7 +605,7 @@
mTmpRect.set(0, 0, mSurfaceWidth, mSurfaceHeight);
}
SyncRtSurfaceTransactionApplier applier = new SyncRtSurfaceTransactionApplier(this);
- applier.scheduleApply(
+ applier.scheduleApply(false /* earlyWakeup */,
new SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(mSurfaceControl)
.withWindowCrop(mTmpRect)
.build());
diff --git a/core/java/android/view/SyncRtSurfaceTransactionApplier.java b/core/java/android/view/SyncRtSurfaceTransactionApplier.java
index 206e4f9..9c97f3e 100644
--- a/core/java/android/view/SyncRtSurfaceTransactionApplier.java
+++ b/core/java/android/view/SyncRtSurfaceTransactionApplier.java
@@ -53,10 +53,11 @@
/**
* Schedules applying surface parameters on the next frame.
*
+ * @param earlyWakeup Whether to set {@link Transaction#setEarlyWakeup()} on transaction.
* @param params The surface parameters to apply. DO NOT MODIFY the list after passing into
* this method to avoid synchronization issues.
*/
- public void scheduleApply(final SurfaceParams... params) {
+ public void scheduleApply(boolean earlyWakeup, final SurfaceParams... params) {
if (mTargetViewRootImpl == null) {
return;
}
@@ -66,7 +67,7 @@
return;
}
Transaction t = new Transaction();
- applyParams(t, frame, params);
+ applyParams(t, frame, earlyWakeup, params);
});
// Make sure a frame gets scheduled.
@@ -77,10 +78,12 @@
* Applies surface parameters on the next frame.
* @param t transaction to apply all parameters in.
* @param frame frame to synchronize to. Set -1 when sync is not required.
+ * @param earlyWakeup Whether to set {@link Transaction#setEarlyWakeup()} on transaction.
* @param params The surface parameters to apply. DO NOT MODIFY the list after passing into
* this method to avoid synchronization issues.
*/
- void applyParams(Transaction t, long frame, final SurfaceParams... params) {
+ void applyParams(Transaction t, long frame, boolean earlyWakeup,
+ final SurfaceParams... params) {
for (int i = params.length - 1; i >= 0; i--) {
SurfaceParams surfaceParams = params[i];
SurfaceControl surface = surfaceParams.surface;
@@ -89,7 +92,9 @@
}
applyParams(t, surfaceParams, mTmpFloat9);
}
- t.setEarlyWakeup();
+ if (earlyWakeup) {
+ t.setEarlyWakeup();
+ }
t.apply();
}
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 6236e6e..708a094 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -3318,7 +3318,7 @@
* Flag indicating that the view is autofilled
*
* @see #isAutofilled()
- * @see #setAutofilled(boolean)
+ * @see #setAutofilled(boolean, boolean)
*/
private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
@@ -3428,6 +3428,7 @@
* 1 PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE
* 11 PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK
* 1 PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS
+ * 1 PFLAG4_AUTOFILL_HIDE_HIGHLIGHT
* |-------|-------|-------|-------|
*/
@@ -3470,6 +3471,11 @@
*/
static final int PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS = 0x000000100;
+ /**
+ * Flag indicating the field should not have yellow highlight when autofilled.
+ */
+ private static final int PFLAG4_AUTOFILL_HIDE_HIGHLIGHT = 0x100;
+
/* End of masks for mPrivateFlags4 */
/** @hide */
@@ -9170,6 +9176,13 @@
}
/**
+ * @hide
+ */
+ public boolean hideAutofillHighlight() {
+ return (mPrivateFlags4 & PFLAG4_AUTOFILL_HIDE_HIGHLIGHT) != 0;
+ }
+
+ /**
* Gets the {@link View}'s current autofill value.
*
* <p>By default returns {@code null}, but subclasses should override it and return an
@@ -11227,6 +11240,15 @@
}
/**
+ * @return {@code true} if any {@link WindowInsetsAnimation.Callback} is registered on the view
+ * or view tree of the sub-hierarchy {@code false} otherwise.
+ * @hide
+ */
+ public boolean hasWindowInsetsAnimationCallback() {
+ return getListenerInfo().mWindowInsetsAnimationCallback != null;
+ }
+
+ /**
* Dispatches {@link WindowInsetsAnimation.Callback#onPrepare(WindowInsetsAnimation)}
* when Window Insets animation is being prepared.
* @param animation current animation
@@ -11741,7 +11763,7 @@
* @hide
*/
@TestApi
- public void setAutofilled(boolean isAutofilled) {
+ public void setAutofilled(boolean isAutofilled, boolean hideHighlight) {
boolean wasChanged = isAutofilled != isAutofilled();
if (wasChanged) {
@@ -11751,6 +11773,12 @@
mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
}
+ if (hideHighlight) {
+ mPrivateFlags4 |= PFLAG4_AUTOFILL_HIDE_HIGHLIGHT;
+ } else {
+ mPrivateFlags4 &= ~PFLAG4_AUTOFILL_HIDE_HIGHLIGHT;
+ }
+
invalidate();
}
}
@@ -20569,6 +20597,7 @@
state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
state.mIsAutofilled = isAutofilled();
+ state.mHideHighlight = hideAutofillHighlight();
state.mAutofillViewId = mAutofillViewId;
return state;
}
@@ -20645,7 +20674,7 @@
mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
}
if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
- setAutofilled(baseState.mIsAutofilled);
+ setAutofilled(baseState.mIsAutofilled, baseState.mHideHighlight);
}
if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) {
// It can happen that views have the same view id and the restoration path will not
@@ -24078,12 +24107,13 @@
}
/**
- * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
+ * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled, unless
+ * {@link #PFLAG4_AUTOFILL_HIDE_HIGHLIGHT} is enabled.
*
* @param canvas The canvas to draw on
*/
private void drawAutofilledHighlight(@NonNull Canvas canvas) {
- if (isAutofilled()) {
+ if (isAutofilled() && !hideAutofillHighlight()) {
Drawable autofilledHighlight = getAutofilledDrawable();
if (autofilledHighlight != null) {
@@ -28526,6 +28556,7 @@
int mSavedData;
String mStartActivityRequestWhoSaved;
boolean mIsAutofilled;
+ boolean mHideHighlight;
int mAutofillViewId;
/**
@@ -28549,6 +28580,7 @@
mSavedData = source.readInt();
mStartActivityRequestWhoSaved = source.readString();
mIsAutofilled = source.readBoolean();
+ mHideHighlight = source.readBoolean();
mAutofillViewId = source.readInt();
}
@@ -28568,6 +28600,7 @@
out.writeInt(mSavedData);
out.writeString(mStartActivityRequestWhoSaved);
out.writeBoolean(mIsAutofilled);
+ out.writeBoolean(mHideHighlight);
out.writeInt(mAutofillViewId);
}
@@ -29066,8 +29099,33 @@
mTreeObserver = new ViewTreeObserver(context);
}
+ @Nullable
+ ContentCaptureManager getContentCaptureManager(@NonNull Context context) {
+ if (mContentCaptureManager != null) {
+ return mContentCaptureManager;
+ }
+ mContentCaptureManager = context.getSystemService(ContentCaptureManager.class);
+ return mContentCaptureManager;
+ }
+
+ void delayNotifyContentCaptureInsetsEvent(@NonNull Insets insets) {
+ if (mContentCaptureManager == null) {
+ return;
+ }
+
+ ArrayList<Object> events = ensureEvents(
+ mContentCaptureManager.getMainContentCaptureSession());
+ events.add(insets);
+ }
+
private void delayNotifyContentCaptureEvent(@NonNull ContentCaptureSession session,
@NonNull View view, boolean appeared) {
+ ArrayList<Object> events = ensureEvents(session);
+ events.add(appeared ? view : view.getAutofillId());
+ }
+
+ @NonNull
+ private ArrayList<Object> ensureEvents(@NonNull ContentCaptureSession session) {
if (mContentCaptureEvents == null) {
// Most of the time there will be just one session, so intial capacity is 1
mContentCaptureEvents = new SparseArray<>(1);
@@ -29079,16 +29137,8 @@
events = new ArrayList<>();
mContentCaptureEvents.put(sessionId, events);
}
- events.add(appeared ? view : view.getAutofillId());
- }
- @Nullable
- ContentCaptureManager getContentCaptureManager(@NonNull Context context) {
- if (mContentCaptureManager != null) {
- return mContentCaptureManager;
- }
- mContentCaptureManager = context.getSystemService(ContentCaptureManager.class);
- return mContentCaptureManager;
+ return events;
}
}
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index b6c46be..e34e84c 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -3714,7 +3714,7 @@
if (extraDataKey.equals(AccessibilityNodeInfo.EXTRA_DATA_RENDERING_INFO_KEY)) {
final AccessibilityNodeInfo.ExtraRenderingInfo extraRenderingInfo =
AccessibilityNodeInfo.ExtraRenderingInfo.obtain();
- extraRenderingInfo.setLayoutParams(getLayoutParams().width, getLayoutParams().height);
+ extraRenderingInfo.setLayoutSize(getLayoutParams().width, getLayoutParams().height);
info.setExtraRenderingInfo(extraRenderingInfo);
}
}
@@ -7258,6 +7258,34 @@
: DISPATCH_MODE_CONTINUE_ON_SUBTREE;
}
+ /**
+ * @hide
+ */
+ @Override
+ public boolean hasWindowInsetsAnimationCallback() {
+ if (super.hasWindowInsetsAnimationCallback()) {
+ return true;
+ }
+
+ // If we are root-level content view that fits insets, we imitate consuming behavior, so
+ // no child will retrieve window insets animation callback.
+ // See dispatchWindowInsetsAnimationPrepare.
+ boolean isOptionalFitSystemWindows = (mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) != 0
+ || isFrameworkOptionalFitsSystemWindows();
+ if (isOptionalFitSystemWindows && mAttachInfo != null
+ && mAttachInfo.mContentOnApplyWindowInsetsListener != null) {
+ return false;
+ }
+
+ final int count = getChildCount();
+ for (int i = 0; i < count; i++) {
+ if (getChildAt(i).hasWindowInsetsAnimationCallback()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
@Override
public void dispatchWindowInsetsAnimationPrepare(
@NonNull WindowInsetsAnimation animation) {
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 8d3cffc..dd34bcb 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -81,6 +81,7 @@
import android.graphics.Color;
import android.graphics.FrameInfo;
import android.graphics.HardwareRenderer.FrameDrawingCallback;
+import android.graphics.Insets;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Point;
@@ -1735,7 +1736,7 @@
mBoundsLayer = new SurfaceControl.Builder(mSurfaceSession)
.setContainerLayer()
.setName("Bounds for - " + getTitle().toString())
- .setParent(mSurfaceControl)
+ .setParent(getRenderSurfaceControl())
.build();
setBoundsLayerCrop();
mTransaction.show(mBoundsLayer).apply();
@@ -2254,6 +2255,7 @@
insets = insets.consumeDisplayCutout();
}
host.dispatchApplyWindowInsets(insets);
+ mAttachInfo.delayNotifyContentCaptureInsetsEvent(insets.getInsets(Type.all()));
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
@@ -3118,6 +3120,8 @@
ViewStructure structure = session.newViewStructure(view);
view.onProvideContentCaptureStructure(structure, /* flags= */ 0);
session.notifyViewAppeared(structure);
+ } else if (event instanceof Insets) {
+ mainSession.notifyViewInsetsChanged(sessionId, (Insets) event);
} else {
Log.w(mTag, "invalid content capture event: " + event);
}
@@ -5699,9 +5703,9 @@
mTranslator.translateEventInScreenToAppWindow(event);
}
- // Enter touch mode if event is coming from a touch screen device.
+ // Enter touch mode on down or scroll from any type of a device.
final int action = event.getAction();
- if (event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
+ if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
ensureTouchMode(true);
}
@@ -9054,7 +9058,7 @@
@Override
public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
- boolean sync) {
+ float zoom, boolean sync) {
if (sync) {
try {
mWindowSession.wallpaperOffsetsComplete(asBinder());
diff --git a/core/java/android/view/WindowContainerTransaction.java b/core/java/android/view/WindowContainerTransaction.java
index f406be9..9c16e13 100644
--- a/core/java/android/view/WindowContainerTransaction.java
+++ b/core/java/android/view/WindowContainerTransaction.java
@@ -72,6 +72,33 @@
}
/**
+ * Resize a container's app bounds. This is the bounds used to report appWidth/Height to an
+ * app's DisplayInfo. It is derived by subtracting the overlapping portion of the navbar from
+ * the full bounds.
+ */
+ public WindowContainerTransaction setAppBounds(IWindowContainer container, Rect appBounds) {
+ Change chg = getOrCreateChange(container.asBinder());
+ chg.mConfiguration.windowConfiguration.setAppBounds(appBounds);
+ chg.mConfigSetMask |= ActivityInfo.CONFIG_WINDOW_CONFIGURATION;
+ chg.mWindowSetMask |= WindowConfiguration.WINDOW_CONFIG_APP_BOUNDS;
+ return this;
+ }
+
+ /**
+ * Resize a container's configuration size. The configuration size is what gets reported to the
+ * app via screenWidth/HeightDp and influences which resources get loaded. This size is
+ * derived by subtracting the overlapping portions of both the statusbar and the navbar from
+ * the full bounds.
+ */
+ public WindowContainerTransaction setScreenSizeDp(IWindowContainer container, int w, int h) {
+ Change chg = getOrCreateChange(container.asBinder());
+ chg.mConfiguration.screenWidthDp = w;
+ chg.mConfiguration.screenHeightDp = h;
+ chg.mConfigSetMask |= ActivityInfo.CONFIG_SCREEN_SIZE;
+ return this;
+ }
+
+ /**
* Notify activies within the hiearchy of a container that they have entered picture-in-picture
* mode with the given bounds.
*/
@@ -104,6 +131,31 @@
}
/**
+ * Set the windowing mode of children of a given root task, without changing
+ * the windowing mode of the Task itself. This can be used during transitions
+ * for example to make the activity render it's fullscreen configuration
+ * while the Task is still in PIP, so you can complete the animation.
+ *
+ * TODO(b/134365562): Can be removed once TaskOrg drives full-screen
+ */
+ public WindowContainerTransaction setActivityWindowingMode(IWindowContainer container,
+ int windowingMode) {
+ Change chg = getOrCreateChange(container.asBinder());
+ chg.mActivityWindowingMode = windowingMode;
+ return this;
+ }
+
+ /**
+ * Sets the windowing mode of the given container.
+ */
+ public WindowContainerTransaction setWindowingMode(IWindowContainer container,
+ int windowingMode) {
+ Change chg = getOrCreateChange(container.asBinder());
+ chg.mWindowingMode = windowingMode;
+ return this;
+ }
+
+ /**
* Sets whether a container or any of its children can be focusable. When {@code false}, no
* child can be focused; however, when {@code true}, it is still possible for children to be
* non-focusable due to WM policy.
@@ -161,7 +213,8 @@
@Override
public String toString() {
- return "WindowContainerTransaction { changes = " + mChanges + " }";
+ return "WindowContainerTransaction { changes = " + mChanges + " hops = " + mHierarchyOps
+ + " }";
}
@Override
@@ -207,6 +260,9 @@
private Rect mPinnedBounds = null;
private SurfaceControl.Transaction mBoundsChangeTransaction = null;
+ private int mActivityWindowingMode = -1;
+ private int mWindowingMode = -1;
+
public Change() {}
protected Change(Parcel in) {
@@ -223,6 +279,17 @@
mBoundsChangeTransaction =
SurfaceControl.Transaction.CREATOR.createFromParcel(in);
}
+
+ mWindowingMode = in.readInt();
+ mActivityWindowingMode = in.readInt();
+ }
+
+ public int getWindowingMode() {
+ return mWindowingMode;
+ }
+
+ public int getActivityWindowingMode() {
+ return mActivityWindowingMode;
}
public Configuration getConfiguration() {
@@ -269,6 +336,11 @@
(mConfigSetMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0
&& ((mWindowSetMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS)
!= 0);
+ final boolean changesAppBounds =
+ (mConfigSetMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0
+ && ((mWindowSetMask & WindowConfiguration.WINDOW_CONFIG_APP_BOUNDS)
+ != 0);
+ final boolean changesSs = (mConfigSetMask & ActivityInfo.CONFIG_SCREEN_SIZE) != 0;
final boolean changesSss =
(mConfigSetMask & ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE) != 0;
StringBuilder sb = new StringBuilder();
@@ -276,9 +348,16 @@
if (changesBounds) {
sb.append("bounds:" + mConfiguration.windowConfiguration.getBounds() + ",");
}
+ if (changesAppBounds) {
+ sb.append("appbounds:" + mConfiguration.windowConfiguration.getAppBounds() + ",");
+ }
if (changesSss) {
sb.append("ssw:" + mConfiguration.smallestScreenWidthDp + ",");
}
+ if (changesSs) {
+ sb.append("sw/h:" + mConfiguration.screenWidthDp + "x"
+ + mConfiguration.screenHeightDp + ",");
+ }
if ((mChangeMask & CHANGE_FOCUSABLE) != 0) {
sb.append("focusable:" + mFocusable + ",");
}
@@ -300,6 +379,9 @@
if (mBoundsChangeTransaction != null) {
mBoundsChangeTransaction.writeToParcel(dest, flags);
}
+
+ dest.writeInt(mWindowingMode);
+ dest.writeInt(mActivityWindowingMode);
}
@Override
diff --git a/core/java/android/view/WindowInsetsAnimationControlListener.java b/core/java/android/view/WindowInsetsAnimationControlListener.java
index 701bd31..faaf920 100644
--- a/core/java/android/view/WindowInsetsAnimationControlListener.java
+++ b/core/java/android/view/WindowInsetsAnimationControlListener.java
@@ -16,7 +16,6 @@
package android.view;
-import android.annotation.Hide;
import android.annotation.NonNull;
import android.view.WindowInsets.Type.InsetsType;
import android.view.inputmethod.EditorInfo;
diff --git a/core/java/android/view/WindowInsetsController.java b/core/java/android/view/WindowInsetsController.java
index b7ca037..0282eca 100644
--- a/core/java/android/view/WindowInsetsController.java
+++ b/core/java/android/view/WindowInsetsController.java
@@ -20,7 +20,9 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.graphics.Insets;
+import android.inputmethodservice.InputMethodService;
import android.os.CancellationSignal;
+import android.view.WindowInsets.Type;
import android.view.WindowInsets.Type.InsetsType;
import android.view.animation.Interpolator;
@@ -154,16 +156,17 @@
* calculate {@link WindowInsetsAnimation#getInterpolatedFraction()}.
* @param listener The {@link WindowInsetsAnimationControlListener} that gets called when the
* windows are ready to be controlled, among other callbacks.
- * @return A cancellation signal that the caller can use to cancel the request to obtain
- * control, or once they have control, to cancel the control.
+ * @param cancellationSignal A cancellation signal that the caller can use to cancel the
+ * request to obtain control, or once they have control, to cancel the
+ * control.
* @see WindowInsetsAnimation#getFraction()
* @see WindowInsetsAnimation#getInterpolatedFraction()
* @see WindowInsetsAnimation#getInterpolator()
* @see WindowInsetsAnimation#getDurationMillis()
*/
- @NonNull
- CancellationSignal controlWindowInsetsAnimation(@InsetsType int types, long durationMillis,
+ void controlWindowInsetsAnimation(@InsetsType int types, long durationMillis,
@Nullable Interpolator interpolator,
+ @Nullable CancellationSignal cancellationSignal,
@NonNull WindowInsetsAnimationControlListener listener);
/**
@@ -212,4 +215,55 @@
* @hide
*/
InsetsState getState();
+
+ /**
+ * Adds a {@link OnControllableInsetsChangedListener} to the window insets controller.
+ *
+ * @param listener The listener to add.
+ *
+ * @see OnControllableInsetsChangedListener
+ * @see #removeOnControllableInsetsChangedListener(OnControllableInsetsChangedListener)
+ */
+ void addOnControllableInsetsChangedListener(
+ @NonNull OnControllableInsetsChangedListener listener);
+
+ /**
+ * Removes a {@link OnControllableInsetsChangedListener} from the window insets controller.
+ *
+ * @param listener The listener to remove.
+ *
+ * @see OnControllableInsetsChangedListener
+ * @see #addOnControllableInsetsChangedListener(OnControllableInsetsChangedListener)
+ */
+ void removeOnControllableInsetsChangedListener(
+ @NonNull OnControllableInsetsChangedListener listener);
+
+ /**
+ * Listener to be notified when the set of controllable {@link InsetsType} controlled by a
+ * {@link WindowInsetsController} changes.
+ * <p>
+ * Once a {@link InsetsType} becomes controllable, the app will be able to control the window
+ * that is causing this type of insets by calling {@link #controlWindowInsetsAnimation}.
+ * <p>
+ * Note: When listening to controllability of the {@link Type#ime},
+ * {@link #controlWindowInsetsAnimation} may still fail in case the {@link InputMethodService}
+ * decides to cancel the show request. This could happen when there is a hardware keyboard
+ * attached.
+ *
+ * @see #addOnControllableInsetsChangedListener(OnControllableInsetsChangedListener)
+ * @see #removeOnControllableInsetsChangedListener(OnControllableInsetsChangedListener)
+ */
+ interface OnControllableInsetsChangedListener {
+
+ /**
+ * Called when the set of controllable {@link InsetsType} changes.
+ *
+ * @param controller The controller for which the set of controllable {@link InsetsType}s
+ * are changing.
+ * @param typeMask Bitwise type-mask of the {@link InsetsType}s the controller is currently
+ * able to control.
+ */
+ void onControllableInsetsChanged(@NonNull WindowInsetsController controller,
+ @InsetsType int typeMask);
+ }
}
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index 867b648..c5fa3c8 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -805,6 +805,7 @@
@ViewDebug.IntToString(from = TYPE_APPLICATION_OVERLAY,
to = "APPLICATION_OVERLAY")
})
+ @WindowType
public int type;
/**
@@ -1244,13 +1245,47 @@
public static final int INVALID_WINDOW_TYPE = -1;
/**
+ * @hide
+ */
+ @IntDef(prefix = "TYPE_", value = {
+ TYPE_ACCESSIBILITY_OVERLAY,
+ TYPE_APPLICATION,
+ TYPE_APPLICATION_ATTACHED_DIALOG,
+ TYPE_APPLICATION_MEDIA,
+ TYPE_APPLICATION_OVERLAY,
+ TYPE_APPLICATION_PANEL,
+ TYPE_APPLICATION_STARTING,
+ TYPE_APPLICATION_SUB_PANEL,
+ TYPE_BASE_APPLICATION,
+ TYPE_DRAWN_APPLICATION,
+ TYPE_INPUT_METHOD,
+ TYPE_INPUT_METHOD_DIALOG,
+ TYPE_KEYGUARD,
+ TYPE_KEYGUARD_DIALOG,
+ TYPE_PHONE,
+ TYPE_PRIORITY_PHONE,
+ TYPE_PRIVATE_PRESENTATION,
+ TYPE_SEARCH_BAR,
+ TYPE_STATUS_BAR,
+ TYPE_STATUS_BAR_PANEL,
+ TYPE_SYSTEM_ALERT,
+ TYPE_SYSTEM_DIALOG,
+ TYPE_SYSTEM_ERROR,
+ TYPE_SYSTEM_OVERLAY,
+ TYPE_TOAST,
+ TYPE_WALLPAPER,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface WindowType {}
+
+ /**
* Return true if the window type is an alert window.
*
* @param type The window type.
* @return If the window type is an alert window.
* @hide
*/
- public static boolean isSystemAlertWindowType(int type) {
+ public static boolean isSystemAlertWindowType(@WindowType int type) {
switch (type) {
case TYPE_PHONE:
case TYPE_PRIORITY_PHONE:
diff --git a/core/java/android/view/WindowManagerGlobal.java b/core/java/android/view/WindowManagerGlobal.java
index 01a1c77..410d9af 100644
--- a/core/java/android/view/WindowManagerGlobal.java
+++ b/core/java/android/view/WindowManagerGlobal.java
@@ -504,6 +504,7 @@
}
void doRemoveView(ViewRootImpl root) {
+ boolean allViewsRemoved;
synchronized (mLock) {
final int index = mRoots.indexOf(root);
if (index >= 0) {
@@ -512,10 +513,17 @@
final View view = mViews.remove(index);
mDyingViews.remove(view);
}
+ allViewsRemoved = mRoots.isEmpty();
}
if (ThreadedRenderer.sTrimForeground && ThreadedRenderer.isAvailable()) {
doTrimForeground();
}
+
+ // If we don't have any views anymore in our process, we no longer need the
+ // InsetsAnimationThread to save some resources.
+ if (allViewsRemoved) {
+ InsetsAnimationThread.release();
+ }
}
private int findViewLocked(View view, boolean required) {
diff --git a/core/java/android/view/WindowManagerImpl.java b/core/java/android/view/WindowManagerImpl.java
index 6435b42..4050da1 100644
--- a/core/java/android/view/WindowManagerImpl.java
+++ b/core/java/android/view/WindowManagerImpl.java
@@ -18,8 +18,11 @@
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
+import static android.view.View.SYSTEM_UI_FLAG_VISIBLE;
+import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
import android.annotation.NonNull;
import android.app.ResourcesManager;
@@ -215,9 +218,9 @@
@Override
public WindowMetrics getCurrentWindowMetrics() {
final Context context = mParentWindow != null ? mParentWindow.getContext() : mContext;
- final Rect bound = getCurrentBounds(context);
+ final Rect bounds = getCurrentBounds(context);
- return new WindowMetrics(toSize(bound), computeWindowInsets());
+ return new WindowMetrics(toSize(bounds), computeWindowInsets(bounds));
}
private static Rect getCurrentBounds(Context context) {
@@ -228,7 +231,8 @@
@Override
public WindowMetrics getMaximumWindowMetrics() {
- return new WindowMetrics(toSize(getMaximumBounds()), computeWindowInsets());
+ final Rect maxBounds = getMaximumBounds();
+ return new WindowMetrics(toSize(maxBounds), computeWindowInsets(maxBounds));
}
private Size toSize(Rect frame) {
@@ -244,9 +248,8 @@
return new Rect(0, 0, displaySize.x, displaySize.y);
}
- private WindowInsets computeWindowInsets() {
- // TODO(b/118118435): This can only be properly implemented
- // once we flip the new insets mode flag.
+ // TODO(b/150095967): Set window type to LayoutParams
+ private WindowInsets computeWindowInsets(Rect bounds) {
// Initialize params which used for obtaining all system insets.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.flags = FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR;
@@ -257,21 +260,34 @@
params.setFitInsetsTypes(0);
params.setFitInsetsSides(0);
- return getWindowInsetsFromServer(params);
+ return getWindowInsetsFromServer(params, bounds);
}
- private WindowInsets getWindowInsetsFromServer(WindowManager.LayoutParams attrs) {
+ private WindowInsets getWindowInsetsFromServer(WindowManager.LayoutParams attrs, Rect bounds) {
try {
final Rect systemWindowInsets = new Rect();
final Rect stableInsets = new Rect();
final DisplayCutout.ParcelableWrapper displayCutout =
new DisplayCutout.ParcelableWrapper();
- WindowManagerGlobal.getWindowManagerService().getWindowInsets(attrs,
- mContext.getDisplayId(), systemWindowInsets, stableInsets, displayCutout);
- return new WindowInsets.Builder()
- .setSystemWindowInsets(Insets.of(systemWindowInsets))
- .setStableInsets(Insets.of(stableInsets))
- .setDisplayCutout(displayCutout.get()).build();
+ final InsetsState insetsState = new InsetsState();
+ final boolean alwaysConsumeSystemBars = WindowManagerGlobal.getWindowManagerService()
+ .getWindowInsets(attrs, mContext.getDisplayId(), systemWindowInsets,
+ stableInsets, displayCutout, insetsState);
+ final boolean isScreenRound =
+ mContext.getResources().getConfiguration().isScreenRound();
+ if (ViewRootImpl.sNewInsetsMode == NEW_INSETS_MODE_FULL) {
+ return insetsState.calculateInsets(bounds, null /* ignoringVisibilityState*/,
+ isScreenRound, alwaysConsumeSystemBars, displayCutout.get(),
+ systemWindowInsets, stableInsets, SOFT_INPUT_ADJUST_NOTHING,
+ SYSTEM_UI_FLAG_VISIBLE, null /* typeSideMap */);
+ } else {
+ return new WindowInsets.Builder()
+ .setAlwaysConsumeSystemBars(alwaysConsumeSystemBars)
+ .setRound(isScreenRound)
+ .setSystemWindowInsets(Insets.of(systemWindowInsets))
+ .setStableInsets(Insets.of(stableInsets))
+ .setDisplayCutout(displayCutout.get()).build();
+ }
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/core/java/android/view/WindowlessWindowManager.java b/core/java/android/view/WindowlessWindowManager.java
index 87dcba0..144f8e3 100644
--- a/core/java/android/view/WindowlessWindowManager.java
+++ b/core/java/android/view/WindowlessWindowManager.java
@@ -312,6 +312,14 @@
}
@Override
+ public void setWallpaperZoomOut(android.os.IBinder windowToken, float zoom) {
+ }
+
+ @Override
+ public void setShouldZoomOutWallpaper(android.os.IBinder windowToken, boolean shouldZoom) {
+ }
+
+ @Override
public void wallpaperOffsetsComplete(android.os.IBinder window) {
}
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
index f2cbf89..5fccf40 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
@@ -559,14 +559,6 @@
public static final String ACTION_ARGUMENT_PRESS_AND_HOLD_DURATION_MILLIS_INT =
"android.view.accessibility.action.ARGUMENT_PRESS_AND_HOLD_DURATION_MILLIS_INT";
- /**
- * Argument to represent the IME action Id to press the returning key on a node.
- * For use with R.id.accessibilityActionImeEnter
- * @hide
- */
- public static final String ACTION_ARGUMENT_IME_ACTION_ID_INT =
- "android.view.accessibility.action.ARGUMENT_IME_ACTION_ID_INT";
-
// Focus types
/**
@@ -649,7 +641,7 @@
* argument.
* <p>
* The data can be retrieved from the {@link ExtraRenderingInfo} returned by
- * {@link #getExtraRenderingInfo()} using {@link ExtraRenderingInfo#getLayoutParams},
+ * {@link #getExtraRenderingInfo()} using {@link ExtraRenderingInfo#getLayoutSize},
* {@link ExtraRenderingInfo#getTextSizeInPx()} and
* {@link ExtraRenderingInfo#getTextSizeUnit()}. For layout params, it is supported by both
* {@link TextView} and {@link ViewGroup}. For text size and unit, it is only supported by
@@ -657,7 +649,6 @@
*
* @see #refreshWithExtraData(String, Bundle)
*/
-
public static final String EXTRA_DATA_RENDERING_INFO_KEY =
"android.view.accessibility.extra.DATA_RENDERING_INFO_KEY";
@@ -1038,8 +1029,8 @@
* with this mechanism is generally expensive to retrieve, so should only be
* requested when needed. See
* {@link #EXTRA_DATA_RENDERING_INFO_KEY},
- * {@link #EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY} and
- * {@link #getAvailableExtraData()}.
+ * {@link #EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY},
+ * {@link #getAvailableExtraData()} and {@link #getExtraRenderingInfo()}.
* @param args A bundle of arguments for the request. These depend on the particular request.
*
* @return {@code true} if the refresh succeeded. {@code false} if the {@link View} represented
@@ -2437,9 +2428,13 @@
}
/**
- * Gets the conformance info if the node is meant to be refreshed with extra data.
+ * Gets the {@link ExtraRenderingInfo extra rendering info} if the node is meant to be
+ * refreshed with extra data to examine rendering related accessibility issues.
*
- * @return The conformance info.
+ * @return The {@link ExtraRenderingInfo extra rendering info}.
+ *
+ * @see #EXTRA_DATA_RENDERING_INFO_KEY
+ * @see #refreshWithExtraData(String, Bundle)
*/
@Nullable
public ExtraRenderingInfo getExtraRenderingInfo() {
@@ -2447,14 +2442,15 @@
}
/**
- * Sets the conformance info if the node is meant to be refreshed with extra data.
+ * Sets the extra rendering info, <code>extraRenderingInfo<code/>, if the node is meant to be
+ * refreshed with extra data.
* <p>
* <strong>Note:</strong> Cannot be called from an
* {@link android.accessibilityservice.AccessibilityService}.
* This class is made immutable before being delivered to an AccessibilityService.
* </p>
*
- * @param extraRenderingInfo The conformance info.
+ * @param extraRenderingInfo The {@link ExtraRenderingInfo extra rendering info}.
* @hide
*/
public void setExtraRenderingInfo(@NonNull ExtraRenderingInfo extraRenderingInfo) {
@@ -3925,7 +3921,7 @@
}
if (isBitSet(nonDefaultFields, fieldIndex++)) {
- parcel.writeValue(mExtraRenderingInfo.getLayoutParams());
+ parcel.writeValue(mExtraRenderingInfo.getLayoutSize());
parcel.writeFloat(mExtraRenderingInfo.getTextSizeInPx());
parcel.writeInt(mExtraRenderingInfo.getTextSizeUnit());
}
@@ -4189,7 +4185,7 @@
if (isBitSet(nonDefaultFields, fieldIndex++)) {
if (mExtraRenderingInfo != null) mExtraRenderingInfo.recycle();
mExtraRenderingInfo = ExtraRenderingInfo.obtain();
- mExtraRenderingInfo.mLayoutParams = (Size) parcel.readValue(null);
+ mExtraRenderingInfo.mLayoutSize = (Size) parcel.readValue(null);
mExtraRenderingInfo.mTextSizeInPx = parcel.readFloat();
mExtraRenderingInfo.mTextSizeUnit = parcel.readInt();
}
@@ -4969,10 +4965,11 @@
new AccessibilityAction(R.id.accessibilityActionPressAndHold);
/**
- * Action to send an ime action which is from
- * {@link android.view.inputmethod.EditorInfo#actionId}. This action would be
+ * Action to send an ime actionId which is from
+ * {@link android.view.inputmethod.EditorInfo#actionId}. This ime actionId sets by
+ * {@link TextView#setImeActionLabel(CharSequence, int)}, or it would be
* {@link android.view.inputmethod.EditorInfo#IME_ACTION_UNSPECIFIED} if no specific
- * actionId defined. A node should expose this action only for views that are currently
+ * actionId has set. A node should expose this action only for views that are currently
* with input focus and editable.
*/
@NonNull public static final AccessibilityAction ACTION_IME_ENTER =
@@ -5808,7 +5805,7 @@
private static final SynchronizedPool<ExtraRenderingInfo> sPool =
new SynchronizedPool<>(MAX_POOL_SIZE);
- private Size mLayoutParams;
+ private Size mLayoutSize;
private float mTextSizeInPx = UNDEFINED_VALUE;
private int mTextSizeUnit = UNDEFINED_VALUE;
@@ -5828,32 +5825,36 @@
/** Obtains a pooled instance that is a clone of another one. */
private static ExtraRenderingInfo obtain(ExtraRenderingInfo other) {
ExtraRenderingInfo extraRenderingInfo = ExtraRenderingInfo.obtain();
- extraRenderingInfo.mLayoutParams = other.mLayoutParams;
+ extraRenderingInfo.mLayoutSize = other.mLayoutSize;
extraRenderingInfo.mTextSizeInPx = other.mTextSizeInPx;
extraRenderingInfo.mTextSizeUnit = other.mTextSizeUnit;
return extraRenderingInfo;
}
/**
- * Creates a new conformance info of a view, and this new instance is initialized from
+ * Creates a new rendering info of a view, and this new instance is initialized from
* the given <code>other</code>.
*
* @param other The instance to clone.
*/
private ExtraRenderingInfo(@Nullable ExtraRenderingInfo other) {
if (other != null) {
- mLayoutParams = other.mLayoutParams;
+ mLayoutSize = other.mLayoutSize;
mTextSizeInPx = other.mTextSizeInPx;
mTextSizeUnit = other.mTextSizeUnit;
}
}
/**
+ * Gets the size object containing the height and the width of layout params if the node is
+ * a {@link ViewGroup} or a {@link TextView}, or null otherwise. Useful for accessibility
+ * scanning tool to understand whether the text is scalable and fits the view or not.
+ *
* @return a {@link Size} stores layout height and layout width of the view,
* or null otherwise.
*/
- public @Nullable Size getLayoutParams() {
- return mLayoutParams;
+ public @Nullable Size getLayoutSize() {
+ return mLayoutSize;
}
/**
@@ -5863,11 +5864,15 @@
* @param height The layout height.
* @hide
*/
- public void setLayoutParams(int width, int height) {
- mLayoutParams = new Size(width, height);
+ public void setLayoutSize(int width, int height) {
+ mLayoutSize = new Size(width, height);
}
/**
+ * Gets the text size if the node is a {@link TextView}, or -1 otherwise. Useful for
+ * accessibility scanning tool to understand whether the text is scalable and fits the view
+ * or not.
+ *
* @return the text size of a {@code TextView}, or -1 otherwise.
*/
public float getTextSizeInPx() {
@@ -5885,6 +5890,11 @@
}
/**
+ * Gets the text size unit if the node is a {@link TextView}, or -1 otherwise.
+ * Text size returned from {@link #getTextSizeInPx} in raw pixels may scale by factors and
+ * convert from other units. Useful for accessibility scanning tool to understand whether
+ * the text is scalable and fits the view or not.
+ *
* @return the text size unit which type is {@link TypedValue#TYPE_DIMENSION} of a
* {@code TextView}, or -1 otherwise.
*
@@ -5915,7 +5925,7 @@
}
private void clear() {
- mLayoutParams = null;
+ mLayoutSize = null;
mTextSizeInPx = UNDEFINED_VALUE;
mTextSizeUnit = UNDEFINED_VALUE;
}
diff --git a/core/java/android/view/autofill/AutofillManager.java b/core/java/android/view/autofill/AutofillManager.java
index ce7cfa7..39a9ed4 100644
--- a/core/java/android/view/autofill/AutofillManager.java
+++ b/core/java/android/view/autofill/AutofillManager.java
@@ -17,6 +17,7 @@
package android.view.autofill;
import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
+import static android.service.autofill.FillRequest.FLAG_PASSWORD_INPUT_TYPE;
import static android.view.autofill.Helper.sDebug;
import static android.view.autofill.Helper.sVerbose;
import static android.view.autofill.Helper.toList;
@@ -63,6 +64,7 @@
import android.view.accessibility.AccessibilityNodeProvider;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.EditText;
+import android.widget.TextView;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.logging.MetricsLogger;
@@ -983,6 +985,10 @@
if (!isClientDisablingEnterExitEvent()) {
final AutofillValue value = view.getAutofillValue();
+ if (view instanceof TextView && ((TextView) view).isAnyPasswordInputType()) {
+ flags |= FLAG_PASSWORD_INPUT_TYPE;
+ }
+
if (!isActiveLocked()) {
// Starts new session.
startSessionLocked(id, null, value, flags);
@@ -1149,6 +1155,10 @@
} else {
// don't notify entered when Activity is already in background
if (!isClientDisablingEnterExitEvent()) {
+ if (view instanceof TextView && ((TextView) view).isAnyPasswordInputType()) {
+ flags |= FLAG_PASSWORD_INPUT_TYPE;
+ }
+
if (!isActiveLocked()) {
// Starts new session.
startSessionLocked(id, bounds, null, flags);
@@ -1226,7 +1236,7 @@
// If the session is gone some fields might still be highlighted, hence we have to
// remove the isAutofilled property even if no sessions are active.
if (mLastAutofilledData == null) {
- view.setAutofilled(false);
+ view.setAutofilled(false, false);
} else {
id = view.getAutofillId();
if (mLastAutofilledData.containsKey(id)) {
@@ -1234,13 +1244,13 @@
valueWasRead = true;
if (Objects.equals(mLastAutofilledData.get(id), value)) {
- view.setAutofilled(true);
+ view.setAutofilled(true, false);
} else {
- view.setAutofilled(false);
+ view.setAutofilled(false, false);
mLastAutofilledData.remove(id);
}
} else {
- view.setAutofilled(false);
+ view.setAutofilled(false, false);
}
}
@@ -2156,7 +2166,8 @@
* @param view The view that is to be autofilled
* @param targetValue The value we want to fill into view
*/
- private void setAutofilledIfValuesIs(@NonNull View view, @Nullable AutofillValue targetValue) {
+ private void setAutofilledIfValuesIs(@NonNull View view, @Nullable AutofillValue targetValue,
+ boolean hideHighlight) {
AutofillValue currentValue = view.getAutofillValue();
if (Objects.equals(currentValue, targetValue)) {
synchronized (mLock) {
@@ -2165,11 +2176,12 @@
}
mLastAutofilledData.put(view.getAutofillId(), targetValue);
}
- view.setAutofilled(true);
+ view.setAutofilled(true, hideHighlight);
}
}
- private void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
+ private void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values,
+ boolean hideHighlight) {
synchronized (mLock) {
if (sessionId != mSessionId) {
return;
@@ -2228,7 +2240,7 @@
// synchronously.
// If autofill happens async, the view is set to autofilled in
// notifyValueChanged.
- setAutofilledIfValuesIs(view, value);
+ setAutofilledIfValuesIs(view, value, hideHighlight);
numApplied++;
}
@@ -3246,10 +3258,11 @@
}
@Override
- public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
+ public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values,
+ boolean hideHighlight) {
final AutofillManager afm = mAfm.get();
if (afm != null) {
- afm.post(() -> afm.autofill(sessionId, ids, values));
+ afm.post(() -> afm.autofill(sessionId, ids, values, hideHighlight));
}
}
@@ -3387,10 +3400,11 @@
}
@Override
- public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values) {
+ public void autofill(int sessionId, List<AutofillId> ids, List<AutofillValue> values,
+ boolean hideHighlight) {
final AutofillManager afm = mAfm.get();
if (afm != null) {
- afm.post(() -> afm.autofill(sessionId, ids, values));
+ afm.post(() -> afm.autofill(sessionId, ids, values, hideHighlight));
}
}
diff --git a/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl b/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl
index 03054df..8526c1e 100644
--- a/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl
+++ b/core/java/android/view/autofill/IAugmentedAutofillManagerClient.aidl
@@ -38,7 +38,8 @@
/**
* Autofills the activity with the contents of the values.
*/
- void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values);
+ void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values,
+ boolean hideHighlight);
/**
* Requests showing the fill UI.
diff --git a/core/java/android/view/autofill/IAutoFillManagerClient.aidl b/core/java/android/view/autofill/IAutoFillManagerClient.aidl
index 3903665..4371b3c 100644
--- a/core/java/android/view/autofill/IAutoFillManagerClient.aidl
+++ b/core/java/android/view/autofill/IAutoFillManagerClient.aidl
@@ -44,7 +44,8 @@
/**
* Autofills the activity with the contents of a dataset.
*/
- void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values);
+ void autofill(int sessionId, in List<AutofillId> ids, in List<AutofillValue> values,
+ boolean hideHighlight);
/**
* Authenticates a fill response or a data set.
diff --git a/core/java/android/view/contentcapture/ChildContentCaptureSession.java b/core/java/android/view/contentcapture/ChildContentCaptureSession.java
index 7487ec4..44b4353 100644
--- a/core/java/android/view/contentcapture/ChildContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ChildContentCaptureSession.java
@@ -17,6 +17,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.graphics.Insets;
import android.view.autofill.AutofillId;
import android.view.contentcapture.ViewNode.ViewStructureImpl;
@@ -84,6 +85,11 @@
}
@Override
+ void internalNotifyViewInsetsChanged(@NonNull Insets viewInsets) {
+ getMainCaptureSession().notifyViewInsetsChanged(mId, viewInsets);
+ }
+
+ @Override
public void internalNotifyViewTreeEvent(boolean started) {
getMainCaptureSession().notifyViewTreeEvent(mId, started);
}
diff --git a/core/java/android/view/contentcapture/ContentCaptureEvent.java b/core/java/android/view/contentcapture/ContentCaptureEvent.java
index c29d251..ea34d94 100644
--- a/core/java/android/view/contentcapture/ContentCaptureEvent.java
+++ b/core/java/android/view/contentcapture/ContentCaptureEvent.java
@@ -23,6 +23,7 @@
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
+import android.graphics.Insets;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
@@ -112,6 +113,11 @@
*/
public static final int TYPE_SESSION_PAUSED = 8;
+ /**
+ * Called when the view's insets are changed. The new insets associated with the
+ * event may then be retrieved by calling {@link #getInsets()}
+ */
+ public static final int TYPE_VIEW_INSETS_CHANGED = 9;
/** @hide */
@IntDef(prefix = { "TYPE_" }, value = {
@@ -122,7 +128,8 @@
TYPE_VIEW_TREE_APPEARED,
TYPE_CONTEXT_UPDATED,
TYPE_SESSION_PAUSED,
- TYPE_SESSION_RESUMED
+ TYPE_SESSION_RESUMED,
+ TYPE_VIEW_INSETS_CHANGED
})
@Retention(RetentionPolicy.SOURCE)
public @interface EventType{}
@@ -136,6 +143,7 @@
private @Nullable CharSequence mText;
private int mParentSessionId = NO_SESSION_ID;
private @Nullable ContentCaptureContext mClientContext;
+ private @Nullable Insets mInsets;
/** @hide */
public ContentCaptureEvent(int sessionId, int type, long eventTime) {
@@ -242,6 +250,13 @@
return this;
}
+ /** @hide */
+ @NonNull
+ public ContentCaptureEvent setInsets(@NonNull Insets insets) {
+ mInsets = insets;
+ return this;
+ }
+
/**
* Gets the type of the event.
*
@@ -305,6 +320,16 @@
}
/**
+ * Gets the rectangle of the insets associated with the event. Valid insets will only be
+ * returned if the type of the event is {@link #TYPE_VIEW_INSETS_CHANGED}, otherwise they
+ * will be null.
+ */
+ @Nullable
+ public Insets getInsets() {
+ return mInsets;
+ }
+
+ /**
* Merges event of the same type, either {@link #TYPE_VIEW_TEXT_CHANGED}
* or {@link #TYPE_VIEW_DISAPPEARED}.
*
@@ -369,7 +394,9 @@
}
if (mClientContext != null) {
pw.print(", context="); mClientContext.dump(pw); pw.println();
-
+ }
+ if (mInsets != null) {
+ pw.print(", insets="); pw.println(mInsets);
}
}
@@ -401,6 +428,9 @@
if (mClientContext != null) {
string.append(", context=").append(mClientContext);
}
+ if (mInsets != null) {
+ string.append(", insets=").append(mInsets);
+ }
return string.append(']').toString();
}
@@ -424,6 +454,9 @@
if (mType == TYPE_SESSION_STARTED || mType == TYPE_CONTEXT_UPDATED) {
parcel.writeParcelable(mClientContext, flags);
}
+ if (mType == TYPE_VIEW_INSETS_CHANGED) {
+ parcel.writeParcelable(mInsets, flags);
+ }
}
public static final @android.annotation.NonNull Parcelable.Creator<ContentCaptureEvent> CREATOR =
@@ -455,6 +488,9 @@
if (type == TYPE_SESSION_STARTED || type == TYPE_CONTEXT_UPDATED) {
event.setClientContext(parcel.readParcelable(null));
}
+ if (type == TYPE_VIEW_INSETS_CHANGED) {
+ event.setInsets(parcel.readParcelable(null));
+ }
return event;
}
@@ -488,6 +524,8 @@
return "VIEW_TREE_APPEARED";
case TYPE_CONTEXT_UPDATED:
return "CONTEXT_UPDATED";
+ case TYPE_VIEW_INSETS_CHANGED:
+ return "VIEW_INSETS_CHANGED";
default:
return "UKNOWN_TYPE: " + type;
}
diff --git a/core/java/android/view/contentcapture/ContentCaptureManager.java b/core/java/android/view/contentcapture/ContentCaptureManager.java
index b7b54c8..b988927 100644
--- a/core/java/android/view/contentcapture/ContentCaptureManager.java
+++ b/core/java/android/view/contentcapture/ContentCaptureManager.java
@@ -217,6 +217,15 @@
public static final int DATA_SHARE_ERROR_TIMEOUT_INTERRUPTED = 3;
/** @hide */
+ @IntDef(flag = false, value = {
+ DATA_SHARE_ERROR_UNKNOWN,
+ DATA_SHARE_ERROR_CONCURRENT_REQUEST,
+ DATA_SHARE_ERROR_TIMEOUT_INTERRUPTED
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface DataShareError {}
+
+ /** @hide */
public static final int RESULT_CODE_OK = 0;
/** @hide */
public static final int RESULT_CODE_TRUE = 1;
diff --git a/core/java/android/view/contentcapture/ContentCaptureSession.java b/core/java/android/view/contentcapture/ContentCaptureSession.java
index 2134dab..012f5e6 100644
--- a/core/java/android/view/contentcapture/ContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/ContentCaptureSession.java
@@ -23,6 +23,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
+import android.graphics.Insets;
import android.util.DebugUtils;
import android.util.Log;
import android.view.View;
@@ -440,6 +441,19 @@
abstract void internalNotifyViewTextChanged(@NonNull AutofillId id,
@Nullable CharSequence text);
+ /**
+ * Notifies the Intelligence Service that the insets of a view have changed.
+ */
+ public final void notifyViewInsetsChanged(@NonNull Insets viewInsets) {
+ Preconditions.checkNotNull(viewInsets);
+
+ if (!isContentCaptureEnabled()) return;
+
+ internalNotifyViewInsetsChanged(viewInsets);
+ }
+
+ abstract void internalNotifyViewInsetsChanged(@NonNull Insets viewInsets);
+
/** @hide */
public abstract void internalNotifyViewTreeEvent(boolean started);
diff --git a/core/java/android/view/contentcapture/DataShareWriteAdapter.java b/core/java/android/view/contentcapture/DataShareWriteAdapter.java
index 2beaede..3b5b756 100644
--- a/core/java/android/view/contentcapture/DataShareWriteAdapter.java
+++ b/core/java/android/view/contentcapture/DataShareWriteAdapter.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.os.ParcelFileDescriptor;
+import android.view.contentcapture.ContentCaptureManager.DataShareError;
/** Adapter class used by apps to share data with the Content Capture service. */
public interface DataShareWriteAdapter {
@@ -42,7 +43,7 @@
*
* @param errorCode the error code corresponding to an ERROR_* value.
*/
- default void onError(int errorCode) {
+ default void onError(@DataShareError int errorCode) {
/* do nothing - stub */
}
}
diff --git a/core/java/android/view/contentcapture/MainContentCaptureSession.java b/core/java/android/view/contentcapture/MainContentCaptureSession.java
index 96f224f..893d38d 100644
--- a/core/java/android/view/contentcapture/MainContentCaptureSession.java
+++ b/core/java/android/view/contentcapture/MainContentCaptureSession.java
@@ -22,6 +22,7 @@
import static android.view.contentcapture.ContentCaptureEvent.TYPE_SESSION_STARTED;
import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_APPEARED;
import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_DISAPPEARED;
+import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_INSETS_CHANGED;
import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TEXT_CHANGED;
import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TREE_APPEARED;
import static android.view.contentcapture.ContentCaptureEvent.TYPE_VIEW_TREE_APPEARING;
@@ -36,6 +37,7 @@
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ParceledListSlice;
+import android.graphics.Insets;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
@@ -578,6 +580,11 @@
}
@Override
+ void internalNotifyViewInsetsChanged(@NonNull Insets viewInsets) {
+ notifyViewInsetsChanged(mId, viewInsets);
+ }
+
+ @Override
public void internalNotifyViewTreeEvent(boolean started) {
notifyViewTreeEvent(mId, started);
}
@@ -642,6 +649,12 @@
}
/** Public because is also used by ViewRootImpl */
+ public void notifyViewInsetsChanged(int sessionId, @NonNull Insets viewInsets) {
+ sendEvent(new ContentCaptureEvent(sessionId, TYPE_VIEW_INSETS_CHANGED)
+ .setInsets(viewInsets));
+ }
+
+ /** Public because is also used by ViewRootImpl */
public void notifyViewTreeEvent(int sessionId, boolean started) {
final int type = started ? TYPE_VIEW_TREE_APPEARING : TYPE_VIEW_TREE_APPEARED;
sendEvent(new ContentCaptureEvent(sessionId, type), FORCE_FLUSH);
diff --git a/core/java/android/view/inline/InlinePresentationSpec.java b/core/java/android/view/inline/InlinePresentationSpec.java
index 3cc04b8..3788e2b 100644
--- a/core/java/android/view/inline/InlinePresentationSpec.java
+++ b/core/java/android/view/inline/InlinePresentationSpec.java
@@ -58,7 +58,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -104,8 +104,8 @@
}
/**
- * The extras encoding the UI style information. Defaults to null in which case the default
- * system UI style will be used.
+ * The extras encoding the UI style information. Defaults to {@code null} in which case the
+ * default system UI style will be used.
*/
@DataClass.Generated.Member
public @Nullable Bundle getStyle() {
@@ -244,11 +244,11 @@
}
/**
- * The extras encoding the UI style information. Defaults to null in which case the default
- * system UI style will be used.
+ * The extras encoding the UI style information. Defaults to {@code null} in which case the
+ * default system UI style will be used.
*/
@DataClass.Generated.Member
- public @NonNull Builder setStyle(@Nullable Bundle value) {
+ public @NonNull Builder setStyle(@NonNull Bundle value) {
checkNotUsed();
mBuilderFieldsSet |= 0x4;
mStyle = value;
@@ -279,8 +279,8 @@
}
@DataClass.Generated(
- time = 1582078731418L,
- codegenVersion = "1.0.14",
+ time = 1584067238741L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/core/java/android/view/inline/InlinePresentationSpec.java",
inputSignatures = "private final @android.annotation.NonNull android.util.Size mMinSize\nprivate final @android.annotation.NonNull android.util.Size mMaxSize\nprivate final @android.annotation.Nullable android.os.Bundle mStyle\nprivate static android.os.Bundle defaultStyle()\nclass InlinePresentationSpec extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genBuilder=true)\nclass BaseBuilder extends java.lang.Object implements []")
@Deprecated
diff --git a/core/java/android/view/inputmethod/InlineSuggestion.java b/core/java/android/view/inputmethod/InlineSuggestion.java
index 6500613..dd1738a 100644
--- a/core/java/android/view/inputmethod/InlineSuggestion.java
+++ b/core/java/android/view/inputmethod/InlineSuggestion.java
@@ -16,6 +16,7 @@
package android.view.inputmethod;
+import android.annotation.BinderThread;
import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -94,19 +95,21 @@
}
-
/**
* Inflates a view with the content of this suggestion at a specific size.
* The size must be between the {@link InlinePresentationSpec#getMinSize() min size}
* and the {@link InlinePresentationSpec#getMaxSize() max size} of the presentation
* spec returned by {@link InlineSuggestionInfo#getPresentationSpec()}.
*
- * @param context Context in which to inflate the view.
- * @param size The size at which to inflate the suggestion.
- * @param callback Callback for receiving the inflated view.
+ * <p> The caller can attach an {@link View.OnClickListener} and/or an
+ * {@link View.OnLongClickListener} to the view in the {@code callback} to receive click and
+ * long click events on the view.
*
+ * @param context Context in which to inflate the view.
+ * @param size The size at which to inflate the suggestion.
+ * @param callback Callback for receiving the inflated view.
* @throws IllegalArgumentException If an invalid argument is passed.
- * @throws IllegalStateException if this method is already called.
+ * @throws IllegalStateException If this method is already called.
*/
public void inflate(@NonNull Context context, @NonNull Size size,
@NonNull @CallbackExecutor Executor callbackExecutor,
@@ -151,12 +154,31 @@
}
@Override
+ @BinderThread
public void onContent(SurfaceControlViewHost.SurfacePackage content) {
final InlineContentCallbackImpl callbackImpl = mCallbackImpl.get();
if (callbackImpl != null) {
callbackImpl.onContent(content);
}
}
+
+ @Override
+ @BinderThread
+ public void onClick() {
+ final InlineContentCallbackImpl callbackImpl = mCallbackImpl.get();
+ if (callbackImpl != null) {
+ callbackImpl.onClick();
+ }
+ }
+
+ @Override
+ @BinderThread
+ public void onLongClick() {
+ final InlineContentCallbackImpl callbackImpl = mCallbackImpl.get();
+ if (callbackImpl != null) {
+ callbackImpl.onLongClick();
+ }
+ }
}
private static final class InlineContentCallbackImpl {
@@ -164,6 +186,7 @@
private final @NonNull Context mContext;
private final @NonNull Executor mCallbackExecutor;
private final @NonNull Consumer<View> mCallback;
+ private @Nullable View mView;
InlineContentCallbackImpl(@NonNull Context context,
@NonNull @CallbackExecutor Executor callbackExecutor,
@@ -173,12 +196,27 @@
mCallback = callback;
}
+ @BinderThread
public void onContent(SurfaceControlViewHost.SurfacePackage content) {
if (content == null) {
mCallbackExecutor.execute(() -> mCallback.accept(/* view */null));
} else {
- mCallbackExecutor.execute(
- () -> mCallback.accept(new InlineContentView(mContext, content)));
+ mView = new InlineContentView(mContext, content);
+ mCallbackExecutor.execute(() -> mCallback.accept(mView));
+ }
+ }
+
+ @BinderThread
+ public void onClick() {
+ if (mView != null && mView.hasOnClickListeners()) {
+ mView.callOnClick();
+ }
+ }
+
+ @BinderThread
+ public void onLongClick() {
+ if (mView != null && mView.hasOnLongClickListeners()) {
+ mView.performLongClick();
}
}
}
@@ -201,7 +239,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -360,8 +398,8 @@
};
@DataClass.Generated(
- time = 1581929285156L,
- codegenVersion = "1.0.14",
+ time = 1583889058241L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/core/java/android/view/inputmethod/InlineSuggestion.java",
inputSignatures = "private static final java.lang.String TAG\nprivate final @android.annotation.NonNull android.view.inputmethod.InlineSuggestionInfo mInfo\nprivate final @android.annotation.Nullable com.android.internal.view.inline.IInlineContentProvider mContentProvider\nprivate @com.android.internal.util.DataClass.ParcelWith(android.view.inputmethod.InlineSuggestion.InlineContentCallbackImplParceling.class) @android.annotation.Nullable android.view.inputmethod.InlineSuggestion.InlineContentCallbackImpl mInlineContentCallback\npublic static @android.annotation.TestApi @android.annotation.NonNull android.view.inputmethod.InlineSuggestion newInlineSuggestion(android.view.inputmethod.InlineSuggestionInfo)\npublic void inflate(android.content.Context,android.util.Size,java.util.concurrent.Executor,java.util.function.Consumer<android.view.View>)\nprivate synchronized android.view.inputmethod.InlineSuggestion.InlineContentCallbackImpl getInlineContentCallback(android.content.Context,java.util.concurrent.Executor,java.util.function.Consumer<android.view.View>)\nclass InlineSuggestion extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genHiddenConstDefs=true, genHiddenConstructor=true)")
@Deprecated
diff --git a/core/java/android/view/inputmethod/InlineSuggestionsRequest.java b/core/java/android/view/inputmethod/InlineSuggestionsRequest.java
index e50da40..2945a86 100644
--- a/core/java/android/view/inputmethod/InlineSuggestionsRequest.java
+++ b/core/java/android/view/inputmethod/InlineSuggestionsRequest.java
@@ -44,15 +44,15 @@
public static final int SUGGESTION_COUNT_UNLIMITED = Integer.MAX_VALUE;
/**
- * Max number of suggestions expected from the response. Defaults to {@code
- * SUGGESTION_COUNT_UNLIMITED} if not set.
+ * Max number of suggestions expected from the response. It must be a positive value.
+ * Defaults to {@code SUGGESTION_COUNT_UNLIMITED} if not set.
*/
private final int mMaxSuggestionCount;
/**
* The {@link InlinePresentationSpec} for each suggestion in the response. If the max suggestion
* count is larger than the number of specs in the list, then the last spec is used for the
- * remainder of the suggestions.
+ * remainder of the suggestions. The list should not be empty.
*/
private final @NonNull List<InlinePresentationSpec> mPresentationSpecs;
@@ -117,6 +117,7 @@
}
private void onConstructed() {
+ Preconditions.checkState(!mPresentationSpecs.isEmpty());
Preconditions.checkState(mMaxSuggestionCount >= mPresentationSpecs.size());
}
@@ -162,7 +163,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -202,8 +203,8 @@
}
/**
- * Max number of suggestions expected from the response. Defaults to {@code
- * SUGGESTION_COUNT_UNLIMITED} if not set.
+ * Max number of suggestions expected from the response. It must be a positive value.
+ * Defaults to {@code SUGGESTION_COUNT_UNLIMITED} if not set.
*/
@DataClass.Generated.Member
public int getMaxSuggestionCount() {
@@ -213,7 +214,7 @@
/**
* The {@link InlinePresentationSpec} for each suggestion in the response. If the max suggestion
* count is larger than the number of specs in the list, then the last spec is used for the
- * remainder of the suggestions.
+ * remainder of the suggestions. The list should not be empty.
*/
@DataClass.Generated.Member
public @NonNull List<InlinePresentationSpec> getPresentationSpecs() {
@@ -419,7 +420,7 @@
* @param presentationSpecs
* The {@link InlinePresentationSpec} for each suggestion in the response. If the max suggestion
* count is larger than the number of specs in the list, then the last spec is used for the
- * remainder of the suggestions.
+ * remainder of the suggestions. The list should not be empty.
*/
public Builder(
@NonNull List<InlinePresentationSpec> presentationSpecs) {
@@ -429,8 +430,8 @@
}
/**
- * Max number of suggestions expected from the response. Defaults to {@code
- * SUGGESTION_COUNT_UNLIMITED} if not set.
+ * Max number of suggestions expected from the response. It must be a positive value.
+ * Defaults to {@code SUGGESTION_COUNT_UNLIMITED} if not set.
*/
@DataClass.Generated.Member
public @NonNull Builder setMaxSuggestionCount(int value) {
@@ -443,7 +444,7 @@
/**
* The {@link InlinePresentationSpec} for each suggestion in the response. If the max suggestion
* count is larger than the number of specs in the list, then the last spec is used for the
- * remainder of the suggestions.
+ * remainder of the suggestions. The list should not be empty.
*/
@DataClass.Generated.Member
@Override
@@ -495,7 +496,7 @@
* The extras state propagated from the IME to pass extra data.
*/
@DataClass.Generated.Member
- public @NonNull Builder setExtras(@Nullable Bundle value) {
+ public @NonNull Builder setExtras(@NonNull Bundle value) {
checkNotUsed();
mBuilderFieldsSet |= 0x10;
mExtras = value;
@@ -510,7 +511,7 @@
*/
@DataClass.Generated.Member
@Override
- @NonNull Builder setHostInputToken(@Nullable IBinder value) {
+ @NonNull Builder setHostInputToken(@NonNull IBinder value) {
checkNotUsed();
mBuilderFieldsSet |= 0x20;
mHostInputToken = value;
@@ -575,8 +576,8 @@
}
@DataClass.Generated(
- time = 1582339908980L,
- codegenVersion = "1.0.14",
+ time = 1584067152935L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/core/java/android/view/inputmethod/InlineSuggestionsRequest.java",
inputSignatures = "public static final int SUGGESTION_COUNT_UNLIMITED\nprivate final int mMaxSuggestionCount\nprivate final @android.annotation.NonNull java.util.List<android.view.inline.InlinePresentationSpec> mPresentationSpecs\nprivate @android.annotation.NonNull java.lang.String mHostPackageName\nprivate @android.annotation.NonNull android.os.LocaleList mSupportedLocales\nprivate @android.annotation.Nullable android.os.Bundle mExtras\nprivate @android.annotation.Nullable android.os.IBinder mHostInputToken\nprivate int mHostDisplayId\npublic void setHostInputToken(android.os.IBinder)\nprivate void parcelHostInputToken(android.os.Parcel,int)\nprivate @android.annotation.Nullable android.os.IBinder unparcelHostInputToken(android.os.Parcel)\npublic void setHostDisplayId(int)\nprivate void onConstructed()\nprivate static int defaultMaxSuggestionCount()\nprivate static java.lang.String defaultHostPackageName()\nprivate static android.os.LocaleList defaultSupportedLocales()\nprivate static @android.annotation.Nullable android.os.IBinder defaultHostInputToken()\nprivate static @android.annotation.Nullable int defaultHostDisplayId()\nprivate static @android.annotation.Nullable android.os.Bundle defaultExtras()\nclass InlineSuggestionsRequest extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true, genToString=true, genBuilder=true)\nabstract android.view.inputmethod.InlineSuggestionsRequest.Builder setPresentationSpecs(java.util.List<android.view.inline.InlinePresentationSpec>)\nabstract android.view.inputmethod.InlineSuggestionsRequest.Builder setHostPackageName(java.lang.String)\nabstract android.view.inputmethod.InlineSuggestionsRequest.Builder setHostInputToken(android.os.IBinder)\nabstract android.view.inputmethod.InlineSuggestionsRequest.Builder setHostDisplayId(int)\nclass BaseBuilder extends java.lang.Object implements []")
@Deprecated
diff --git a/core/java/android/view/textclassifier/ActionsModelParamsSupplier.java b/core/java/android/view/textclassifier/ActionsModelParamsSupplier.java
deleted file mode 100644
index 3164567..0000000
--- a/core/java/android/view/textclassifier/ActionsModelParamsSupplier.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier;
-
-import android.annotation.Nullable;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.database.ContentObserver;
-import android.provider.Settings;
-import android.text.TextUtils;
-import android.util.Base64;
-import android.util.KeyValueListParser;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
-
-import java.lang.ref.WeakReference;
-import java.util.Objects;
-import java.util.function.Supplier;
-
-/**
- * Parses the {@link Settings.Global#TEXT_CLASSIFIER_ACTION_MODEL_PARAMS} flag.
- *
- * @hide
- */
-public final class ActionsModelParamsSupplier implements
- Supplier<ActionsModelParamsSupplier.ActionsModelParams> {
- private static final String TAG = TextClassifier.DEFAULT_LOG_TAG;
-
- @VisibleForTesting
- static final String KEY_REQUIRED_MODEL_VERSION = "required_model_version";
- @VisibleForTesting
- static final String KEY_REQUIRED_LOCALES = "required_locales";
- @VisibleForTesting
- static final String KEY_SERIALIZED_PRECONDITIONS = "serialized_preconditions";
-
- private final Context mAppContext;
- private final SettingsObserver mSettingsObserver;
-
- private final Object mLock = new Object();
- private final Runnable mOnChangedListener;
- @Nullable
- @GuardedBy("mLock")
- private ActionsModelParams mActionsModelParams;
- @GuardedBy("mLock")
- private boolean mParsed = true;
-
- public ActionsModelParamsSupplier(Context context, @Nullable Runnable onChangedListener) {
- final Context appContext = Preconditions.checkNotNull(context).getApplicationContext();
- // Some contexts don't have an app context.
- mAppContext = appContext != null ? appContext : context;
- mOnChangedListener = onChangedListener == null ? () -> {} : onChangedListener;
- mSettingsObserver = new SettingsObserver(mAppContext, () -> {
- synchronized (mLock) {
- Log.v(TAG, "Settings.Global.TEXT_CLASSIFIER_ACTION_MODEL_PARAMS is updated");
- mParsed = true;
- mOnChangedListener.run();
- }
- });
- }
-
- /**
- * Returns the parsed actions params or {@link ActionsModelParams#INVALID} if the value is
- * invalid.
- */
- @Override
- public ActionsModelParams get() {
- synchronized (mLock) {
- if (mParsed) {
- mActionsModelParams = parse(mAppContext.getContentResolver());
- mParsed = false;
- }
- }
- return mActionsModelParams;
- }
-
- private ActionsModelParams parse(ContentResolver contentResolver) {
- String settingStr = Settings.Global.getString(contentResolver,
- Settings.Global.TEXT_CLASSIFIER_ACTION_MODEL_PARAMS);
- if (TextUtils.isEmpty(settingStr)) {
- return ActionsModelParams.INVALID;
- }
- try {
- KeyValueListParser keyValueListParser = new KeyValueListParser(',');
- keyValueListParser.setString(settingStr);
- int version = keyValueListParser.getInt(KEY_REQUIRED_MODEL_VERSION, -1);
- if (version == -1) {
- Log.w(TAG, "ActionsModelParams.Parse, invalid model version");
- return ActionsModelParams.INVALID;
- }
- String locales = keyValueListParser.getString(KEY_REQUIRED_LOCALES, null);
- if (locales == null) {
- Log.w(TAG, "ActionsModelParams.Parse, invalid locales");
- return ActionsModelParams.INVALID;
- }
- String serializedPreconditionsStr =
- keyValueListParser.getString(KEY_SERIALIZED_PRECONDITIONS, null);
- if (serializedPreconditionsStr == null) {
- Log.w(TAG, "ActionsModelParams.Parse, invalid preconditions");
- return ActionsModelParams.INVALID;
- }
- byte[] serializedPreconditions =
- Base64.decode(serializedPreconditionsStr, Base64.NO_WRAP);
- return new ActionsModelParams(version, locales, serializedPreconditions);
- } catch (Throwable t) {
- Log.e(TAG, "Invalid TEXT_CLASSIFIER_ACTION_MODEL_PARAMS, ignore", t);
- }
- return ActionsModelParams.INVALID;
- }
-
- @Override
- protected void finalize() throws Throwable {
- try {
- mAppContext.getContentResolver().unregisterContentObserver(mSettingsObserver);
- } finally {
- super.finalize();
- }
- }
-
- /**
- * Represents the parsed result.
- */
- public static final class ActionsModelParams {
-
- public static final ActionsModelParams INVALID =
- new ActionsModelParams(-1, "", new byte[0]);
-
- /**
- * The required model version to apply {@code mSerializedPreconditions}.
- */
- private final int mRequiredModelVersion;
-
- /**
- * The required model locales to apply {@code mSerializedPreconditions}.
- */
- private final String mRequiredModelLocales;
-
- /**
- * The serialized params that will be applied to the model file, if all requirements are
- * met. Do not modify.
- */
- private final byte[] mSerializedPreconditions;
-
- public ActionsModelParams(int requiredModelVersion, String requiredModelLocales,
- byte[] serializedPreconditions) {
- mRequiredModelVersion = requiredModelVersion;
- mRequiredModelLocales = Preconditions.checkNotNull(requiredModelLocales);
- mSerializedPreconditions = Preconditions.checkNotNull(serializedPreconditions);
- }
-
- /**
- * Returns the serialized preconditions. Returns {@code null} if the the model in use does
- * not meet all the requirements listed in the {@code ActionsModelParams} or the params
- * are invalid.
- */
- @Nullable
- public byte[] getSerializedPreconditions(ModelFileManager.ModelFile modelInUse) {
- if (this == INVALID) {
- return null;
- }
- if (modelInUse.getVersion() != mRequiredModelVersion) {
- Log.w(TAG, String.format(
- "Not applying mSerializedPreconditions, required version=%d, actual=%d",
- mRequiredModelVersion, modelInUse.getVersion()));
- return null;
- }
- if (!Objects.equals(modelInUse.getSupportedLocalesStr(), mRequiredModelLocales)) {
- Log.w(TAG, String.format(
- "Not applying mSerializedPreconditions, required locales=%s, actual=%s",
- mRequiredModelLocales, modelInUse.getSupportedLocalesStr()));
- return null;
- }
- return mSerializedPreconditions;
- }
- }
-
- private static final class SettingsObserver extends ContentObserver {
-
- private final WeakReference<Runnable> mOnChangedListener;
-
- SettingsObserver(Context appContext, Runnable listener) {
- super(null);
- mOnChangedListener = new WeakReference<>(listener);
- appContext.getContentResolver().registerContentObserver(
- Settings.Global.getUriFor(Settings.Global.TEXT_CLASSIFIER_ACTION_MODEL_PARAMS),
- false /* notifyForDescendants */,
- this);
- }
-
- public void onChange(boolean selfChange) {
- if (mOnChangedListener.get() != null) {
- mOnChangedListener.get().run();
- }
- }
- }
-}
diff --git a/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java b/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java
deleted file mode 100644
index 3ed48f6..0000000
--- a/core/java/android/view/textclassifier/ActionsSuggestionsHelper.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier;
-
-import android.annotation.Nullable;
-import android.app.Person;
-import android.app.RemoteAction;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.text.TextUtils;
-import android.util.ArrayMap;
-import android.util.Pair;
-import android.view.textclassifier.intent.LabeledIntent;
-import android.view.textclassifier.intent.TemplateIntentFactory;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import com.google.android.textclassifier.ActionsSuggestionsModel;
-import com.google.android.textclassifier.RemoteActionTemplate;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-import java.util.StringJoiner;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-/**
- * Helper class for action suggestions.
- *
- * @hide
- */
-@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-public final class ActionsSuggestionsHelper {
- private static final String TAG = "ActionsSuggestions";
- private static final int USER_LOCAL = 0;
- private static final int FIRST_NON_LOCAL_USER = 1;
-
- private ActionsSuggestionsHelper() {}
-
- /**
- * Converts the messages to a list of native messages object that the model can understand.
- * <p>
- * User id encoding - local user is represented as 0, Other users are numbered according to
- * how far before they spoke last time in the conversation. For example, considering this
- * conversation:
- * <ul>
- * <li> User A: xxx
- * <li> Local user: yyy
- * <li> User B: zzz
- * </ul>
- * User A will be encoded as 2, user B will be encoded as 1 and local user will be encoded as 0.
- */
- public static ActionsSuggestionsModel.ConversationMessage[] toNativeMessages(
- List<ConversationActions.Message> messages,
- Function<CharSequence, String> languageDetector) {
- List<ConversationActions.Message> messagesWithText =
- messages.stream()
- .filter(message -> !TextUtils.isEmpty(message.getText()))
- .collect(Collectors.toCollection(ArrayList::new));
- if (messagesWithText.isEmpty()) {
- return new ActionsSuggestionsModel.ConversationMessage[0];
- }
- Deque<ActionsSuggestionsModel.ConversationMessage> nativeMessages = new ArrayDeque<>();
- PersonEncoder personEncoder = new PersonEncoder();
- int size = messagesWithText.size();
- for (int i = size - 1; i >= 0; i--) {
- ConversationActions.Message message = messagesWithText.get(i);
- long referenceTime = message.getReferenceTime() == null
- ? 0
- : message.getReferenceTime().toInstant().toEpochMilli();
- String timeZone = message.getReferenceTime() == null
- ? null
- : message.getReferenceTime().getZone().getId();
- nativeMessages.push(new ActionsSuggestionsModel.ConversationMessage(
- personEncoder.encode(message.getAuthor()),
- message.getText().toString(), referenceTime, timeZone,
- languageDetector.apply(message.getText())));
- }
- return nativeMessages.toArray(
- new ActionsSuggestionsModel.ConversationMessage[nativeMessages.size()]);
- }
-
- /**
- * Returns the result id for logging.
- */
- public static String createResultId(
- Context context,
- List<ConversationActions.Message> messages,
- int modelVersion,
- List<Locale> modelLocales) {
- final StringJoiner localesJoiner = new StringJoiner(",");
- for (Locale locale : modelLocales) {
- localesJoiner.add(locale.toLanguageTag());
- }
- final String modelName = String.format(
- Locale.US, "%s_v%d", localesJoiner.toString(), modelVersion);
- final int hash = Objects.hash(
- messages.stream().mapToInt(ActionsSuggestionsHelper::hashMessage),
- context.getPackageName(),
- System.currentTimeMillis());
- return SelectionSessionLogger.SignatureParser.createSignature(
- SelectionSessionLogger.CLASSIFIER_ID, modelName, hash);
- }
-
- /**
- * Generated labeled intent from an action suggestion and return the resolved result.
- */
- @Nullable
- public static LabeledIntent.Result createLabeledIntentResult(
- Context context,
- TemplateIntentFactory templateIntentFactory,
- ActionsSuggestionsModel.ActionSuggestion nativeSuggestion) {
- RemoteActionTemplate[] remoteActionTemplates =
- nativeSuggestion.getRemoteActionTemplates();
- if (remoteActionTemplates == null) {
- Log.w(TAG, "createRemoteAction: Missing template for type "
- + nativeSuggestion.getActionType());
- return null;
- }
- List<LabeledIntent> labeledIntents = templateIntentFactory.create(remoteActionTemplates);
- if (labeledIntents.isEmpty()) {
- return null;
- }
- // Given that we only support implicit intent here, we should expect there is just one
- // intent for each action type.
- LabeledIntent.TitleChooser titleChooser =
- ActionsSuggestionsHelper.createTitleChooser(nativeSuggestion.getActionType());
- return labeledIntents.get(0).resolve(context, titleChooser, null);
- }
-
- /**
- * Returns a {@link LabeledIntent.TitleChooser} for conversation actions use case.
- */
- @Nullable
- public static LabeledIntent.TitleChooser createTitleChooser(String actionType) {
- if (ConversationAction.TYPE_OPEN_URL.equals(actionType)) {
- return (labeledIntent, resolveInfo) -> {
- if (resolveInfo.handleAllWebDataURI) {
- return labeledIntent.titleWithEntity;
- }
- if ("android".equals(resolveInfo.activityInfo.packageName)) {
- return labeledIntent.titleWithEntity;
- }
- return labeledIntent.titleWithoutEntity;
- };
- }
- return null;
- }
-
- /**
- * Returns a list of {@link ConversationAction}s that have 0 duplicates. Two actions are
- * duplicates if they may look the same to users. This function assumes every
- * ConversationActions with a non-null RemoteAction also have a non-null intent in the extras.
- */
- public static List<ConversationAction> removeActionsWithDuplicates(
- List<ConversationAction> conversationActions) {
- // Ideally, we should compare title and icon here, but comparing icon is expensive and thus
- // we use the component name of the target handler as the heuristic.
- Map<Pair<String, String>, Integer> counter = new ArrayMap<>();
- for (ConversationAction conversationAction : conversationActions) {
- Pair<String, String> representation = getRepresentation(conversationAction);
- if (representation == null) {
- continue;
- }
- Integer existingCount = counter.getOrDefault(representation, 0);
- counter.put(representation, existingCount + 1);
- }
- List<ConversationAction> result = new ArrayList<>();
- for (ConversationAction conversationAction : conversationActions) {
- Pair<String, String> representation = getRepresentation(conversationAction);
- if (representation == null || counter.getOrDefault(representation, 0) == 1) {
- result.add(conversationAction);
- }
- }
- return result;
- }
-
- @Nullable
- private static Pair<String, String> getRepresentation(
- ConversationAction conversationAction) {
- RemoteAction remoteAction = conversationAction.getAction();
- if (remoteAction == null) {
- return null;
- }
- Intent actionIntent = ExtrasUtils.getActionIntent(conversationAction.getExtras());
- ComponentName componentName = actionIntent.getComponent();
- // Action without a component name will be considered as from the same app.
- String packageName = componentName == null ? null : componentName.getPackageName();
- return new Pair<>(
- conversationAction.getAction().getTitle().toString(), packageName);
- }
-
- private static final class PersonEncoder {
- private final Map<Person, Integer> mMapping = new ArrayMap<>();
- private int mNextUserId = FIRST_NON_LOCAL_USER;
-
- private int encode(Person person) {
- if (ConversationActions.Message.PERSON_USER_SELF.equals(person)) {
- return USER_LOCAL;
- }
- Integer result = mMapping.get(person);
- if (result == null) {
- mMapping.put(person, mNextUserId);
- result = mNextUserId;
- mNextUserId++;
- }
- return result;
- }
- }
-
- private static int hashMessage(ConversationActions.Message message) {
- return Objects.hash(message.getAuthor(), message.getText(), message.getReferenceTime());
- }
-}
diff --git a/core/java/android/view/textclassifier/ConversationActions.java b/core/java/android/view/textclassifier/ConversationActions.java
index 6246b50..842ba29 100644
--- a/core/java/android/view/textclassifier/ConversationActions.java
+++ b/core/java/android/view/textclassifier/ConversationActions.java
@@ -21,15 +21,12 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringDef;
-import android.annotation.UserIdInt;
import android.app.Person;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.text.SpannedString;
-import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
import java.lang.annotation.Retention;
@@ -317,13 +314,9 @@
@NonNull
@Hint
private final List<String> mHints;
- @Nullable
- private String mCallingPackageName;
- @UserIdInt
- private int mUserId = UserHandle.USER_NULL;
@NonNull
private Bundle mExtras;
- private boolean mUseDefaultTextClassifier;
+ @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
private Request(
@NonNull List<Message> conversation,
@@ -345,10 +338,8 @@
int maxSuggestions = in.readInt();
List<String> hints = new ArrayList<>();
in.readStringList(hints);
- String callingPackageName = in.readString();
- int userId = in.readInt();
Bundle extras = in.readBundle();
- boolean useDefaultTextClassifier = in.readBoolean();
+ SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
Request request = new Request(
conversation,
@@ -356,9 +347,7 @@
maxSuggestions,
hints,
extras);
- request.setCallingPackageName(callingPackageName);
- request.setUserId(userId);
- request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+ request.setSystemTextClassifierMetadata(systemTcMetadata);
return request;
}
@@ -368,10 +357,8 @@
parcel.writeParcelable(mTypeConfig, flags);
parcel.writeInt(mMaxSuggestions);
parcel.writeStringList(mHints);
- parcel.writeString(mCallingPackageName);
- parcel.writeInt(mUserId);
parcel.writeBundle(mExtras);
- parcel.writeBoolean(mUseDefaultTextClassifier);
+ parcel.writeParcelable(mSystemTcMetadata, flags);
}
@Override
@@ -421,62 +408,31 @@
}
/**
- * Sets the name of the package that is sending this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
- public void setCallingPackageName(@Nullable String callingPackageName) {
- mCallingPackageName = callingPackageName;
- }
-
- /**
* Returns the name of the package that sent this request.
* This returns {@code null} if no calling package name is set.
*/
@Nullable
public String getCallingPackageName() {
- return mCallingPackageName;
+ return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
}
/**
- * Sets the id of the user that sent this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
- }
-
- /**
- * Returns the id of the user that sent this request.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
+ void setSystemTextClassifierMetadata(@Nullable SystemTextClassifierMetadata systemTcData) {
+ mSystemTcMetadata = systemTcData;
}
/**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
diff --git a/core/java/android/view/textclassifier/ExtrasUtils.java b/core/java/android/view/textclassifier/ExtrasUtils.java
index 11e0e2c..9e2b642 100644
--- a/core/java/android/view/textclassifier/ExtrasUtils.java
+++ b/core/java/android/view/textclassifier/ExtrasUtils.java
@@ -19,15 +19,9 @@
import android.annotation.Nullable;
import android.app.RemoteAction;
import android.content.Intent;
-import android.icu.util.ULocale;
import android.os.Bundle;
-import com.android.internal.util.ArrayUtils;
-
-import com.google.android.textclassifier.AnnotatorModel;
-
import java.util.ArrayList;
-import java.util.List;
/**
* Utility class for inserting and retrieving data in TextClassifier request/response extras.
@@ -37,52 +31,19 @@
public final class ExtrasUtils {
// Keys for response objects.
- private static final String SERIALIZED_ENTITIES_DATA = "serialized-entities-data";
- private static final String ENTITIES_EXTRAS = "entities-extras";
private static final String ACTION_INTENT = "action-intent";
private static final String ACTIONS_INTENTS = "actions-intents";
private static final String FOREIGN_LANGUAGE = "foreign-language";
private static final String ENTITY_TYPE = "entity-type";
private static final String SCORE = "score";
- private static final String MODEL_VERSION = "model-version";
private static final String MODEL_NAME = "model-name";
- private static final String TEXT_LANGUAGES = "text-languages";
- private static final String ENTITIES = "entities";
- // Keys for request objects.
- private static final String IS_SERIALIZED_ENTITY_DATA_ENABLED =
- "is-serialized-entity-data-enabled";
-
- private ExtrasUtils() {}
-
- /**
- * Bundles and returns foreign language detection information for TextClassifier responses.
- */
- static Bundle createForeignLanguageExtra(
- String language, float score, int modelVersion) {
- final Bundle bundle = new Bundle();
- bundle.putString(ENTITY_TYPE, language);
- bundle.putFloat(SCORE, score);
- bundle.putInt(MODEL_VERSION, modelVersion);
- bundle.putString(MODEL_NAME, "langId_v" + modelVersion);
- return bundle;
- }
-
- /**
- * Stores {@code extra} as foreign language information in TextClassifier response object's
- * extras {@code container}.
- *
- * @see #getForeignLanguageExtra(TextClassification)
- */
- static void putForeignLanguageExtra(Bundle container, Bundle extra) {
- container.putParcelable(FOREIGN_LANGUAGE, extra);
+ private ExtrasUtils() {
}
/**
* Returns foreign language detection information contained in the TextClassification object.
* responses.
- *
- * @see #putForeignLanguageExtra(Bundle, Bundle)
*/
@Nullable
public static Bundle getForeignLanguageExtra(@Nullable TextClassification classification) {
@@ -93,72 +54,6 @@
}
/**
- * @see #getTopLanguage(Intent)
- */
- static void putTopLanguageScores(Bundle container, EntityConfidence languageScores) {
- final int maxSize = Math.min(3, languageScores.getEntities().size());
- final String[] languages = languageScores.getEntities().subList(0, maxSize)
- .toArray(new String[0]);
- final float[] scores = new float[languages.length];
- for (int i = 0; i < languages.length; i++) {
- scores[i] = languageScores.getConfidenceScore(languages[i]);
- }
- container.putStringArray(ENTITY_TYPE, languages);
- container.putFloatArray(SCORE, scores);
- }
-
- /**
- * @see #putTopLanguageScores(Bundle, EntityConfidence)
- */
- @Nullable
- public static ULocale getTopLanguage(@Nullable Intent intent) {
- if (intent == null) {
- return null;
- }
- final Bundle tcBundle = intent.getBundleExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER);
- if (tcBundle == null) {
- return null;
- }
- final Bundle textLanguagesExtra = tcBundle.getBundle(TEXT_LANGUAGES);
- if (textLanguagesExtra == null) {
- return null;
- }
- final String[] languages = textLanguagesExtra.getStringArray(ENTITY_TYPE);
- final float[] scores = textLanguagesExtra.getFloatArray(SCORE);
- if (languages == null || scores == null
- || languages.length == 0 || languages.length != scores.length) {
- return null;
- }
- int highestScoringIndex = 0;
- for (int i = 1; i < languages.length; i++) {
- if (scores[highestScoringIndex] < scores[i]) {
- highestScoringIndex = i;
- }
- }
- return ULocale.forLanguageTag(languages[highestScoringIndex]);
- }
-
- public static void putTextLanguagesExtra(Bundle container, Bundle extra) {
- container.putBundle(TEXT_LANGUAGES, extra);
- }
-
- /**
- * Stores {@code actionIntents} information in TextClassifier response object's extras
- * {@code container}.
- */
- static void putActionsIntents(Bundle container, ArrayList<Intent> actionsIntents) {
- container.putParcelableArrayList(ACTIONS_INTENTS, actionsIntents);
- }
-
- /**
- * Stores {@code actionIntents} information in TextClassifier response object's extras
- * {@code container}.
- */
- public static void putActionIntent(Bundle container, @Nullable Intent actionIntent) {
- container.putParcelable(ACTION_INTENT, actionIntent);
- }
-
- /**
* Returns {@code actionIntent} information contained in a TextClassifier response object.
*/
@Nullable
@@ -167,48 +62,6 @@
}
/**
- * Stores serialized entity data information in TextClassifier response object's extras
- * {@code container}.
- */
- public static void putSerializedEntityData(
- Bundle container, @Nullable byte[] serializedEntityData) {
- container.putByteArray(SERIALIZED_ENTITIES_DATA, serializedEntityData);
- }
-
- /**
- * Returns serialized entity data information contained in a TextClassifier response
- * object.
- */
- @Nullable
- public static byte[] getSerializedEntityData(Bundle container) {
- return container.getByteArray(SERIALIZED_ENTITIES_DATA);
- }
-
- /**
- * Stores {@code entities} information in TextClassifier response object's extras
- * {@code container}.
- *
- * @see {@link #getCopyText(Bundle)}
- */
- public static void putEntitiesExtras(Bundle container, @Nullable Bundle entitiesExtras) {
- container.putParcelable(ENTITIES_EXTRAS, entitiesExtras);
- }
-
- /**
- * Returns {@code entities} information contained in a TextClassifier response object.
- *
- * @see {@link #putEntitiesExtras(Bundle, Bundle)}
- */
- @Nullable
- public static String getCopyText(Bundle container) {
- Bundle entitiesExtras = container.getParcelable(ENTITIES_EXTRAS);
- if (entitiesExtras == null) {
- return null;
- }
- return entitiesExtras.getString("text");
- }
-
- /**
* Returns {@code actionIntents} information contained in the TextClassification object.
*/
@Nullable
@@ -224,7 +77,7 @@
* action string, {@code intentAction}.
*/
@Nullable
- public static RemoteAction findAction(
+ private static RemoteAction findAction(
@Nullable TextClassification classification, @Nullable String intentAction) {
if (classification == null || intentAction == null) {
return null;
@@ -283,53 +136,4 @@
}
return extra.getString(MODEL_NAME);
}
-
- /**
- * Stores the entities from {@link AnnotatorModel.ClassificationResult} in {@code container}.
- */
- public static void putEntities(
- Bundle container,
- @Nullable AnnotatorModel.ClassificationResult[] classifications) {
- if (ArrayUtils.isEmpty(classifications)) {
- return;
- }
- ArrayList<Bundle> entitiesBundle = new ArrayList<>();
- for (AnnotatorModel.ClassificationResult classification : classifications) {
- if (classification == null) {
- continue;
- }
- Bundle entityBundle = new Bundle();
- entityBundle.putString(ENTITY_TYPE, classification.getCollection());
- entityBundle.putByteArray(
- SERIALIZED_ENTITIES_DATA,
- classification.getSerializedEntityData());
- entitiesBundle.add(entityBundle);
- }
- if (!entitiesBundle.isEmpty()) {
- container.putParcelableArrayList(ENTITIES, entitiesBundle);
- }
- }
-
- /**
- * Returns a list of entities contained in the {@code extra}.
- */
- @Nullable
- public static List<Bundle> getEntities(Bundle container) {
- return container.getParcelableArrayList(ENTITIES);
- }
-
- /**
- * Whether the annotator should populate serialized entity data into the result object.
- */
- public static boolean isSerializedEntityDataEnabled(TextLinks.Request request) {
- return request.getExtras().getBoolean(IS_SERIALIZED_ENTITY_DATA_ENABLED);
- }
-
- /**
- * To indicate whether the annotator should populate serialized entity data in the result
- * object.
- */
- public static void putIsSerializedEntityDataEnabled(Bundle bundle, boolean isEnabled) {
- bundle.putBoolean(IS_SERIALIZED_ENTITY_DATA_ENABLED, isEnabled);
- }
-}
+}
\ No newline at end of file
diff --git a/core/java/android/view/textclassifier/GenerateLinksLogger.java b/core/java/android/view/textclassifier/GenerateLinksLogger.java
deleted file mode 100644
index 17ec73a..0000000
--- a/core/java/android/view/textclassifier/GenerateLinksLogger.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2017 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.view.textclassifier;
-
-import android.annotation.Nullable;
-import android.metrics.LogMaker;
-import android.util.ArrayMap;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Random;
-import java.util.UUID;
-
-/**
- * A helper for logging calls to generateLinks.
- * @hide
- */
-@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-public final class GenerateLinksLogger {
-
- private static final String LOG_TAG = "GenerateLinksLogger";
- private static final String ZERO = "0";
-
- private final MetricsLogger mMetricsLogger;
- private final Random mRng;
- private final int mSampleRate;
-
- /**
- * @param sampleRate the rate at which log events are written. (e.g. 100 means there is a 0.01
- * chance that a call to logGenerateLinks results in an event being written).
- * To write all events, pass 1.
- */
- public GenerateLinksLogger(int sampleRate) {
- mSampleRate = sampleRate;
- mRng = new Random(System.nanoTime());
- mMetricsLogger = new MetricsLogger();
- }
-
- @VisibleForTesting
- public GenerateLinksLogger(int sampleRate, MetricsLogger metricsLogger) {
- mSampleRate = sampleRate;
- mRng = new Random(System.nanoTime());
- mMetricsLogger = metricsLogger;
- }
-
- /** Logs statistics about a call to generateLinks. */
- public void logGenerateLinks(CharSequence text, TextLinks links, String callingPackageName,
- long latencyMs) {
- Objects.requireNonNull(text);
- Objects.requireNonNull(links);
- Objects.requireNonNull(callingPackageName);
- if (!shouldLog()) {
- return;
- }
-
- // Always populate the total stats, and per-entity stats for each entity type detected.
- final LinkifyStats totalStats = new LinkifyStats();
- final Map<String, LinkifyStats> perEntityTypeStats = new ArrayMap<>();
- for (TextLinks.TextLink link : links.getLinks()) {
- if (link.getEntityCount() == 0) continue;
- final String entityType = link.getEntity(0);
- if (entityType == null
- || TextClassifier.TYPE_OTHER.equals(entityType)
- || TextClassifier.TYPE_UNKNOWN.equals(entityType)) {
- continue;
- }
- totalStats.countLink(link);
- perEntityTypeStats.computeIfAbsent(entityType, k -> new LinkifyStats()).countLink(link);
- }
-
- final String callId = UUID.randomUUID().toString();
- writeStats(callId, callingPackageName, null, totalStats, text, latencyMs);
- for (Map.Entry<String, LinkifyStats> entry : perEntityTypeStats.entrySet()) {
- writeStats(callId, callingPackageName, entry.getKey(), entry.getValue(), text,
- latencyMs);
- }
- }
-
- /**
- * Returns whether this particular event should be logged.
- *
- * Sampling is used to reduce the amount of logging data generated.
- **/
- private boolean shouldLog() {
- if (mSampleRate <= 1) {
- return true;
- } else {
- return mRng.nextInt(mSampleRate) == 0;
- }
- }
-
- /** Writes a log event for the given stats. */
- private void writeStats(String callId, String callingPackageName, @Nullable String entityType,
- LinkifyStats stats, CharSequence text, long latencyMs) {
- final LogMaker log = new LogMaker(MetricsEvent.TEXT_CLASSIFIER_GENERATE_LINKS)
- .setPackageName(callingPackageName)
- .addTaggedData(MetricsEvent.FIELD_LINKIFY_CALL_ID, callId)
- .addTaggedData(MetricsEvent.FIELD_LINKIFY_NUM_LINKS, stats.mNumLinks)
- .addTaggedData(MetricsEvent.FIELD_LINKIFY_LINK_LENGTH, stats.mNumLinksTextLength)
- .addTaggedData(MetricsEvent.FIELD_LINKIFY_TEXT_LENGTH, text.length())
- .addTaggedData(MetricsEvent.FIELD_LINKIFY_LATENCY, latencyMs);
- if (entityType != null) {
- log.addTaggedData(MetricsEvent.FIELD_LINKIFY_ENTITY_TYPE, entityType);
- }
- mMetricsLogger.write(log);
- debugLog(log);
- }
-
- private static void debugLog(LogMaker log) {
- if (!Log.ENABLE_FULL_LOGGING) {
- return;
- }
- final String callId = Objects.toString(
- log.getTaggedData(MetricsEvent.FIELD_LINKIFY_CALL_ID), "");
- final String entityType = Objects.toString(
- log.getTaggedData(MetricsEvent.FIELD_LINKIFY_ENTITY_TYPE), "ANY_ENTITY");
- final int numLinks = Integer.parseInt(
- Objects.toString(log.getTaggedData(MetricsEvent.FIELD_LINKIFY_NUM_LINKS), ZERO));
- final int linkLength = Integer.parseInt(
- Objects.toString(log.getTaggedData(MetricsEvent.FIELD_LINKIFY_LINK_LENGTH), ZERO));
- final int textLength = Integer.parseInt(
- Objects.toString(log.getTaggedData(MetricsEvent.FIELD_LINKIFY_TEXT_LENGTH), ZERO));
- final int latencyMs = Integer.parseInt(
- Objects.toString(log.getTaggedData(MetricsEvent.FIELD_LINKIFY_LATENCY), ZERO));
-
- Log.v(LOG_TAG,
- String.format(Locale.US, "%s:%s %d links (%d/%d chars) %dms %s", callId, entityType,
- numLinks, linkLength, textLength, latencyMs, log.getPackageName()));
- }
-
- /** Helper class for storing per-entity type statistics. */
- private static final class LinkifyStats {
- int mNumLinks;
- int mNumLinksTextLength;
-
- void countLink(TextLinks.TextLink link) {
- mNumLinks += 1;
- mNumLinksTextLength += link.getEnd() - link.getStart();
- }
- }
-}
diff --git a/core/java/android/view/textclassifier/Log.java b/core/java/android/view/textclassifier/Log.java
index 03ed496..98ee09c 100644
--- a/core/java/android/view/textclassifier/Log.java
+++ b/core/java/android/view/textclassifier/Log.java
@@ -32,7 +32,7 @@
* false: Limits logging to debug level.
*/
static final boolean ENABLE_FULL_LOGGING =
- android.util.Log.isLoggable(TextClassifier.DEFAULT_LOG_TAG, android.util.Log.VERBOSE);
+ android.util.Log.isLoggable(TextClassifier.LOG_TAG, android.util.Log.VERBOSE);
private Log() {
}
diff --git a/core/java/android/view/textclassifier/ModelFileManager.java b/core/java/android/view/textclassifier/ModelFileManager.java
deleted file mode 100644
index 0a4ff5d..0000000
--- a/core/java/android/view/textclassifier/ModelFileManager.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier;
-
-import static android.view.textclassifier.TextClassifier.DEFAULT_LOG_TAG;
-
-import android.annotation.Nullable;
-import android.os.LocaleList;
-import android.os.ParcelFileDescriptor;
-import android.text.TextUtils;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.Objects;
-import java.util.StringJoiner;
-import java.util.function.Function;
-import java.util.function.Supplier;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Manages model files that are listed by the model files supplier.
- * @hide
- */
-@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-public final class ModelFileManager {
- private final Object mLock = new Object();
- private final Supplier<List<ModelFile>> mModelFileSupplier;
-
- private List<ModelFile> mModelFiles;
-
- public ModelFileManager(Supplier<List<ModelFile>> modelFileSupplier) {
- mModelFileSupplier = Objects.requireNonNull(modelFileSupplier);
- }
-
- /**
- * Returns an unmodifiable list of model files listed by the given model files supplier.
- * <p>
- * The result is cached.
- */
- public List<ModelFile> listModelFiles() {
- synchronized (mLock) {
- if (mModelFiles == null) {
- mModelFiles = Collections.unmodifiableList(mModelFileSupplier.get());
- }
- return mModelFiles;
- }
- }
-
- /**
- * Returns the best model file for the given localelist, {@code null} if nothing is found.
- *
- * @param localeList the required locales, use {@code null} if there is no preference.
- */
- public ModelFile findBestModelFile(@Nullable LocaleList localeList) {
- final String languages = localeList == null || localeList.isEmpty()
- ? LocaleList.getDefault().toLanguageTags()
- : localeList.toLanguageTags();
- final List<Locale.LanguageRange> languageRangeList = Locale.LanguageRange.parse(languages);
-
- ModelFile bestModel = null;
- for (ModelFile model : listModelFiles()) {
- if (model.isAnyLanguageSupported(languageRangeList)) {
- if (model.isPreferredTo(bestModel)) {
- bestModel = model;
- }
- }
- }
- return bestModel;
- }
-
- /**
- * Default implementation of the model file supplier.
- */
- public static final class ModelFileSupplierImpl implements Supplier<List<ModelFile>> {
- private final File mUpdatedModelFile;
- private final File mFactoryModelDir;
- private final Pattern mModelFilenamePattern;
- private final Function<Integer, Integer> mVersionSupplier;
- private final Function<Integer, String> mSupportedLocalesSupplier;
-
- public ModelFileSupplierImpl(
- File factoryModelDir,
- String factoryModelFileNameRegex,
- File updatedModelFile,
- Function<Integer, Integer> versionSupplier,
- Function<Integer, String> supportedLocalesSupplier) {
- mUpdatedModelFile = Objects.requireNonNull(updatedModelFile);
- mFactoryModelDir = Objects.requireNonNull(factoryModelDir);
- mModelFilenamePattern = Pattern.compile(
- Objects.requireNonNull(factoryModelFileNameRegex));
- mVersionSupplier = Objects.requireNonNull(versionSupplier);
- mSupportedLocalesSupplier = Objects.requireNonNull(supportedLocalesSupplier);
- }
-
- @Override
- public List<ModelFile> get() {
- final List<ModelFile> modelFiles = new ArrayList<>();
- // The update model has the highest precedence.
- if (mUpdatedModelFile.exists()) {
- final ModelFile updatedModel = createModelFile(mUpdatedModelFile);
- if (updatedModel != null) {
- modelFiles.add(updatedModel);
- }
- }
- // Factory models should never have overlapping locales, so the order doesn't matter.
- if (mFactoryModelDir.exists() && mFactoryModelDir.isDirectory()) {
- final File[] files = mFactoryModelDir.listFiles();
- for (File file : files) {
- final Matcher matcher = mModelFilenamePattern.matcher(file.getName());
- if (matcher.matches() && file.isFile()) {
- final ModelFile model = createModelFile(file);
- if (model != null) {
- modelFiles.add(model);
- }
- }
- }
- }
- return modelFiles;
- }
-
- /** Returns null if the path did not point to a compatible model. */
- @Nullable
- private ModelFile createModelFile(File file) {
- if (!file.exists()) {
- return null;
- }
- ParcelFileDescriptor modelFd = null;
- try {
- modelFd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
- if (modelFd == null) {
- return null;
- }
- final int modelFdInt = modelFd.getFd();
- final int version = mVersionSupplier.apply(modelFdInt);
- final String supportedLocalesStr = mSupportedLocalesSupplier.apply(modelFdInt);
- if (supportedLocalesStr.isEmpty()) {
- Log.d(DEFAULT_LOG_TAG, "Ignoring " + file.getAbsolutePath());
- return null;
- }
- final List<Locale> supportedLocales = new ArrayList<>();
- for (String langTag : supportedLocalesStr.split(",")) {
- supportedLocales.add(Locale.forLanguageTag(langTag));
- }
- return new ModelFile(
- file,
- version,
- supportedLocales,
- supportedLocalesStr,
- ModelFile.LANGUAGE_INDEPENDENT.equals(supportedLocalesStr));
- } catch (FileNotFoundException e) {
- Log.e(DEFAULT_LOG_TAG, "Failed to find " + file.getAbsolutePath(), e);
- return null;
- } finally {
- maybeCloseAndLogError(modelFd);
- }
- }
-
- /**
- * Closes the ParcelFileDescriptor, if non-null, and logs any errors that occur.
- */
- private static void maybeCloseAndLogError(@Nullable ParcelFileDescriptor fd) {
- if (fd == null) {
- return;
- }
- try {
- fd.close();
- } catch (IOException e) {
- Log.e(DEFAULT_LOG_TAG, "Error closing file.", e);
- }
- }
-
- }
-
- /**
- * Describes TextClassifier model files on disk.
- */
- public static final class ModelFile {
- public static final String LANGUAGE_INDEPENDENT = "*";
-
- private final File mFile;
- private final int mVersion;
- private final List<Locale> mSupportedLocales;
- private final String mSupportedLocalesStr;
- private final boolean mLanguageIndependent;
-
- public ModelFile(File file, int version, List<Locale> supportedLocales,
- String supportedLocalesStr,
- boolean languageIndependent) {
- mFile = Objects.requireNonNull(file);
- mVersion = version;
- mSupportedLocales = Objects.requireNonNull(supportedLocales);
- mSupportedLocalesStr = Objects.requireNonNull(supportedLocalesStr);
- mLanguageIndependent = languageIndependent;
- }
-
- /** Returns the absolute path to the model file. */
- public String getPath() {
- return mFile.getAbsolutePath();
- }
-
- /** Returns a name to use for id generation, effectively the name of the model file. */
- public String getName() {
- return mFile.getName();
- }
-
- /** Returns the version tag in the model's metadata. */
- public int getVersion() {
- return mVersion;
- }
-
- /** Returns whether the language supports any language in the given ranges. */
- public boolean isAnyLanguageSupported(List<Locale.LanguageRange> languageRanges) {
- Objects.requireNonNull(languageRanges);
- return mLanguageIndependent || Locale.lookup(languageRanges, mSupportedLocales) != null;
- }
-
- /** Returns an immutable lists of supported locales. */
- public List<Locale> getSupportedLocales() {
- return Collections.unmodifiableList(mSupportedLocales);
- }
-
- /** Returns the original supported locals string read from the model file. */
- public String getSupportedLocalesStr() {
- return mSupportedLocalesStr;
- }
-
- /**
- * Returns if this model file is preferred to the given one.
- */
- public boolean isPreferredTo(@Nullable ModelFile model) {
- // A model is preferred to no model.
- if (model == null) {
- return true;
- }
-
- // A language-specific model is preferred to a language independent
- // model.
- if (!mLanguageIndependent && model.mLanguageIndependent) {
- return true;
- }
- if (mLanguageIndependent && !model.mLanguageIndependent) {
- return false;
- }
-
- // A higher-version model is preferred.
- if (mVersion > model.getVersion()) {
- return true;
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(getPath());
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
- if (other instanceof ModelFile) {
- final ModelFile otherModel = (ModelFile) other;
- return TextUtils.equals(getPath(), otherModel.getPath());
- }
- return false;
- }
-
- @Override
- public String toString() {
- final StringJoiner localesJoiner = new StringJoiner(",");
- for (Locale locale : mSupportedLocales) {
- localesJoiner.add(locale.toLanguageTag());
- }
- return String.format(Locale.US,
- "ModelFile { path=%s name=%s version=%d locales=%s }",
- getPath(), getName(), mVersion, localesJoiner.toString());
- }
- }
-}
diff --git a/core/java/android/view/textclassifier/SelectionEvent.java b/core/java/android/view/textclassifier/SelectionEvent.java
index e0f29a9..6f9556b 100644
--- a/core/java/android/view/textclassifier/SelectionEvent.java
+++ b/core/java/android/view/textclassifier/SelectionEvent.java
@@ -19,10 +19,8 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.view.textclassifier.TextClassifier.EntityType;
import android.view.textclassifier.TextClassifier.WidgetType;
@@ -129,7 +127,6 @@
private String mWidgetType = TextClassifier.WIDGET_TYPE_UNKNOWN;
private @InvocationMethod int mInvocationMethod;
@Nullable private String mWidgetVersion;
- private @UserIdInt int mUserId = UserHandle.USER_NULL;
@Nullable private String mResultId;
private long mEventTime;
private long mDurationSinceSessionStart;
@@ -140,7 +137,7 @@
private int mEnd;
private int mSmartStart;
private int mSmartEnd;
- private boolean mUseDefaultTextClassifier;
+ @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
SelectionEvent(
int start, int end,
@@ -175,8 +172,7 @@
mEnd = in.readInt();
mSmartStart = in.readInt();
mSmartEnd = in.readInt();
- mUserId = in.readInt();
- mUseDefaultTextClassifier = in.readBoolean();
+ mSystemTcMetadata = in.readParcelable(null);
}
@Override
@@ -205,8 +201,7 @@
dest.writeInt(mEnd);
dest.writeInt(mSmartStart);
dest.writeInt(mSmartEnd);
- dest.writeInt(mUserId);
- dest.writeBoolean(mUseDefaultTextClassifier);
+ dest.writeParcelable(mSystemTcMetadata, flags);
}
@Override
@@ -413,41 +408,22 @@
}
/**
- * Sets the id of this event's user.
- * <p>
- * Package-private for SystemTextClassifier's use.
- */
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
- }
-
- /**
- * Returns the id of this event's user.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
+ void setSystemTextClassifierMetadata(@Nullable SystemTextClassifierMetadata systemTcMetadata) {
+ mSystemTcMetadata = systemTcMetadata;
}
/**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
@@ -476,7 +452,7 @@
mPackageName = context.getPackageName();
mWidgetType = context.getWidgetType();
mWidgetVersion = context.getWidgetVersion();
- mUserId = context.getUserId();
+ mSystemTcMetadata = context.getSystemTextClassifierMetadata();
}
/**
@@ -663,10 +639,9 @@
@Override
public int hashCode() {
return Objects.hash(mAbsoluteStart, mAbsoluteEnd, mEventType, mEntityType,
- mWidgetVersion, mPackageName, mUserId, mWidgetType, mInvocationMethod, mResultId,
+ mWidgetVersion, mPackageName, mWidgetType, mInvocationMethod, mResultId,
mEventTime, mDurationSinceSessionStart, mDurationSincePreviousEvent,
- mEventIndex, mSessionId, mStart, mEnd, mSmartStart, mSmartEnd,
- mUseDefaultTextClassifier);
+ mEventIndex, mSessionId, mStart, mEnd, mSmartStart, mSmartEnd, mSystemTcMetadata);
}
@Override
@@ -685,7 +660,6 @@
&& Objects.equals(mEntityType, other.mEntityType)
&& Objects.equals(mWidgetVersion, other.mWidgetVersion)
&& Objects.equals(mPackageName, other.mPackageName)
- && mUserId == other.mUserId
&& Objects.equals(mWidgetType, other.mWidgetType)
&& mInvocationMethod == other.mInvocationMethod
&& Objects.equals(mResultId, other.mResultId)
@@ -698,7 +672,7 @@
&& mEnd == other.mEnd
&& mSmartStart == other.mSmartStart
&& mSmartEnd == other.mSmartEnd
- && mUseDefaultTextClassifier == other.mUseDefaultTextClassifier;
+ && mSystemTcMetadata == other.mSystemTcMetadata;
}
@Override
@@ -706,15 +680,14 @@
return String.format(Locale.US,
"SelectionEvent {absoluteStart=%d, absoluteEnd=%d, eventType=%d, entityType=%s, "
+ "widgetVersion=%s, packageName=%s, widgetType=%s, invocationMethod=%s, "
- + "userId=%d, resultId=%s, eventTime=%d, durationSinceSessionStart=%d, "
+ + "resultId=%s, eventTime=%d, durationSinceSessionStart=%d, "
+ "durationSincePreviousEvent=%d, eventIndex=%d,"
+ "sessionId=%s, start=%d, end=%d, smartStart=%d, smartEnd=%d, "
- + "mUseDefaultTextClassifier=%b}",
+ + "systemTcMetadata=%s}",
mAbsoluteStart, mAbsoluteEnd, mEventType, mEntityType,
mWidgetVersion, mPackageName, mWidgetType, mInvocationMethod,
- mUserId, mResultId, mEventTime, mDurationSinceSessionStart,
- mDurationSincePreviousEvent, mEventIndex,
- mSessionId, mStart, mEnd, mSmartStart, mSmartEnd, mUseDefaultTextClassifier);
+ mResultId, mEventTime, mDurationSinceSessionStart, mDurationSincePreviousEvent,
+ mEventIndex, mSessionId, mStart, mEnd, mSmartStart, mSmartEnd, mSystemTcMetadata);
}
public static final @android.annotation.NonNull Creator<SelectionEvent> CREATOR = new Creator<SelectionEvent>() {
diff --git a/core/java/android/view/textclassifier/SelectionSessionLogger.java b/core/java/android/view/textclassifier/SelectionSessionLogger.java
index ae9f65b..e7d896e 100644
--- a/core/java/android/view/textclassifier/SelectionSessionLogger.java
+++ b/core/java/android/view/textclassifier/SelectionSessionLogger.java
@@ -16,251 +16,24 @@
package android.view.textclassifier;
-import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.content.Context;
-import android.metrics.LogMaker;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-import java.text.BreakIterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Objects;
-import java.util.StringJoiner;
/**
* A helper for logging selection session events.
+ *
* @hide
*/
public final class SelectionSessionLogger {
-
- private static final String LOG_TAG = "SelectionSessionLogger";
- static final String CLASSIFIER_ID = "androidtc";
-
- private static final int START_EVENT_DELTA = MetricsEvent.FIELD_SELECTION_SINCE_START;
- private static final int PREV_EVENT_DELTA = MetricsEvent.FIELD_SELECTION_SINCE_PREVIOUS;
- private static final int INDEX = MetricsEvent.FIELD_SELECTION_SESSION_INDEX;
- private static final int WIDGET_TYPE = MetricsEvent.FIELD_SELECTION_WIDGET_TYPE;
- private static final int WIDGET_VERSION = MetricsEvent.FIELD_SELECTION_WIDGET_VERSION;
- private static final int MODEL_NAME = MetricsEvent.FIELD_TEXTCLASSIFIER_MODEL;
- private static final int ENTITY_TYPE = MetricsEvent.FIELD_SELECTION_ENTITY_TYPE;
- private static final int SMART_START = MetricsEvent.FIELD_SELECTION_SMART_RANGE_START;
- private static final int SMART_END = MetricsEvent.FIELD_SELECTION_SMART_RANGE_END;
- private static final int EVENT_START = MetricsEvent.FIELD_SELECTION_RANGE_START;
- private static final int EVENT_END = MetricsEvent.FIELD_SELECTION_RANGE_END;
- private static final int SESSION_ID = MetricsEvent.FIELD_SELECTION_SESSION_ID;
-
- private static final String ZERO = "0";
- private static final String UNKNOWN = "unknown";
-
- private final MetricsLogger mMetricsLogger;
-
- public SelectionSessionLogger() {
- mMetricsLogger = new MetricsLogger();
- }
-
- @VisibleForTesting
- public SelectionSessionLogger(@NonNull MetricsLogger metricsLogger) {
- mMetricsLogger = Objects.requireNonNull(metricsLogger);
- }
-
- /** Emits a selection event to the logs. */
- public void writeEvent(@NonNull SelectionEvent event) {
- Objects.requireNonNull(event);
- final LogMaker log = new LogMaker(MetricsEvent.TEXT_SELECTION_SESSION)
- .setType(getLogType(event))
- .setSubtype(getLogSubType(event))
- .setPackageName(event.getPackageName())
- .addTaggedData(START_EVENT_DELTA, event.getDurationSinceSessionStart())
- .addTaggedData(PREV_EVENT_DELTA, event.getDurationSincePreviousEvent())
- .addTaggedData(INDEX, event.getEventIndex())
- .addTaggedData(WIDGET_TYPE, event.getWidgetType())
- .addTaggedData(WIDGET_VERSION, event.getWidgetVersion())
- .addTaggedData(ENTITY_TYPE, event.getEntityType())
- .addTaggedData(EVENT_START, event.getStart())
- .addTaggedData(EVENT_END, event.getEnd());
- if (isPlatformLocalTextClassifierSmartSelection(event.getResultId())) {
- // Ensure result id and smart indices are only set for events with smart selection from
- // the platform's textclassifier.
- log.addTaggedData(MODEL_NAME, SignatureParser.getModelName(event.getResultId()))
- .addTaggedData(SMART_START, event.getSmartStart())
- .addTaggedData(SMART_END, event.getSmartEnd());
- }
- if (event.getSessionId() != null) {
- log.addTaggedData(SESSION_ID, event.getSessionId().getValue());
- }
- mMetricsLogger.write(log);
- debugLog(log);
- }
-
- private static int getLogType(SelectionEvent event) {
- switch (event.getEventType()) {
- case SelectionEvent.ACTION_OVERTYPE:
- return MetricsEvent.ACTION_TEXT_SELECTION_OVERTYPE;
- case SelectionEvent.ACTION_COPY:
- return MetricsEvent.ACTION_TEXT_SELECTION_COPY;
- case SelectionEvent.ACTION_PASTE:
- return MetricsEvent.ACTION_TEXT_SELECTION_PASTE;
- case SelectionEvent.ACTION_CUT:
- return MetricsEvent.ACTION_TEXT_SELECTION_CUT;
- case SelectionEvent.ACTION_SHARE:
- return MetricsEvent.ACTION_TEXT_SELECTION_SHARE;
- case SelectionEvent.ACTION_SMART_SHARE:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE;
- case SelectionEvent.ACTION_DRAG:
- return MetricsEvent.ACTION_TEXT_SELECTION_DRAG;
- case SelectionEvent.ACTION_ABANDON:
- return MetricsEvent.ACTION_TEXT_SELECTION_ABANDON;
- case SelectionEvent.ACTION_OTHER:
- return MetricsEvent.ACTION_TEXT_SELECTION_OTHER;
- case SelectionEvent.ACTION_SELECT_ALL:
- return MetricsEvent.ACTION_TEXT_SELECTION_SELECT_ALL;
- case SelectionEvent.ACTION_RESET:
- return MetricsEvent.ACTION_TEXT_SELECTION_RESET;
- case SelectionEvent.EVENT_SELECTION_STARTED:
- return MetricsEvent.ACTION_TEXT_SELECTION_START;
- case SelectionEvent.EVENT_SELECTION_MODIFIED:
- return MetricsEvent.ACTION_TEXT_SELECTION_MODIFY;
- case SelectionEvent.EVENT_SMART_SELECTION_SINGLE:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_SINGLE;
- case SelectionEvent.EVENT_SMART_SELECTION_MULTI:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_MULTI;
- case SelectionEvent.EVENT_AUTO_SELECTION:
- return MetricsEvent.ACTION_TEXT_SELECTION_AUTO;
- default:
- return MetricsEvent.VIEW_UNKNOWN;
- }
- }
-
- private static int getLogSubType(SelectionEvent event) {
- switch (event.getInvocationMethod()) {
- case SelectionEvent.INVOCATION_MANUAL:
- return MetricsEvent.TEXT_SELECTION_INVOCATION_MANUAL;
- case SelectionEvent.INVOCATION_LINK:
- return MetricsEvent.TEXT_SELECTION_INVOCATION_LINK;
- default:
- return MetricsEvent.TEXT_SELECTION_INVOCATION_UNKNOWN;
- }
- }
-
- private static String getLogTypeString(int logType) {
- switch (logType) {
- case MetricsEvent.ACTION_TEXT_SELECTION_OVERTYPE:
- return "OVERTYPE";
- case MetricsEvent.ACTION_TEXT_SELECTION_COPY:
- return "COPY";
- case MetricsEvent.ACTION_TEXT_SELECTION_PASTE:
- return "PASTE";
- case MetricsEvent.ACTION_TEXT_SELECTION_CUT:
- return "CUT";
- case MetricsEvent.ACTION_TEXT_SELECTION_SHARE:
- return "SHARE";
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE:
- return "SMART_SHARE";
- case MetricsEvent.ACTION_TEXT_SELECTION_DRAG:
- return "DRAG";
- case MetricsEvent.ACTION_TEXT_SELECTION_ABANDON:
- return "ABANDON";
- case MetricsEvent.ACTION_TEXT_SELECTION_OTHER:
- return "OTHER";
- case MetricsEvent.ACTION_TEXT_SELECTION_SELECT_ALL:
- return "SELECT_ALL";
- case MetricsEvent.ACTION_TEXT_SELECTION_RESET:
- return "RESET";
- case MetricsEvent.ACTION_TEXT_SELECTION_START:
- return "SELECTION_STARTED";
- case MetricsEvent.ACTION_TEXT_SELECTION_MODIFY:
- return "SELECTION_MODIFIED";
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_SINGLE:
- return "SMART_SELECTION_SINGLE";
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_MULTI:
- return "SMART_SELECTION_MULTI";
- case MetricsEvent.ACTION_TEXT_SELECTION_AUTO:
- return "AUTO_SELECTION";
- default:
- return UNKNOWN;
- }
- }
-
- private static String getLogSubTypeString(int logSubType) {
- switch (logSubType) {
- case MetricsEvent.TEXT_SELECTION_INVOCATION_MANUAL:
- return "MANUAL";
- case MetricsEvent.TEXT_SELECTION_INVOCATION_LINK:
- return "LINK";
- default:
- return UNKNOWN;
- }
- }
+ // Keep this in sync with the ResultIdUtils in libtextclassifier.
+ private static final String CLASSIFIER_ID = "androidtc";
static boolean isPlatformLocalTextClassifierSmartSelection(String signature) {
return SelectionSessionLogger.CLASSIFIER_ID.equals(
SelectionSessionLogger.SignatureParser.getClassifierId(signature));
}
- private static void debugLog(LogMaker log) {
- if (!Log.ENABLE_FULL_LOGGING) {
- return;
- }
- final String widgetType = Objects.toString(log.getTaggedData(WIDGET_TYPE), UNKNOWN);
- final String widgetVersion = Objects.toString(log.getTaggedData(WIDGET_VERSION), "");
- final String widget = widgetVersion.isEmpty()
- ? widgetType : widgetType + "-" + widgetVersion;
- final int index = Integer.parseInt(Objects.toString(log.getTaggedData(INDEX), ZERO));
- if (log.getType() == MetricsEvent.ACTION_TEXT_SELECTION_START) {
- String sessionId = Objects.toString(log.getTaggedData(SESSION_ID), "");
- sessionId = sessionId.substring(sessionId.lastIndexOf("-") + 1);
- Log.d(LOG_TAG, String.format("New selection session: %s (%s)", widget, sessionId));
- }
-
- final String model = Objects.toString(log.getTaggedData(MODEL_NAME), UNKNOWN);
- final String entity = Objects.toString(log.getTaggedData(ENTITY_TYPE), UNKNOWN);
- final String type = getLogTypeString(log.getType());
- final String subType = getLogSubTypeString(log.getSubtype());
- final int smartStart = Integer.parseInt(
- Objects.toString(log.getTaggedData(SMART_START), ZERO));
- final int smartEnd = Integer.parseInt(
- Objects.toString(log.getTaggedData(SMART_END), ZERO));
- final int eventStart = Integer.parseInt(
- Objects.toString(log.getTaggedData(EVENT_START), ZERO));
- final int eventEnd = Integer.parseInt(
- Objects.toString(log.getTaggedData(EVENT_END), ZERO));
-
- Log.v(LOG_TAG,
- String.format(Locale.US, "%2d: %s/%s/%s, range=%d,%d - smart_range=%d,%d (%s/%s)",
- index, type, subType, entity, eventStart, eventEnd, smartStart, smartEnd,
- widget, model));
- }
-
- /**
- * Returns a token iterator for tokenizing text for logging purposes.
- */
- public static BreakIterator getTokenIterator(@NonNull Locale locale) {
- return BreakIterator.getWordInstance(Objects.requireNonNull(locale));
- }
-
- /**
- * Creates a string id that may be used to identify a TextClassifier result.
- */
- public static String createId(
- String text, int start, int end, Context context, int modelVersion,
- List<Locale> locales) {
- Objects.requireNonNull(text);
- Objects.requireNonNull(context);
- Objects.requireNonNull(locales);
- final StringJoiner localesJoiner = new StringJoiner(",");
- for (Locale locale : locales) {
- localesJoiner.add(locale.toLanguageTag());
- }
- final String modelName = String.format(Locale.US, "%s_v%d", localesJoiner.toString(),
- modelVersion);
- final int hash = Objects.hash(text, start, end, context.getPackageName());
- return SignatureParser.createSignature(CLASSIFIER_ID, modelName, hash);
- }
-
/**
* Helper for creating and parsing string ids for
* {@link android.view.textclassifier.TextClassifierImpl}.
@@ -268,10 +41,6 @@
@VisibleForTesting
public static final class SignatureParser {
- static String createSignature(String classifierId, String modelName, int hash) {
- return String.format(Locale.US, "%s|%s|%d", classifierId, modelName, hash);
- }
-
static String getClassifierId(@Nullable String signature) {
if (signature == null) {
return "";
@@ -282,29 +51,5 @@
}
return "";
}
-
- static String getModelName(@Nullable String signature) {
- if (signature == null) {
- return "";
- }
- final int start = signature.indexOf("|") + 1;
- final int end = signature.indexOf("|", start);
- if (start >= 1 && end >= start) {
- return signature.substring(start, end);
- }
- return "";
- }
-
- static int getHash(@Nullable String signature) {
- if (signature == null) {
- return 0;
- }
- final int index1 = signature.indexOf("|");
- final int index2 = signature.indexOf("|", index1);
- if (index2 > 0) {
- return Integer.parseInt(signature.substring(index2));
- }
- return 0;
- }
}
}
diff --git a/core/java/android/view/textclassifier/SystemTextClassifier.java b/core/java/android/view/textclassifier/SystemTextClassifier.java
index fe5e8d6..8eac1c1 100644
--- a/core/java/android/view/textclassifier/SystemTextClassifier.java
+++ b/core/java/android/view/textclassifier/SystemTextClassifier.java
@@ -18,7 +18,6 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.annotation.WorkerThread;
import android.content.Context;
import android.os.Bundle;
@@ -39,25 +38,31 @@
import java.util.concurrent.TimeUnit;
/**
- * Proxy to the system's default TextClassifier.
+ * proxy to the request to TextClassifierService via the TextClassificationManagerService.
+ *
* @hide
*/
@VisibleForTesting(visibility = Visibility.PACKAGE)
public final class SystemTextClassifier implements TextClassifier {
- private static final String LOG_TAG = "SystemTextClassifier";
+ private static final String LOG_TAG = TextClassifier.LOG_TAG;
private final ITextClassifierService mManagerService;
private final TextClassificationConstants mSettings;
private final TextClassifier mFallback;
- private final String mPackageName;
- // NOTE: Always set this before sending a request to the manager service otherwise the manager
- // service will throw a remote exception.
- @UserIdInt
- private final int mUserId;
- private final boolean mUseDefault;
private TextClassificationSessionId mSessionId;
+ // NOTE: Always set this before sending a request to the manager service otherwise the
+ // manager service will throw a remote exception.
+ @NonNull
+ private final SystemTextClassifierMetadata mSystemTcMetadata;
+ /**
+ * Constructor of {@link SystemTextClassifier}
+ *
+ * @param context the context of the request.
+ * @param settings TextClassifier specific settings.
+ * @param useDefault whether to use the default text classifier to handle this request
+ */
public SystemTextClassifier(
Context context,
TextClassificationConstants settings,
@@ -66,9 +71,11 @@
ServiceManager.getServiceOrThrow(Context.TEXT_CLASSIFICATION_SERVICE));
mSettings = Objects.requireNonNull(settings);
mFallback = TextClassifier.NO_OP;
- mPackageName = Objects.requireNonNull(context.getOpPackageName());
- mUserId = context.getUserId();
- mUseDefault = useDefault;
+ // NOTE: Always set this before sending a request to the manager service otherwise the
+ // manager service will throw a remote exception.
+ mSystemTcMetadata = new SystemTextClassifierMetadata(
+ Objects.requireNonNull(context.getOpPackageName()), context.getUserId(),
+ useDefault);
}
/**
@@ -80,9 +87,7 @@
Objects.requireNonNull(request);
Utils.checkMainThread();
try {
- request.setCallingPackageName(mPackageName);
- request.setUserId(mUserId);
- request.setUseDefaultTextClassifier(mUseDefault);
+ request.setSystemTextClassifierMetadata(mSystemTcMetadata);
final BlockingCallback<TextSelection> callback =
new BlockingCallback<>("textselection");
mManagerService.onSuggestSelection(mSessionId, request, callback);
@@ -105,9 +110,7 @@
Objects.requireNonNull(request);
Utils.checkMainThread();
try {
- request.setCallingPackageName(mPackageName);
- request.setUserId(mUserId);
- request.setUseDefaultTextClassifier(mUseDefault);
+ request.setSystemTextClassifierMetadata(mSystemTcMetadata);
final BlockingCallback<TextClassification> callback =
new BlockingCallback<>("textclassification");
mManagerService.onClassifyText(mSessionId, request, callback);
@@ -137,9 +140,7 @@
}
try {
- request.setCallingPackageName(mPackageName);
- request.setUserId(mUserId);
- request.setUseDefaultTextClassifier(mUseDefault);
+ request.setSystemTextClassifierMetadata(mSystemTcMetadata);
final BlockingCallback<TextLinks> callback =
new BlockingCallback<>("textlinks");
mManagerService.onGenerateLinks(mSessionId, request, callback);
@@ -159,8 +160,7 @@
Utils.checkMainThread();
try {
- event.setUserId(mUserId);
- event.setUseDefaultTextClassifier(mUseDefault);
+ event.setSystemTextClassifierMetadata(mSystemTcMetadata);
mManagerService.onSelectionEvent(mSessionId, event);
} catch (RemoteException e) {
Log.e(LOG_TAG, "Error reporting selection event.", e);
@@ -173,12 +173,11 @@
Utils.checkMainThread();
try {
- final TextClassificationContext tcContext = event.getEventContext() == null
- ? new TextClassificationContext.Builder(mPackageName, WIDGET_TYPE_UNKNOWN)
- .build()
- : event.getEventContext();
- tcContext.setUserId(mUserId);
- tcContext.setUseDefaultTextClassifier(mUseDefault);
+ final TextClassificationContext tcContext =
+ event.getEventContext() == null ? new TextClassificationContext.Builder(
+ mSystemTcMetadata.getCallingPackageName(), WIDGET_TYPE_UNKNOWN).build()
+ : event.getEventContext();
+ tcContext.setSystemTextClassifierMetadata(mSystemTcMetadata);
event.setEventContext(tcContext);
mManagerService.onTextClassifierEvent(mSessionId, event);
} catch (RemoteException e) {
@@ -192,9 +191,7 @@
Utils.checkMainThread();
try {
- request.setCallingPackageName(mPackageName);
- request.setUserId(mUserId);
- request.setUseDefaultTextClassifier(mUseDefault);
+ request.setSystemTextClassifierMetadata(mSystemTcMetadata);
final BlockingCallback<TextLanguage> callback =
new BlockingCallback<>("textlanguage");
mManagerService.onDetectLanguage(mSessionId, request, callback);
@@ -214,9 +211,7 @@
Utils.checkMainThread();
try {
- request.setCallingPackageName(mPackageName);
- request.setUserId(mUserId);
- request.setUseDefaultTextClassifier(mUseDefault);
+ request.setSystemTextClassifierMetadata(mSystemTcMetadata);
final BlockingCallback<ConversationActions> callback =
new BlockingCallback<>("conversation-actions");
mManagerService.onSuggestConversationActions(mSessionId, request, callback);
@@ -256,10 +251,8 @@
printWriter.println("SystemTextClassifier:");
printWriter.increaseIndent();
printWriter.printPair("mFallback", mFallback);
- printWriter.printPair("mPackageName", mPackageName);
printWriter.printPair("mSessionId", mSessionId);
- printWriter.printPair("mUserId", mUserId);
- printWriter.printPair("mUseDefault", mUseDefault);
+ printWriter.printPair("mSystemTcMetadata", mSystemTcMetadata);
printWriter.decreaseIndent();
printWriter.println();
}
@@ -275,7 +268,7 @@
@NonNull TextClassificationSessionId sessionId) {
mSessionId = Objects.requireNonNull(sessionId);
try {
- classificationContext.setUserId(mUserId);
+ classificationContext.setSystemTextClassifierMetadata(mSystemTcMetadata);
mManagerService.onCreateTextClassificationSession(classificationContext, mSessionId);
} catch (RemoteException e) {
Log.e(LOG_TAG, "Error starting a new classification session.", e);
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.aidl
similarity index 71%
copy from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
copy to core/java/android/view/textclassifier/SystemTextClassifierMetadata.aidl
index d691f41..4d4e90a 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.aidl
@@ -14,16 +14,6 @@
* limitations under the License.
*/
-package android.net.wifi;
+package android.view.textclassifier;
-/**
- * Interface for Wi-Fi score callback.
- *
- * @hide
- */
-oneway interface IScoreChangeCallback
-{
- void onScoreChange(int sessionId, int score);
-
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
-}
+parcelable SystemTextClassifierMetadata;
\ No newline at end of file
diff --git a/core/java/android/view/textclassifier/SystemTextClassifierMetadata.java b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.java
new file mode 100644
index 0000000..971e3e2
--- /dev/null
+++ b/core/java/android/view/textclassifier/SystemTextClassifierMetadata.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2020 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.view.textclassifier;
+
+import android.annotation.NonNull;
+import android.annotation.UserIdInt;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.annotations.VisibleForTesting.Visibility;
+
+import java.util.Locale;
+import java.util.Objects;
+
+/**
+ * SystemTextClassifier specific information.
+ * <p>
+ * This contains information requires for the TextClassificationManagerService to process the
+ * requests from the application, e.g. user id, calling package name and etc. Centrialize the data
+ * into this class helps to extend the scalability if we want to add new fields.
+ * @hide
+ */
+@VisibleForTesting(visibility = Visibility.PACKAGE)
+public final class SystemTextClassifierMetadata implements Parcelable {
+
+ /* The name of the package that sent the TC request. */
+ @NonNull
+ private final String mCallingPackageName;
+ /* The id of the user that sent the TC request. */
+ @UserIdInt
+ private final int mUserId;
+ /* Whether to use the default text classifier to handle the request. */
+ private final boolean mUseDefaultTextClassifier;
+
+ public SystemTextClassifierMetadata(@NonNull String packageName, @UserIdInt int userId,
+ boolean useDefaultTextClassifier) {
+ Objects.requireNonNull(packageName);
+ mCallingPackageName = packageName;
+ mUserId = userId;
+ mUseDefaultTextClassifier = useDefaultTextClassifier;
+ }
+
+ /**
+ * Returns the id of the user that sent the TC request.
+ */
+ @UserIdInt
+ public int getUserId() {
+ return mUserId;
+ }
+
+ /**
+ * Returns the name of the package that sent the TC request.
+ * This returns {@code null} if no calling package name is set.
+ */
+ @NonNull
+ public String getCallingPackageName() {
+ return mCallingPackageName;
+ }
+
+ /**
+ * Returns whether to use the default text classifier to handle TC request.
+ */
+ public boolean useDefaultTextClassifier() {
+ return mUseDefaultTextClassifier;
+ }
+
+ @Override
+ public String toString() {
+ return String.format(Locale.US,
+ "SystemTextClassifierMetadata {callingPackageName=%s, userId=%d, "
+ + "useDefaultTextClassifier=%b}",
+ mCallingPackageName, mUserId, mUseDefaultTextClassifier);
+ }
+
+ private static SystemTextClassifierMetadata readFromParcel(Parcel in) {
+ final String packageName = in.readString();
+ final int userId = in.readInt();
+ final boolean useDefaultTextClassifier = in.readBoolean();
+ return new SystemTextClassifierMetadata(packageName, userId, useDefaultTextClassifier);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeString(mCallingPackageName);
+ dest.writeInt(mUserId);
+ dest.writeBoolean(mUseDefaultTextClassifier);
+ }
+
+ public static final @NonNull Creator<SystemTextClassifierMetadata> CREATOR =
+ new Creator<SystemTextClassifierMetadata>() {
+ @Override
+ public SystemTextClassifierMetadata createFromParcel(Parcel in) {
+ return readFromParcel(in);
+ }
+
+ @Override
+ public SystemTextClassifierMetadata[] newArray(int size) {
+ return new SystemTextClassifierMetadata[size];
+ }
+ };
+}
diff --git a/core/java/android/view/textclassifier/TextClassification.java b/core/java/android/view/textclassifier/TextClassification.java
index 00f762b..3aed32a 100644
--- a/core/java/android/view/textclassifier/TextClassification.java
+++ b/core/java/android/view/textclassifier/TextClassification.java
@@ -21,7 +21,6 @@
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.app.PendingIntent;
import android.app.RemoteAction;
import android.content.Context;
@@ -36,7 +35,6 @@
import android.os.LocaleList;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.text.SpannedString;
import android.util.ArrayMap;
import android.view.View.OnClickListener;
@@ -46,8 +44,6 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
-import com.google.android.textclassifier.AnnotatorModel;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.time.ZonedDateTime;
@@ -329,9 +325,6 @@
@NonNull private List<RemoteAction> mActions = new ArrayList<>();
@NonNull private final Map<String, Float> mTypeScoreMap = new ArrayMap<>();
- @NonNull
- private final Map<String, AnnotatorModel.ClassificationResult> mClassificationResults =
- new ArrayMap<>();
@Nullable private String mText;
@Nullable private Drawable mLegacyIcon;
@Nullable private String mLegacyLabel;
@@ -364,36 +357,7 @@
public Builder setEntityType(
@NonNull @EntityType String type,
@FloatRange(from = 0.0, to = 1.0) float confidenceScore) {
- setEntityType(type, confidenceScore, null);
- return this;
- }
-
- /**
- * @see #setEntityType(String, float)
- *
- * @hide
- */
- @NonNull
- public Builder setEntityType(AnnotatorModel.ClassificationResult classificationResult) {
- setEntityType(
- classificationResult.getCollection(),
- classificationResult.getScore(),
- classificationResult);
- return this;
- }
-
- /**
- * @see #setEntityType(String, float)
- *
- * @hide
- */
- @NonNull
- private Builder setEntityType(
- @NonNull @EntityType String type,
- @FloatRange(from = 0.0, to = 1.0) float confidenceScore,
- @Nullable AnnotatorModel.ClassificationResult classificationResult) {
mTypeScoreMap.put(type, confidenceScore);
- mClassificationResults.put(type, classificationResult);
return this;
}
@@ -519,25 +483,7 @@
EntityConfidence entityConfidence = new EntityConfidence(mTypeScoreMap);
return new TextClassification(mText, mLegacyIcon, mLegacyLabel, mLegacyIntent,
mLegacyOnClickListener, mActions, entityConfidence, mId,
- buildExtras(entityConfidence));
- }
-
- private Bundle buildExtras(EntityConfidence entityConfidence) {
- final Bundle extras = mExtras == null ? new Bundle() : mExtras;
- if (mActionIntents.stream().anyMatch(Objects::nonNull)) {
- ExtrasUtils.putActionsIntents(extras, mActionIntents);
- }
- if (mForeignLanguageExtra != null) {
- ExtrasUtils.putForeignLanguageExtra(extras, mForeignLanguageExtra);
- }
- List<String> sortedTypes = entityConfidence.getEntities();
- ArrayList<AnnotatorModel.ClassificationResult> sortedEntities = new ArrayList<>();
- for (String type : sortedTypes) {
- sortedEntities.add(mClassificationResults.get(type));
- }
- ExtrasUtils.putEntities(
- extras, sortedEntities.toArray(new AnnotatorModel.ClassificationResult[0]));
- return extras.isEmpty() ? Bundle.EMPTY : extras;
+ mExtras == null ? Bundle.EMPTY : mExtras);
}
}
@@ -552,10 +498,7 @@
@Nullable private final LocaleList mDefaultLocales;
@Nullable private final ZonedDateTime mReferenceTime;
@NonNull private final Bundle mExtras;
- @Nullable private String mCallingPackageName;
- @UserIdInt
- private int mUserId = UserHandle.USER_NULL;
- private boolean mUseDefaultTextClassifier;
+ @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
private Request(
CharSequence text,
@@ -616,62 +559,33 @@
}
/**
- * Sets the name of the package that is sending this request.
- * <p>
- * For SystemTextClassifier's use.
- * @hide
- */
- @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
- public void setCallingPackageName(@Nullable String callingPackageName) {
- mCallingPackageName = callingPackageName;
- }
-
- /**
* Returns the name of the package that sent this request.
* This returns {@code null} if no calling package name is set.
*/
@Nullable
public String getCallingPackageName() {
- return mCallingPackageName;
+ return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
}
/**
- * Sets the id of the user that sent this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
- }
-
- /**
- * Returns the id of the user that sent this request.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
+ @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+ public void setSystemTextClassifierMetadata(
+ @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+ mSystemTcMetadata = systemTcMetadata;
}
/**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
@@ -773,10 +687,8 @@
dest.writeInt(mEndIndex);
dest.writeParcelable(mDefaultLocales, flags);
dest.writeString(mReferenceTime == null ? null : mReferenceTime.toString());
- dest.writeString(mCallingPackageName);
- dest.writeInt(mUserId);
dest.writeBundle(mExtras);
- dest.writeBoolean(mUseDefaultTextClassifier);
+ dest.writeParcelable(mSystemTcMetadata, flags);
}
private static Request readFromParcel(Parcel in) {
@@ -787,16 +699,12 @@
final String referenceTimeString = in.readString();
final ZonedDateTime referenceTime = referenceTimeString == null
? null : ZonedDateTime.parse(referenceTimeString);
- final String callingPackageName = in.readString();
- final int userId = in.readInt();
final Bundle extras = in.readBundle();
- final boolean useDefaultTextClassifier = in.readBoolean();
+ final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
final Request request = new Request(text, startIndex, endIndex,
defaultLocales, referenceTime, extras);
- request.setCallingPackageName(callingPackageName);
- request.setUserId(userId);
- request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+ request.setSystemTextClassifierMetadata(systemTcMetadata);
return request;
}
diff --git a/core/java/android/view/textclassifier/TextClassificationConstants.java b/core/java/android/view/textclassifier/TextClassificationConstants.java
index 3d5ac58..adb6fea 100644
--- a/core/java/android/view/textclassifier/TextClassificationConstants.java
+++ b/core/java/android/view/textclassifier/TextClassificationConstants.java
@@ -17,16 +17,11 @@
package android.view.textclassifier;
import android.annotation.Nullable;
-import android.content.Context;
import android.provider.DeviceConfig;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
/**
* TextClassifier specific settings.
*
@@ -41,8 +36,6 @@
*/
// TODO: Rename to TextClassifierSettings.
public final class TextClassificationConstants {
- private static final String DELIMITER = ":";
-
/**
* Whether the smart linkify feature is enabled.
*/
@@ -60,7 +53,6 @@
* Enable smart selection without a visible UI changes.
*/
private static final String MODEL_DARK_LAUNCH_ENABLED = "model_dark_launch_enabled";
-
/**
* Whether the smart selection feature is enabled.
*/
@@ -75,88 +67,10 @@
private static final String SMART_SELECT_ANIMATION_ENABLED =
"smart_select_animation_enabled";
/**
- * Max length of text that suggestSelection can accept.
- */
- @VisibleForTesting
- static final String SUGGEST_SELECTION_MAX_RANGE_LENGTH =
- "suggest_selection_max_range_length";
- /**
- * Max length of text that classifyText can accept.
- */
- private static final String CLASSIFY_TEXT_MAX_RANGE_LENGTH = "classify_text_max_range_length";
- /**
* Max length of text that generateLinks can accept.
*/
- private static final String GENERATE_LINKS_MAX_TEXT_LENGTH = "generate_links_max_text_length";
- /**
- * Sampling rate for generateLinks logging.
- */
- private static final String GENERATE_LINKS_LOG_SAMPLE_RATE =
- "generate_links_log_sample_rate";
- /**
- * A colon(:) separated string that specifies the default entities types for
- * generateLinks when hint is not given.
- */
@VisibleForTesting
- static final String ENTITY_LIST_DEFAULT = "entity_list_default";
- /**
- * A colon(:) separated string that specifies the default entities types for
- * generateLinks when the text is in a not editable UI widget.
- */
- private static final String ENTITY_LIST_NOT_EDITABLE = "entity_list_not_editable";
- /**
- * A colon(:) separated string that specifies the default entities types for
- * generateLinks when the text is in an editable UI widget.
- */
- private static final String ENTITY_LIST_EDITABLE = "entity_list_editable";
- /**
- * A colon(:) separated string that specifies the default action types for
- * suggestConversationActions when the suggestions are used in an app.
- */
- private static final String IN_APP_CONVERSATION_ACTION_TYPES_DEFAULT =
- "in_app_conversation_action_types_default";
- /**
- * A colon(:) separated string that specifies the default action types for
- * suggestConversationActions when the suggestions are used in a notification.
- */
- private static final String NOTIFICATION_CONVERSATION_ACTION_TYPES_DEFAULT =
- "notification_conversation_action_types_default";
- /**
- * Threshold to accept a suggested language from LangID model.
- */
- @VisibleForTesting
- static final String LANG_ID_THRESHOLD_OVERRIDE = "lang_id_threshold_override";
- /**
- * Whether to enable {@link android.view.textclassifier.TemplateIntentFactory}.
- */
- private static final String TEMPLATE_INTENT_FACTORY_ENABLED = "template_intent_factory_enabled";
- /**
- * Whether to enable "translate" action in classifyText.
- */
- private static final String TRANSLATE_IN_CLASSIFICATION_ENABLED =
- "translate_in_classification_enabled";
- /**
- * Whether to detect the languages of the text in request by using langId for the native
- * model.
- */
- private static final String DETECT_LANGUAGES_FROM_TEXT_ENABLED =
- "detect_languages_from_text_enabled";
- /**
- * A colon(:) separated string that specifies the configuration to use when including
- * surrounding context text in language detection queries.
- * <p>
- * Format= minimumTextSize<int>:penalizeRatio<float>:textScoreRatio<float>
- * <p>
- * e.g. 20:1.0:0.4
- * <p>
- * Accept all text lengths with minimumTextSize=0
- * <p>
- * Reject all text less than minimumTextSize with penalizeRatio=0
- * @see {@code TextClassifierImpl#detectLanguages(String, int, int)} for reference.
- */
- @VisibleForTesting
- static final String LANG_ID_CONTEXT_SETTINGS = "lang_id_context_settings";
-
+ static final String GENERATE_LINKS_MAX_TEXT_LENGTH = "generate_links_max_text_length";
/**
* The TextClassifierService which would like to use. Example of setting the package:
* <pre>
@@ -168,16 +82,6 @@
static final String TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE =
"textclassifier_service_package_override";
- /**
- * Whether to use the default system text classifier as the default text classifier
- * implementation. The local text classifier is used if it is {@code false}.
- *
- * @see android.service.textclassifier.TextClassifierService#getDefaultTextClassifierImplementation(Context)
- */
- // TODO: Once the system health experiment is done, remove this together with local TC.
- private static final String USE_DEFAULT_SYSTEM_TEXT_CLASSIFIER_AS_DEFAULT_IMPL =
- "use_default_system_text_classifier_as_default_impl";
-
private static final String DEFAULT_TEXT_CLASSIFIER_SERVICE_PACKAGE_OVERRIDE = null;
private static final boolean LOCAL_TEXT_CLASSIFIER_ENABLED_DEFAULT = true;
private static final boolean SYSTEM_TEXT_CLASSIFIER_ENABLED_DEFAULT = true;
@@ -186,42 +90,7 @@
private static final boolean SMART_TEXT_SHARE_ENABLED_DEFAULT = true;
private static final boolean SMART_LINKIFY_ENABLED_DEFAULT = true;
private static final boolean SMART_SELECT_ANIMATION_ENABLED_DEFAULT = true;
- private static final int SUGGEST_SELECTION_MAX_RANGE_LENGTH_DEFAULT = 10 * 1000;
- private static final int CLASSIFY_TEXT_MAX_RANGE_LENGTH_DEFAULT = 10 * 1000;
private static final int GENERATE_LINKS_MAX_TEXT_LENGTH_DEFAULT = 100 * 1000;
- private static final int GENERATE_LINKS_LOG_SAMPLE_RATE_DEFAULT = 100;
- private static final List<String> ENTITY_LIST_DEFAULT_VALUE = Arrays.asList(
- TextClassifier.TYPE_ADDRESS,
- TextClassifier.TYPE_EMAIL,
- TextClassifier.TYPE_PHONE,
- TextClassifier.TYPE_URL,
- TextClassifier.TYPE_DATE,
- TextClassifier.TYPE_DATE_TIME,
- TextClassifier.TYPE_FLIGHT_NUMBER);
- private static final List<String> CONVERSATION_ACTIONS_TYPES_DEFAULT_VALUES = Arrays.asList(
- ConversationAction.TYPE_TEXT_REPLY,
- ConversationAction.TYPE_CREATE_REMINDER,
- ConversationAction.TYPE_CALL_PHONE,
- ConversationAction.TYPE_OPEN_URL,
- ConversationAction.TYPE_SEND_EMAIL,
- ConversationAction.TYPE_SEND_SMS,
- ConversationAction.TYPE_TRACK_FLIGHT,
- ConversationAction.TYPE_VIEW_CALENDAR,
- ConversationAction.TYPE_VIEW_MAP,
- ConversationAction.TYPE_ADD_CONTACT,
- ConversationAction.TYPE_COPY);
- /**
- * < 0 : Not set. Use value from LangId model.
- * 0 - 1: Override value in LangId model.
- *
- * @see EntityConfidence
- */
- private static final float LANG_ID_THRESHOLD_OVERRIDE_DEFAULT = -1f;
- private static final boolean TEMPLATE_INTENT_FACTORY_ENABLED_DEFAULT = true;
- private static final boolean TRANSLATE_IN_CLASSIFICATION_ENABLED_DEFAULT = true;
- private static final boolean DETECT_LANGUAGES_FROM_TEXT_ENABLED_DEFAULT = true;
- private static final float[] LANG_ID_CONTEXT_SETTINGS_DEFAULT = new float[]{20f, 1.0f, 0.4f};
- private static final boolean USE_DEFAULT_SYSTEM_TEXT_CLASSIFIER_AS_DEFAULT_IMPL_DEFAULT = true;
@Nullable
public String getTextClassifierServicePackageOverride() {
@@ -266,119 +135,20 @@
SMART_SELECT_ANIMATION_ENABLED, SMART_SELECT_ANIMATION_ENABLED_DEFAULT);
}
- public int getSuggestSelectionMaxRangeLength() {
- return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- SUGGEST_SELECTION_MAX_RANGE_LENGTH, SUGGEST_SELECTION_MAX_RANGE_LENGTH_DEFAULT);
- }
-
- public int getClassifyTextMaxRangeLength() {
- return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- CLASSIFY_TEXT_MAX_RANGE_LENGTH, CLASSIFY_TEXT_MAX_RANGE_LENGTH_DEFAULT);
- }
-
public int getGenerateLinksMaxTextLength() {
return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
GENERATE_LINKS_MAX_TEXT_LENGTH, GENERATE_LINKS_MAX_TEXT_LENGTH_DEFAULT);
}
- public int getGenerateLinksLogSampleRate() {
- return DeviceConfig.getInt(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- GENERATE_LINKS_LOG_SAMPLE_RATE, GENERATE_LINKS_LOG_SAMPLE_RATE_DEFAULT);
- }
-
- public List<String> getEntityListDefault() {
- return getDeviceConfigStringList(ENTITY_LIST_DEFAULT, ENTITY_LIST_DEFAULT_VALUE);
- }
-
- public List<String> getEntityListNotEditable() {
- return getDeviceConfigStringList(ENTITY_LIST_NOT_EDITABLE, ENTITY_LIST_DEFAULT_VALUE);
- }
-
- public List<String> getEntityListEditable() {
- return getDeviceConfigStringList(ENTITY_LIST_EDITABLE, ENTITY_LIST_DEFAULT_VALUE);
- }
-
- public List<String> getInAppConversationActionTypes() {
- return getDeviceConfigStringList(
- IN_APP_CONVERSATION_ACTION_TYPES_DEFAULT,
- CONVERSATION_ACTIONS_TYPES_DEFAULT_VALUES);
- }
-
- public List<String> getNotificationConversationActionTypes() {
- return getDeviceConfigStringList(
- NOTIFICATION_CONVERSATION_ACTION_TYPES_DEFAULT,
- CONVERSATION_ACTIONS_TYPES_DEFAULT_VALUES);
- }
-
- public float getLangIdThresholdOverride() {
- return DeviceConfig.getFloat(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- LANG_ID_THRESHOLD_OVERRIDE,
- LANG_ID_THRESHOLD_OVERRIDE_DEFAULT);
- }
-
- public boolean isTemplateIntentFactoryEnabled() {
- return DeviceConfig.getBoolean(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- TEMPLATE_INTENT_FACTORY_ENABLED,
- TEMPLATE_INTENT_FACTORY_ENABLED_DEFAULT);
- }
-
- public boolean isTranslateInClassificationEnabled() {
- return DeviceConfig.getBoolean(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- TRANSLATE_IN_CLASSIFICATION_ENABLED,
- TRANSLATE_IN_CLASSIFICATION_ENABLED_DEFAULT);
- }
-
- public boolean isDetectLanguagesFromTextEnabled() {
- return DeviceConfig.getBoolean(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- DETECT_LANGUAGES_FROM_TEXT_ENABLED,
- DETECT_LANGUAGES_FROM_TEXT_ENABLED_DEFAULT);
- }
-
- public float[] getLangIdContextSettings() {
- return getDeviceConfigFloatArray(
- LANG_ID_CONTEXT_SETTINGS, LANG_ID_CONTEXT_SETTINGS_DEFAULT);
- }
-
- public boolean getUseDefaultTextClassifierAsDefaultImplementation() {
- return DeviceConfig.getBoolean(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- USE_DEFAULT_SYSTEM_TEXT_CLASSIFIER_AS_DEFAULT_IMPL,
- USE_DEFAULT_SYSTEM_TEXT_CLASSIFIER_AS_DEFAULT_IMPL_DEFAULT);
- }
-
void dump(IndentingPrintWriter pw) {
pw.println("TextClassificationConstants:");
pw.increaseIndent();
- pw.printPair("classify_text_max_range_length", getClassifyTextMaxRangeLength())
- .println();
- pw.printPair("detect_languages_from_text_enabled", isDetectLanguagesFromTextEnabled())
- .println();
- pw.printPair("entity_list_default", getEntityListDefault())
- .println();
- pw.printPair("entity_list_editable", getEntityListEditable())
- .println();
- pw.printPair("entity_list_not_editable", getEntityListNotEditable())
- .println();
- pw.printPair("generate_links_log_sample_rate", getGenerateLinksLogSampleRate())
- .println();
pw.printPair("generate_links_max_text_length", getGenerateLinksMaxTextLength())
.println();
- pw.printPair("in_app_conversation_action_types_default", getInAppConversationActionTypes())
- .println();
- pw.printPair("lang_id_context_settings", Arrays.toString(getLangIdContextSettings()))
- .println();
- pw.printPair("lang_id_threshold_override", getLangIdThresholdOverride())
- .println();
pw.printPair("local_textclassifier_enabled", isLocalTextClassifierEnabled())
.println();
pw.printPair("model_dark_launch_enabled", isModelDarkLaunchEnabled())
.println();
- pw.printPair("notification_conversation_action_types_default",
- getNotificationConversationActionTypes()).println();
pw.printPair("smart_linkify_enabled", isSmartLinkifyEnabled())
.println();
pw.printPair("smart_select_animation_enabled", isSmartSelectionAnimationEnabled())
@@ -387,57 +157,10 @@
.println();
pw.printPair("smart_text_share_enabled", isSmartTextShareEnabled())
.println();
- pw.printPair("suggest_selection_max_range_length", getSuggestSelectionMaxRangeLength())
- .println();
pw.printPair("system_textclassifier_enabled", isSystemTextClassifierEnabled())
.println();
- pw.printPair("template_intent_factory_enabled", isTemplateIntentFactoryEnabled())
- .println();
- pw.printPair("translate_in_classification_enabled", isTranslateInClassificationEnabled())
- .println();
pw.printPair("textclassifier_service_package_override",
getTextClassifierServicePackageOverride()).println();
- pw.printPair("use_default_system_text_classifier_as_default_impl",
- getUseDefaultTextClassifierAsDefaultImplementation()).println();
pw.decreaseIndent();
}
-
- private static List<String> getDeviceConfigStringList(String key, List<String> defaultValue) {
- return parse(
- DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
- defaultValue);
- }
-
- private static float[] getDeviceConfigFloatArray(String key, float[] defaultValue) {
- return parse(
- DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
- defaultValue);
- }
-
- private static List<String> parse(@Nullable String listStr, List<String> defaultValue) {
- if (listStr != null) {
- return Collections.unmodifiableList(Arrays.asList(listStr.split(DELIMITER)));
- }
- return defaultValue;
- }
-
- private static float[] parse(@Nullable String arrayStr, float[] defaultValue) {
- if (arrayStr != null) {
- final String[] split = arrayStr.split(DELIMITER);
- if (split.length != defaultValue.length) {
- return defaultValue;
- }
- final float[] result = new float[split.length];
- for (int i = 0; i < split.length; i++) {
- try {
- result[i] = Float.parseFloat(split[i]);
- } catch (NumberFormatException e) {
- return defaultValue;
- }
- }
- return result;
- } else {
- return defaultValue;
- }
- }
}
\ No newline at end of file
diff --git a/core/java/android/view/textclassifier/TextClassificationContext.java b/core/java/android/view/textclassifier/TextClassificationContext.java
index d58d175..f2323c6 100644
--- a/core/java/android/view/textclassifier/TextClassificationContext.java
+++ b/core/java/android/view/textclassifier/TextClassificationContext.java
@@ -18,10 +18,8 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.view.textclassifier.TextClassifier.WidgetType;
import java.util.Locale;
@@ -33,12 +31,11 @@
*/
public final class TextClassificationContext implements Parcelable {
- private final String mPackageName;
+ // NOTE: Modify packageName only in the constructor or in setSystemTextClassifierMetadata()
+ private String mPackageName;
private final String mWidgetType;
@Nullable private final String mWidgetVersion;
- @UserIdInt
- private int mUserId = UserHandle.USER_NULL;
- private boolean mUseDefaultTextClassifier;
+ private SystemTextClassifierMetadata mSystemTcMetadata;
private TextClassificationContext(
String packageName,
@@ -58,42 +55,26 @@
}
/**
- * Sets the id of this context's user.
- * <p>
- * Package-private for SystemTextClassifier's use.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
+ *
+ * <p><b>NOTE: </b>This will override the value returned in {@link getPackageName()}.
* @hide
*/
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
+ void setSystemTextClassifierMetadata(@Nullable SystemTextClassifierMetadata systemTcMetadata) {
+ mSystemTcMetadata = systemTcMetadata;
+ if (mSystemTcMetadata != null) {
+ mPackageName = mSystemTcMetadata.getCallingPackageName();
+ }
}
/**
- * Returns the id of this context's user.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
- }
-
- /**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
- *
- * @hide
- */
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
@@ -118,8 +99,8 @@
@Override
public String toString() {
return String.format(Locale.US, "TextClassificationContext{"
- + "packageName=%s, widgetType=%s, widgetVersion=%s, userId=%d}",
- mPackageName, mWidgetType, mWidgetVersion, mUserId);
+ + "packageName=%s, widgetType=%s, widgetVersion=%s, systemTcMetadata=%s}",
+ mPackageName, mWidgetType, mWidgetVersion, mSystemTcMetadata);
}
/**
@@ -176,16 +157,14 @@
parcel.writeString(mPackageName);
parcel.writeString(mWidgetType);
parcel.writeString(mWidgetVersion);
- parcel.writeInt(mUserId);
- parcel.writeBoolean(mUseDefaultTextClassifier);
+ parcel.writeParcelable(mSystemTcMetadata, flags);
}
private TextClassificationContext(Parcel in) {
mPackageName = in.readString();
mWidgetType = in.readString();
mWidgetVersion = in.readString();
- mUserId = in.readInt();
- mUseDefaultTextClassifier = in.readBoolean();
+ mSystemTcMetadata = in.readParcelable(null);
}
public static final @android.annotation.NonNull Parcelable.Creator<TextClassificationContext> CREATOR =
diff --git a/core/java/android/view/textclassifier/TextClassificationManager.java b/core/java/android/view/textclassifier/TextClassificationManager.java
index dfbec9b..fa4f7d6 100644
--- a/core/java/android/view/textclassifier/TextClassificationManager.java
+++ b/core/java/android/view/textclassifier/TextClassificationManager.java
@@ -19,21 +19,15 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemService;
-import android.app.ActivityThread;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.ServiceManager;
-import android.provider.DeviceConfig;
-import android.provider.DeviceConfig.Properties;
import android.view.textclassifier.TextClassifier.TextClassifierType;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
-import java.lang.ref.WeakReference;
import java.util.Objects;
-import java.util.Set;
/**
* Interface to the text classification service.
@@ -41,7 +35,7 @@
@SystemService(Context.TEXT_CLASSIFICATION_SERVICE)
public final class TextClassificationManager {
- private static final String LOG_TAG = "TextClassificationManager";
+ private static final String LOG_TAG = TextClassifier.LOG_TAG;
private static final TextClassificationConstants sDefaultSettings =
new TextClassificationConstants();
@@ -52,15 +46,11 @@
classificationContext, getTextClassifier());
private final Context mContext;
- private final SettingsObserver mSettingsObserver;
@GuardedBy("mLock")
@Nullable
private TextClassifier mCustomTextClassifier;
@GuardedBy("mLock")
- @Nullable
- private TextClassifier mLocalTextClassifier;
- @GuardedBy("mLock")
private TextClassificationSessionFactory mSessionFactory;
@GuardedBy("mLock")
private TextClassificationConstants mSettings;
@@ -69,7 +59,6 @@
public TextClassificationManager(Context context) {
mContext = Objects.requireNonNull(context);
mSessionFactory = mDefaultSessionFactory;
- mSettingsObserver = new SettingsObserver(this);
}
/**
@@ -112,7 +101,7 @@
*
* @see TextClassifier#LOCAL
* @see TextClassifier#SYSTEM
- * @see TextClassifier#DEFAULT_SERVICE
+ * @see TextClassifier#DEFAULT_SYSTEM
* @hide
*/
@UnsupportedAppUsage
@@ -189,28 +178,17 @@
}
}
- @Override
- protected void finalize() throws Throwable {
- try {
- // Note that fields could be null if the constructor threw.
- if (mSettingsObserver != null) {
- DeviceConfig.removeOnPropertiesChangedListener(mSettingsObserver);
- }
- } finally {
- super.finalize();
- }
- }
-
/** @hide */
private TextClassifier getSystemTextClassifier(@TextClassifierType int type) {
synchronized (mLock) {
if (getSettings().isSystemTextClassifierEnabled()) {
try {
- Log.d(LOG_TAG, "Initializing SystemTextClassifier, type = " + type);
+ Log.d(LOG_TAG, "Initializing SystemTextClassifier, type = "
+ + TextClassifier.typeToString(type));
return new SystemTextClassifier(
mContext,
getSettings(),
- /* useDefault= */ type == TextClassifier.DEFAULT_SERVICE);
+ /* useDefault= */ type == TextClassifier.DEFAULT_SYSTEM);
} catch (ServiceManager.ServiceNotFoundException e) {
Log.e(LOG_TAG, "Could not initialize SystemTextClassifier", e);
}
@@ -224,49 +202,13 @@
*/
@NonNull
private TextClassifier getLocalTextClassifier() {
- synchronized (mLock) {
- if (mLocalTextClassifier == null) {
- if (getSettings().isLocalTextClassifierEnabled()) {
- mLocalTextClassifier =
- new TextClassifierImpl(mContext, getSettings(), TextClassifier.NO_OP);
- } else {
- Log.d(LOG_TAG, "Local TextClassifier disabled");
- mLocalTextClassifier = TextClassifier.NO_OP;
- }
- }
- return mLocalTextClassifier;
- }
- }
-
- /** @hide */
- @VisibleForTesting
- public void invalidateForTesting() {
- invalidate();
- }
-
- private void invalidate() {
- synchronized (mLock) {
- mSettings = null;
- invalidateTextClassifiers();
- }
- }
-
- private void invalidateTextClassifiers() {
- synchronized (mLock) {
- mLocalTextClassifier = null;
- }
- }
-
- Context getApplicationContext() {
- return mContext.getApplicationContext() != null
- ? mContext.getApplicationContext()
- : mContext;
+ Log.d(LOG_TAG, "Local text-classifier not supported. Returning a no-op text-classifier.");
+ return TextClassifier.NO_OP;
}
/** @hide **/
public void dump(IndentingPrintWriter pw) {
- getLocalTextClassifier().dump(pw);
- getSystemTextClassifier(TextClassifier.DEFAULT_SERVICE).dump(pw);
+ getSystemTextClassifier(TextClassifier.DEFAULT_SYSTEM).dump(pw);
getSystemTextClassifier(TextClassifier.SYSTEM).dump(pw);
getSettings().dump(pw);
}
@@ -283,31 +225,4 @@
return sDefaultSettings;
}
}
-
- private static final class SettingsObserver implements
- DeviceConfig.OnPropertiesChangedListener {
-
- private final WeakReference<TextClassificationManager> mTcm;
-
- SettingsObserver(TextClassificationManager tcm) {
- mTcm = new WeakReference<>(tcm);
- DeviceConfig.addOnPropertiesChangedListener(
- DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- ActivityThread.currentApplication().getMainExecutor(),
- this);
- }
-
- @Override
- public void onPropertiesChanged(Properties properties) {
- final TextClassificationManager tcm = mTcm.get();
- if (tcm != null) {
- final Set<String> keys = properties.getKeyset();
- if (keys.contains(TextClassificationConstants.SYSTEM_TEXT_CLASSIFIER_ENABLED)
- || keys.contains(
- TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED)) {
- tcm.invalidateTextClassifiers();
- }
- }
- }
- }
}
diff --git a/core/java/android/view/textclassifier/TextClassifier.java b/core/java/android/view/textclassifier/TextClassifier.java
index 2cc226d..6d5077a 100644
--- a/core/java/android/view/textclassifier/TextClassifier.java
+++ b/core/java/android/view/textclassifier/TextClassifier.java
@@ -61,19 +61,32 @@
public interface TextClassifier {
/** @hide */
- String DEFAULT_LOG_TAG = "androidtc";
+ String LOG_TAG = "androidtc";
/** @hide */
@Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {LOCAL, SYSTEM, DEFAULT_SERVICE})
+ @IntDef(value = {LOCAL, SYSTEM, DEFAULT_SYSTEM})
@interface TextClassifierType {} // TODO: Expose as system APIs.
/** Specifies a TextClassifier that runs locally in the app's process. @hide */
int LOCAL = 0;
/** Specifies a TextClassifier that runs in the system process and serves all apps. @hide */
int SYSTEM = 1;
/** Specifies the default TextClassifier that runs in the system process. @hide */
- int DEFAULT_SERVICE = 2;
+ int DEFAULT_SYSTEM = 2;
+
+ /** @hide */
+ static String typeToString(@TextClassifierType int type) {
+ switch (type) {
+ case LOCAL:
+ return "Local";
+ case SYSTEM:
+ return "System";
+ case DEFAULT_SYSTEM:
+ return "Default system";
+ }
+ return "Unknown";
+ }
/** The TextClassifier failed to run. */
String TYPE_UNKNOWN = "";
@@ -776,7 +789,7 @@
static void checkMainThread() {
if (Looper.myLooper() == Looper.getMainLooper()) {
- Log.w(DEFAULT_LOG_TAG, "TextClassifier called on main thread");
+ Log.w(LOG_TAG, "TextClassifier called on main thread");
}
}
}
diff --git a/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java b/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
deleted file mode 100644
index 8162699..0000000
--- a/core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier;
-
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXTCLASSIFIER_MODEL;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SCORE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SECOND_ENTITY_TYPE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SESSION_ID;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_THIRD_ENTITY_TYPE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_WIDGET_TYPE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_WIDGET_VERSION;
-
-import android.metrics.LogMaker;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import java.util.Objects;
-
-
-/**
- * Log {@link TextClassifierEvent} by using Tron, only support language detection and
- * conversation actions.
- *
- * @hide
- */
-public final class TextClassifierEventTronLogger {
-
- private static final String TAG = "TCEventTronLogger";
-
- private final MetricsLogger mMetricsLogger;
-
- public TextClassifierEventTronLogger() {
- this(new MetricsLogger());
- }
-
- @VisibleForTesting
- public TextClassifierEventTronLogger(MetricsLogger metricsLogger) {
- mMetricsLogger = Objects.requireNonNull(metricsLogger);
- }
-
- /** Emits a text classifier event to the logs. */
- public void writeEvent(TextClassifierEvent event) {
- Objects.requireNonNull(event);
-
- int category = getCategory(event);
- if (category == -1) {
- Log.w(TAG, "Unknown category: " + event.getEventCategory());
- return;
- }
- final LogMaker log = new LogMaker(category)
- .setSubtype(getLogType(event))
- .addTaggedData(FIELD_TEXT_CLASSIFIER_SESSION_ID, event.getResultId())
- .addTaggedData(FIELD_TEXTCLASSIFIER_MODEL, getModelName(event));
- if (event.getScores().length >= 1) {
- log.addTaggedData(FIELD_TEXT_CLASSIFIER_SCORE, event.getScores()[0]);
- }
- String[] entityTypes = event.getEntityTypes();
- // The old logger does not support a field of list type, and thus workaround by store them
- // in three separate fields. This is not an issue with the new logger.
- if (entityTypes.length >= 1) {
- log.addTaggedData(FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE, entityTypes[0]);
- }
- if (entityTypes.length >= 2) {
- log.addTaggedData(FIELD_TEXT_CLASSIFIER_SECOND_ENTITY_TYPE, entityTypes[1]);
- }
- if (entityTypes.length >= 3) {
- log.addTaggedData(FIELD_TEXT_CLASSIFIER_THIRD_ENTITY_TYPE, entityTypes[2]);
- }
- TextClassificationContext eventContext = event.getEventContext();
- if (eventContext != null) {
- log.addTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_TYPE, eventContext.getWidgetType());
- log.addTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_VERSION,
- eventContext.getWidgetVersion());
- log.setPackageName(eventContext.getPackageName());
- }
- mMetricsLogger.write(log);
- debugLog(log);
- }
-
- private static String getModelName(TextClassifierEvent event) {
- if (event.getModelName() != null) {
- return event.getModelName();
- }
- return SelectionSessionLogger.SignatureParser.getModelName(event.getResultId());
- }
-
- private static int getCategory(TextClassifierEvent event) {
- switch (event.getEventCategory()) {
- case TextClassifierEvent.CATEGORY_CONVERSATION_ACTIONS:
- return MetricsEvent.CONVERSATION_ACTIONS;
- case TextClassifierEvent.CATEGORY_LANGUAGE_DETECTION:
- return MetricsEvent.LANGUAGE_DETECTION;
- }
- return -1;
- }
-
- private static int getLogType(TextClassifierEvent event) {
- switch (event.getEventType()) {
- case TextClassifierEvent.TYPE_SMART_ACTION:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE;
- case TextClassifierEvent.TYPE_ACTIONS_SHOWN:
- return MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_SHOWN;
- case TextClassifierEvent.TYPE_MANUAL_REPLY:
- return MetricsEvent.ACTION_TEXT_CLASSIFIER_MANUAL_REPLY;
- case TextClassifierEvent.TYPE_ACTIONS_GENERATED:
- return MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_GENERATED;
- default:
- return MetricsEvent.VIEW_UNKNOWN;
- }
- }
-
- private String toCategoryName(int category) {
- switch (category) {
- case MetricsEvent.CONVERSATION_ACTIONS:
- return "conversation_actions";
- case MetricsEvent.LANGUAGE_DETECTION:
- return "language_detection";
- }
- return "unknown";
- }
-
- private String toEventName(int logType) {
- switch (logType) {
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE:
- return "smart_share";
- case MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_SHOWN:
- return "actions_shown";
- case MetricsEvent.ACTION_TEXT_CLASSIFIER_MANUAL_REPLY:
- return "manual_reply";
- case MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_GENERATED:
- return "actions_generated";
- }
- return "unknown";
- }
-
- private void debugLog(LogMaker log) {
- if (!Log.ENABLE_FULL_LOGGING) {
- return;
- }
- final String id = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_SESSION_ID));
- final String categoryName = toCategoryName(log.getCategory());
- final String eventName = toEventName(log.getSubtype());
- final String widgetType =
- String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_TYPE));
- final String widgetVersion =
- String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_VERSION));
- final String model = String.valueOf(log.getTaggedData(FIELD_TEXTCLASSIFIER_MODEL));
- final String firstEntityType =
- String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE));
- final String secondEntityType =
- String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_SECOND_ENTITY_TYPE));
- final String thirdEntityType =
- String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_THIRD_ENTITY_TYPE));
- final String score =
- String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_SCORE));
-
- StringBuilder builder = new StringBuilder();
- builder.append("writeEvent: ");
- builder.append("id=").append(id);
- builder.append(", category=").append(categoryName);
- builder.append(", eventName=").append(eventName);
- builder.append(", widgetType=").append(widgetType);
- builder.append(", widgetVersion=").append(widgetVersion);
- builder.append(", model=").append(model);
- builder.append(", firstEntityType=").append(firstEntityType);
- builder.append(", secondEntityType=").append(secondEntityType);
- builder.append(", thirdEntityType=").append(thirdEntityType);
- builder.append(", score=").append(score);
-
- Log.v(TAG, builder.toString());
- }
-}
diff --git a/core/java/android/view/textclassifier/TextClassifierImpl.java b/core/java/android/view/textclassifier/TextClassifierImpl.java
deleted file mode 100644
index d7149ee..0000000
--- a/core/java/android/view/textclassifier/TextClassifierImpl.java
+++ /dev/null
@@ -1,911 +0,0 @@
-/*
- * Copyright (C) 2017 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.view.textclassifier;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.WorkerThread;
-import android.app.RemoteAction;
-import android.content.Context;
-import android.content.Intent;
-import android.icu.util.ULocale;
-import android.os.Bundle;
-import android.os.LocaleList;
-import android.os.ParcelFileDescriptor;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import android.util.Pair;
-import android.view.textclassifier.ActionsModelParamsSupplier.ActionsModelParams;
-import android.view.textclassifier.intent.ClassificationIntentFactory;
-import android.view.textclassifier.intent.LabeledIntent;
-import android.view.textclassifier.intent.LegacyClassificationIntentFactory;
-import android.view.textclassifier.intent.TemplateClassificationIntentFactory;
-import android.view.textclassifier.intent.TemplateIntentFactory;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.util.IndentingPrintWriter;
-import com.android.internal.util.Preconditions;
-
-import com.google.android.textclassifier.ActionsSuggestionsModel;
-import com.google.android.textclassifier.AnnotatorModel;
-import com.google.android.textclassifier.LangIdModel;
-import com.google.android.textclassifier.LangIdModel.LanguageResult;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.time.Instant;
-import java.time.ZonedDateTime;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.function.Supplier;
-
-/**
- * Default implementation of the {@link TextClassifier} interface.
- *
- * <p>This class uses machine learning to recognize entities in text.
- * Unless otherwise stated, methods of this class are blocking operations and should most
- * likely not be called on the UI thread.
- *
- * @hide
- */
-public final class TextClassifierImpl implements TextClassifier {
-
- private static final String LOG_TAG = DEFAULT_LOG_TAG;
-
- private static final boolean DEBUG = false;
-
- private static final File FACTORY_MODEL_DIR = new File("/etc/textclassifier/");
- // Annotator
- private static final String ANNOTATOR_FACTORY_MODEL_FILENAME_REGEX =
- "textclassifier\\.(.*)\\.model";
- private static final File ANNOTATOR_UPDATED_MODEL_FILE =
- new File("/data/misc/textclassifier/textclassifier.model");
-
- // LangID
- private static final String LANG_ID_FACTORY_MODEL_FILENAME_REGEX = "lang_id.model";
- private static final File UPDATED_LANG_ID_MODEL_FILE =
- new File("/data/misc/textclassifier/lang_id.model");
-
- // Actions
- private static final String ACTIONS_FACTORY_MODEL_FILENAME_REGEX =
- "actions_suggestions\\.(.*)\\.model";
- private static final File UPDATED_ACTIONS_MODEL =
- new File("/data/misc/textclassifier/actions_suggestions.model");
-
- private final Context mContext;
- private final TextClassifier mFallback;
- private final GenerateLinksLogger mGenerateLinksLogger;
-
- private final Object mLock = new Object();
-
- @GuardedBy("mLock")
- private ModelFileManager.ModelFile mAnnotatorModelInUse;
- @GuardedBy("mLock")
- private AnnotatorModel mAnnotatorImpl;
-
- @GuardedBy("mLock")
- private ModelFileManager.ModelFile mLangIdModelInUse;
- @GuardedBy("mLock")
- private LangIdModel mLangIdImpl;
-
- @GuardedBy("mLock")
- private ModelFileManager.ModelFile mActionModelInUse;
- @GuardedBy("mLock")
- private ActionsSuggestionsModel mActionsImpl;
-
- private final SelectionSessionLogger mSessionLogger = new SelectionSessionLogger();
- private final TextClassifierEventTronLogger mTextClassifierEventTronLogger =
- new TextClassifierEventTronLogger();
-
- private final TextClassificationConstants mSettings;
-
- private final ModelFileManager mAnnotatorModelFileManager;
- private final ModelFileManager mLangIdModelFileManager;
- private final ModelFileManager mActionsModelFileManager;
-
- private final ClassificationIntentFactory mClassificationIntentFactory;
- private final TemplateIntentFactory mTemplateIntentFactory;
- private final Supplier<ActionsModelParams> mActionsModelParamsSupplier;
-
- public TextClassifierImpl(
- Context context, TextClassificationConstants settings, TextClassifier fallback) {
- mContext = Objects.requireNonNull(context);
- mFallback = Objects.requireNonNull(fallback);
- mSettings = Objects.requireNonNull(settings);
- mGenerateLinksLogger = new GenerateLinksLogger(mSettings.getGenerateLinksLogSampleRate());
- mAnnotatorModelFileManager = new ModelFileManager(
- new ModelFileManager.ModelFileSupplierImpl(
- FACTORY_MODEL_DIR,
- ANNOTATOR_FACTORY_MODEL_FILENAME_REGEX,
- ANNOTATOR_UPDATED_MODEL_FILE,
- AnnotatorModel::getVersion,
- AnnotatorModel::getLocales));
- mLangIdModelFileManager = new ModelFileManager(
- new ModelFileManager.ModelFileSupplierImpl(
- FACTORY_MODEL_DIR,
- LANG_ID_FACTORY_MODEL_FILENAME_REGEX,
- UPDATED_LANG_ID_MODEL_FILE,
- LangIdModel::getVersion,
- fd -> ModelFileManager.ModelFile.LANGUAGE_INDEPENDENT));
- mActionsModelFileManager = new ModelFileManager(
- new ModelFileManager.ModelFileSupplierImpl(
- FACTORY_MODEL_DIR,
- ACTIONS_FACTORY_MODEL_FILENAME_REGEX,
- UPDATED_ACTIONS_MODEL,
- ActionsSuggestionsModel::getVersion,
- ActionsSuggestionsModel::getLocales));
-
- mTemplateIntentFactory = new TemplateIntentFactory();
- mClassificationIntentFactory = mSettings.isTemplateIntentFactoryEnabled()
- ? new TemplateClassificationIntentFactory(
- mTemplateIntentFactory, new LegacyClassificationIntentFactory())
- : new LegacyClassificationIntentFactory();
- mActionsModelParamsSupplier = new ActionsModelParamsSupplier(mContext,
- () -> {
- synchronized (mLock) {
- // Clear mActionsImpl here, so that we will create a new
- // ActionsSuggestionsModel object with the new flag in the next request.
- mActionsImpl = null;
- mActionModelInUse = null;
- }
- });
- }
-
- public TextClassifierImpl(Context context, TextClassificationConstants settings) {
- this(context, settings, TextClassifier.NO_OP);
- }
-
- /** @inheritDoc */
- @Override
- @WorkerThread
- public TextSelection suggestSelection(TextSelection.Request request) {
- Objects.requireNonNull(request);
- Utils.checkMainThread();
- try {
- final int rangeLength = request.getEndIndex() - request.getStartIndex();
- final String string = request.getText().toString();
- if (string.length() > 0
- && rangeLength <= mSettings.getSuggestSelectionMaxRangeLength()) {
- final String localesString = concatenateLocales(request.getDefaultLocales());
- final String detectLanguageTags = detectLanguageTagsFromText(request.getText());
- final ZonedDateTime refTime = ZonedDateTime.now();
- final AnnotatorModel annotatorImpl = getAnnotatorImpl(request.getDefaultLocales());
- final int start;
- final int end;
- if (mSettings.isModelDarkLaunchEnabled() && !request.isDarkLaunchAllowed()) {
- start = request.getStartIndex();
- end = request.getEndIndex();
- } else {
- final int[] startEnd = annotatorImpl.suggestSelection(
- string, request.getStartIndex(), request.getEndIndex(),
- new AnnotatorModel.SelectionOptions(localesString, detectLanguageTags));
- start = startEnd[0];
- end = startEnd[1];
- }
- if (start < end
- && start >= 0 && end <= string.length()
- && start <= request.getStartIndex() && end >= request.getEndIndex()) {
- final TextSelection.Builder tsBuilder = new TextSelection.Builder(start, end);
- final AnnotatorModel.ClassificationResult[] results =
- annotatorImpl.classifyText(
- string, start, end,
- new AnnotatorModel.ClassificationOptions(
- refTime.toInstant().toEpochMilli(),
- refTime.getZone().getId(),
- localesString,
- detectLanguageTags),
- // Passing null here to suppress intent generation
- // TODO: Use an explicit flag to suppress it.
- /* appContext */ null,
- /* deviceLocales */null);
- final int size = results.length;
- for (int i = 0; i < size; i++) {
- tsBuilder.setEntityType(results[i].getCollection(), results[i].getScore());
- }
- return tsBuilder.setId(createId(
- string, request.getStartIndex(), request.getEndIndex()))
- .build();
- } else {
- // We can not trust the result. Log the issue and ignore the result.
- Log.d(LOG_TAG, "Got bad indices for input text. Ignoring result.");
- }
- }
- } catch (Throwable t) {
- // Avoid throwing from this method. Log the error.
- Log.e(LOG_TAG,
- "Error suggesting selection for text. No changes to selection suggested.",
- t);
- }
- // Getting here means something went wrong, return a NO_OP result.
- return mFallback.suggestSelection(request);
- }
-
- /** @inheritDoc */
- @Override
- @WorkerThread
- public TextClassification classifyText(TextClassification.Request request) {
- Objects.requireNonNull(request);
- Utils.checkMainThread();
- try {
- final int rangeLength = request.getEndIndex() - request.getStartIndex();
- final String string = request.getText().toString();
- if (string.length() > 0 && rangeLength <= mSettings.getClassifyTextMaxRangeLength()) {
- final String localesString = concatenateLocales(request.getDefaultLocales());
- final String detectLanguageTags = detectLanguageTagsFromText(request.getText());
- final ZonedDateTime refTime = request.getReferenceTime() != null
- ? request.getReferenceTime() : ZonedDateTime.now();
- final AnnotatorModel.ClassificationResult[] results =
- getAnnotatorImpl(request.getDefaultLocales())
- .classifyText(
- string, request.getStartIndex(), request.getEndIndex(),
- new AnnotatorModel.ClassificationOptions(
- refTime.toInstant().toEpochMilli(),
- refTime.getZone().getId(),
- localesString,
- detectLanguageTags),
- mContext,
- getResourceLocalesString()
- );
- if (results.length > 0) {
- return createClassificationResult(
- results, string,
- request.getStartIndex(), request.getEndIndex(), refTime.toInstant());
- }
- }
- } catch (Throwable t) {
- // Avoid throwing from this method. Log the error.
- Log.e(LOG_TAG, "Error getting text classification info.", t);
- }
- // Getting here means something went wrong, return a NO_OP result.
- return mFallback.classifyText(request);
- }
-
- /** @inheritDoc */
- @Override
- @WorkerThread
- public TextLinks generateLinks(@NonNull TextLinks.Request request) {
- Objects.requireNonNull(request);
- Utils.checkMainThread();
- if (!Utils.checkTextLength(request.getText(), getMaxGenerateLinksTextLength())) {
- return mFallback.generateLinks(request);
- }
-
- if (!mSettings.isSmartLinkifyEnabled() && request.isLegacyFallback()) {
- return Utils.generateLegacyLinks(request);
- }
-
- final String textString = request.getText().toString();
- final TextLinks.Builder builder = new TextLinks.Builder(textString);
-
- try {
- final long startTimeMs = System.currentTimeMillis();
- final ZonedDateTime refTime = ZonedDateTime.now();
- final Collection<String> entitiesToIdentify = request.getEntityConfig() != null
- ? request.getEntityConfig().resolveEntityListModifications(
- getEntitiesForHints(request.getEntityConfig().getHints()))
- : mSettings.getEntityListDefault();
- final String localesString = concatenateLocales(request.getDefaultLocales());
- final String detectLanguageTags = detectLanguageTagsFromText(request.getText());
- final AnnotatorModel annotatorImpl =
- getAnnotatorImpl(request.getDefaultLocales());
- final boolean isSerializedEntityDataEnabled =
- ExtrasUtils.isSerializedEntityDataEnabled(request);
- final AnnotatorModel.AnnotatedSpan[] annotations =
- annotatorImpl.annotate(
- textString,
- new AnnotatorModel.AnnotationOptions(
- refTime.toInstant().toEpochMilli(),
- refTime.getZone().getId(),
- localesString,
- detectLanguageTags,
- entitiesToIdentify,
- AnnotatorModel.AnnotationUsecase.SMART.getValue(),
- isSerializedEntityDataEnabled));
- for (AnnotatorModel.AnnotatedSpan span : annotations) {
- final AnnotatorModel.ClassificationResult[] results =
- span.getClassification();
- if (results.length == 0
- || !entitiesToIdentify.contains(results[0].getCollection())) {
- continue;
- }
- final Map<String, Float> entityScores = new ArrayMap<>();
- for (int i = 0; i < results.length; i++) {
- entityScores.put(results[i].getCollection(), results[i].getScore());
- }
- Bundle extras = new Bundle();
- if (isSerializedEntityDataEnabled) {
- ExtrasUtils.putEntities(extras, results);
- }
- builder.addLink(span.getStartIndex(), span.getEndIndex(), entityScores, extras);
- }
- final TextLinks links = builder.build();
- final long endTimeMs = System.currentTimeMillis();
- final String callingPackageName = request.getCallingPackageName() == null
- ? mContext.getPackageName() // local (in process) TC.
- : request.getCallingPackageName();
- mGenerateLinksLogger.logGenerateLinks(
- request.getText(), links, callingPackageName, endTimeMs - startTimeMs);
- return links;
- } catch (Throwable t) {
- // Avoid throwing from this method. Log the error.
- Log.e(LOG_TAG, "Error getting links info.", t);
- }
- return mFallback.generateLinks(request);
- }
-
- /** @inheritDoc */
- @Override
- public int getMaxGenerateLinksTextLength() {
- return mSettings.getGenerateLinksMaxTextLength();
- }
-
- private Collection<String> getEntitiesForHints(Collection<String> hints) {
- final boolean editable = hints.contains(HINT_TEXT_IS_EDITABLE);
- final boolean notEditable = hints.contains(HINT_TEXT_IS_NOT_EDITABLE);
-
- // Use the default if there is no hint, or conflicting ones.
- final boolean useDefault = editable == notEditable;
- if (useDefault) {
- return mSettings.getEntityListDefault();
- } else if (editable) {
- return mSettings.getEntityListEditable();
- } else { // notEditable
- return mSettings.getEntityListNotEditable();
- }
- }
-
- /** @inheritDoc */
- @Override
- public void onSelectionEvent(SelectionEvent event) {
- mSessionLogger.writeEvent(event);
- }
-
- @Override
- public void onTextClassifierEvent(TextClassifierEvent event) {
- if (DEBUG) {
- Log.d(DEFAULT_LOG_TAG, "onTextClassifierEvent() called with: event = [" + event + "]");
- }
- try {
- final SelectionEvent selEvent = event.toSelectionEvent();
- if (selEvent != null) {
- mSessionLogger.writeEvent(selEvent);
- } else {
- mTextClassifierEventTronLogger.writeEvent(event);
- }
- } catch (Exception e) {
- Log.e(LOG_TAG, "Error writing event", e);
- }
- }
-
- /** @inheritDoc */
- @Override
- public TextLanguage detectLanguage(@NonNull TextLanguage.Request request) {
- Objects.requireNonNull(request);
- Utils.checkMainThread();
- try {
- final TextLanguage.Builder builder = new TextLanguage.Builder();
- final LangIdModel.LanguageResult[] langResults =
- getLangIdImpl().detectLanguages(request.getText().toString());
- for (int i = 0; i < langResults.length; i++) {
- builder.putLocale(
- ULocale.forLanguageTag(langResults[i].getLanguage()),
- langResults[i].getScore());
- }
- return builder.build();
- } catch (Throwable t) {
- // Avoid throwing from this method. Log the error.
- Log.e(LOG_TAG, "Error detecting text language.", t);
- }
- return mFallback.detectLanguage(request);
- }
-
- @Override
- public ConversationActions suggestConversationActions(ConversationActions.Request request) {
- Objects.requireNonNull(request);
- Utils.checkMainThread();
- try {
- ActionsSuggestionsModel actionsImpl = getActionsImpl();
- if (actionsImpl == null) {
- // Actions model is optional, fallback if it is not available.
- return mFallback.suggestConversationActions(request);
- }
- ActionsSuggestionsModel.ConversationMessage[] nativeMessages =
- ActionsSuggestionsHelper.toNativeMessages(
- request.getConversation(), this::detectLanguageTagsFromText);
- if (nativeMessages.length == 0) {
- return mFallback.suggestConversationActions(request);
- }
- ActionsSuggestionsModel.Conversation nativeConversation =
- new ActionsSuggestionsModel.Conversation(nativeMessages);
-
- ActionsSuggestionsModel.ActionSuggestion[] nativeSuggestions =
- actionsImpl.suggestActionsWithIntents(
- nativeConversation,
- null,
- mContext,
- getResourceLocalesString(),
- getAnnotatorImpl(LocaleList.getDefault()));
- return createConversationActionResult(request, nativeSuggestions);
- } catch (Throwable t) {
- // Avoid throwing from this method. Log the error.
- Log.e(LOG_TAG, "Error suggesting conversation actions.", t);
- }
- return mFallback.suggestConversationActions(request);
- }
-
- /**
- * Returns the {@link ConversationAction} result, with a non-null extras.
- * <p>
- * Whenever the RemoteAction is non-null, you can expect its corresponding intent
- * with a non-null component name is in the extras.
- */
- private ConversationActions createConversationActionResult(
- ConversationActions.Request request,
- ActionsSuggestionsModel.ActionSuggestion[] nativeSuggestions) {
- Collection<String> expectedTypes = resolveActionTypesFromRequest(request);
- List<ConversationAction> conversationActions = new ArrayList<>();
- for (ActionsSuggestionsModel.ActionSuggestion nativeSuggestion : nativeSuggestions) {
- String actionType = nativeSuggestion.getActionType();
- if (!expectedTypes.contains(actionType)) {
- continue;
- }
- LabeledIntent.Result labeledIntentResult =
- ActionsSuggestionsHelper.createLabeledIntentResult(
- mContext,
- mTemplateIntentFactory,
- nativeSuggestion);
- RemoteAction remoteAction = null;
- Bundle extras = new Bundle();
- if (labeledIntentResult != null) {
- remoteAction = labeledIntentResult.remoteAction;
- ExtrasUtils.putActionIntent(extras, labeledIntentResult.resolvedIntent);
- }
- ExtrasUtils.putSerializedEntityData(extras, nativeSuggestion.getSerializedEntityData());
- ExtrasUtils.putEntitiesExtras(
- extras,
- TemplateIntentFactory.nameVariantsToBundle(nativeSuggestion.getEntityData()));
- conversationActions.add(
- new ConversationAction.Builder(actionType)
- .setConfidenceScore(nativeSuggestion.getScore())
- .setTextReply(nativeSuggestion.getResponseText())
- .setAction(remoteAction)
- .setExtras(extras)
- .build());
- }
- conversationActions =
- ActionsSuggestionsHelper.removeActionsWithDuplicates(conversationActions);
- if (request.getMaxSuggestions() >= 0
- && conversationActions.size() > request.getMaxSuggestions()) {
- conversationActions = conversationActions.subList(0, request.getMaxSuggestions());
- }
- String resultId = ActionsSuggestionsHelper.createResultId(
- mContext,
- request.getConversation(),
- mActionModelInUse.getVersion(),
- mActionModelInUse.getSupportedLocales());
- return new ConversationActions(conversationActions, resultId);
- }
-
- @Nullable
- private String detectLanguageTagsFromText(CharSequence text) {
- if (!mSettings.isDetectLanguagesFromTextEnabled()) {
- return null;
- }
- final float threshold = getLangIdThreshold();
- if (threshold < 0 || threshold > 1) {
- Log.w(LOG_TAG,
- "[detectLanguageTagsFromText] unexpected threshold is found: " + threshold);
- return null;
- }
- TextLanguage.Request request = new TextLanguage.Request.Builder(text).build();
- TextLanguage textLanguage = detectLanguage(request);
- int localeHypothesisCount = textLanguage.getLocaleHypothesisCount();
- List<String> languageTags = new ArrayList<>();
- for (int i = 0; i < localeHypothesisCount; i++) {
- ULocale locale = textLanguage.getLocale(i);
- if (textLanguage.getConfidenceScore(locale) < threshold) {
- break;
- }
- languageTags.add(locale.toLanguageTag());
- }
- if (languageTags.isEmpty()) {
- return null;
- }
- return String.join(",", languageTags);
- }
-
- private Collection<String> resolveActionTypesFromRequest(ConversationActions.Request request) {
- List<String> defaultActionTypes =
- request.getHints().contains(ConversationActions.Request.HINT_FOR_NOTIFICATION)
- ? mSettings.getNotificationConversationActionTypes()
- : mSettings.getInAppConversationActionTypes();
- return request.getTypeConfig().resolveEntityListModifications(defaultActionTypes);
- }
-
- private AnnotatorModel getAnnotatorImpl(LocaleList localeList)
- throws FileNotFoundException {
- synchronized (mLock) {
- localeList = localeList == null ? LocaleList.getDefault() : localeList;
- final ModelFileManager.ModelFile bestModel =
- mAnnotatorModelFileManager.findBestModelFile(localeList);
- if (bestModel == null) {
- throw new FileNotFoundException(
- "No annotator model for " + localeList.toLanguageTags());
- }
- if (mAnnotatorImpl == null || !Objects.equals(mAnnotatorModelInUse, bestModel)) {
- Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel);
- final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
- new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY);
- try {
- if (pfd != null) {
- // The current annotator model may be still used by another thread / model.
- // Do not call close() here, and let the GC to clean it up when no one else
- // is using it.
- mAnnotatorImpl = new AnnotatorModel(pfd.getFd());
- mAnnotatorModelInUse = bestModel;
- }
- } finally {
- maybeCloseAndLogError(pfd);
- }
- }
- return mAnnotatorImpl;
- }
- }
-
- private LangIdModel getLangIdImpl() throws FileNotFoundException {
- synchronized (mLock) {
- final ModelFileManager.ModelFile bestModel =
- mLangIdModelFileManager.findBestModelFile(null);
- if (bestModel == null) {
- throw new FileNotFoundException("No LangID model is found");
- }
- if (mLangIdImpl == null || !Objects.equals(mLangIdModelInUse, bestModel)) {
- Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel);
- final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
- new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY);
- try {
- if (pfd != null) {
- mLangIdImpl = new LangIdModel(pfd.getFd());
- mLangIdModelInUse = bestModel;
- }
- } finally {
- maybeCloseAndLogError(pfd);
- }
- }
- return mLangIdImpl;
- }
- }
-
- @Nullable
- private ActionsSuggestionsModel getActionsImpl() throws FileNotFoundException {
- synchronized (mLock) {
- // TODO: Use LangID to determine the locale we should use here?
- final ModelFileManager.ModelFile bestModel =
- mActionsModelFileManager.findBestModelFile(LocaleList.getDefault());
- if (bestModel == null) {
- return null;
- }
- if (mActionsImpl == null || !Objects.equals(mActionModelInUse, bestModel)) {
- Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel);
- final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
- new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY);
- try {
- if (pfd == null) {
- Log.d(LOG_TAG, "Failed to read the model file: " + bestModel.getPath());
- return null;
- }
- ActionsModelParams params = mActionsModelParamsSupplier.get();
- mActionsImpl = new ActionsSuggestionsModel(
- pfd.getFd(), params.getSerializedPreconditions(bestModel));
- mActionModelInUse = bestModel;
- } finally {
- maybeCloseAndLogError(pfd);
- }
- }
- return mActionsImpl;
- }
- }
-
- private String createId(String text, int start, int end) {
- synchronized (mLock) {
- return SelectionSessionLogger.createId(text, start, end, mContext,
- mAnnotatorModelInUse.getVersion(),
- mAnnotatorModelInUse.getSupportedLocales());
- }
- }
-
- private static String concatenateLocales(@Nullable LocaleList locales) {
- return (locales == null) ? "" : locales.toLanguageTags();
- }
-
- private TextClassification createClassificationResult(
- AnnotatorModel.ClassificationResult[] classifications,
- String text, int start, int end, @Nullable Instant referenceTime) {
- final String classifiedText = text.substring(start, end);
- final TextClassification.Builder builder = new TextClassification.Builder()
- .setText(classifiedText);
-
- final int typeCount = classifications.length;
- AnnotatorModel.ClassificationResult highestScoringResult =
- typeCount > 0 ? classifications[0] : null;
- for (int i = 0; i < typeCount; i++) {
- builder.setEntityType(classifications[i]);
- if (classifications[i].getScore() > highestScoringResult.getScore()) {
- highestScoringResult = classifications[i];
- }
- }
-
- final Pair<Bundle, Bundle> languagesBundles = generateLanguageBundles(text, start, end);
- final Bundle textLanguagesBundle = languagesBundles.first;
- final Bundle foreignLanguageBundle = languagesBundles.second;
- builder.setForeignLanguageExtra(foreignLanguageBundle);
-
- boolean isPrimaryAction = true;
- final List<LabeledIntent> labeledIntents = mClassificationIntentFactory.create(
- mContext,
- classifiedText,
- foreignLanguageBundle != null,
- referenceTime,
- highestScoringResult);
- final LabeledIntent.TitleChooser titleChooser =
- (labeledIntent, resolveInfo) -> labeledIntent.titleWithoutEntity;
-
- for (LabeledIntent labeledIntent : labeledIntents) {
- final LabeledIntent.Result result =
- labeledIntent.resolve(mContext, titleChooser, textLanguagesBundle);
- if (result == null) {
- continue;
- }
-
- final Intent intent = result.resolvedIntent;
- final RemoteAction action = result.remoteAction;
- if (isPrimaryAction) {
- // For O backwards compatibility, the first RemoteAction is also written to the
- // legacy API fields.
- builder.setIcon(action.getIcon().loadDrawable(mContext));
- builder.setLabel(action.getTitle().toString());
- builder.setIntent(intent);
- builder.setOnClickListener(TextClassification.createIntentOnClickListener(
- TextClassification.createPendingIntent(
- mContext, intent, labeledIntent.requestCode)));
- isPrimaryAction = false;
- }
- builder.addAction(action, intent);
- }
- return builder.setId(createId(text, start, end)).build();
- }
-
- /**
- * Returns a bundle pair with language detection information for extras.
- * <p>
- * Pair.first = textLanguagesBundle - A bundle containing information about all detected
- * languages in the text. May be null if language detection fails or is disabled. This is
- * typically expected to be added to a textClassifier generated remote action intent.
- * See {@link ExtrasUtils#putTextLanguagesExtra(Bundle, Bundle)}.
- * See {@link ExtrasUtils#getTopLanguage(Intent)}.
- * <p>
- * Pair.second = foreignLanguageBundle - A bundle with the language and confidence score if the
- * system finds the text to be in a foreign language. Otherwise is null.
- * See {@link TextClassification.Builder#setForeignLanguageExtra(Bundle)}.
- *
- * @param context the context of the text to detect languages for
- * @param start the start index of the text
- * @param end the end index of the text
- */
- // TODO: Revisit this algorithm.
- // TODO: Consider making this public API.
- private Pair<Bundle, Bundle> generateLanguageBundles(String context, int start, int end) {
- if (!mSettings.isTranslateInClassificationEnabled()) {
- return null;
- }
- try {
- final float threshold = getLangIdThreshold();
- if (threshold < 0 || threshold > 1) {
- Log.w(LOG_TAG,
- "[detectForeignLanguage] unexpected threshold is found: " + threshold);
- return Pair.create(null, null);
- }
-
- final EntityConfidence languageScores = detectLanguages(context, start, end);
- if (languageScores.getEntities().isEmpty()) {
- return Pair.create(null, null);
- }
-
- final Bundle textLanguagesBundle = new Bundle();
- ExtrasUtils.putTopLanguageScores(textLanguagesBundle, languageScores);
-
- final String language = languageScores.getEntities().get(0);
- final float score = languageScores.getConfidenceScore(language);
- if (score < threshold) {
- return Pair.create(textLanguagesBundle, null);
- }
-
- Log.v(LOG_TAG, String.format(
- Locale.US, "Language detected: <%s:%.2f>", language, score));
-
- final Locale detected = new Locale(language);
- final LocaleList deviceLocales = LocaleList.getDefault();
- final int size = deviceLocales.size();
- for (int i = 0; i < size; i++) {
- if (deviceLocales.get(i).getLanguage().equals(detected.getLanguage())) {
- return Pair.create(textLanguagesBundle, null);
- }
- }
- final Bundle foreignLanguageBundle = ExtrasUtils.createForeignLanguageExtra(
- detected.getLanguage(), score, getLangIdImpl().getVersion());
- return Pair.create(textLanguagesBundle, foreignLanguageBundle);
- } catch (Throwable t) {
- Log.e(LOG_TAG, "Error generating language bundles.", t);
- }
- return Pair.create(null, null);
- }
-
- /**
- * Detect the language of a piece of text by taking surrounding text into consideration.
- *
- * @param text text providing context for the text for which its language is to be detected
- * @param start the start index of the text to detect its language
- * @param end the end index of the text to detect its language
- */
- // TODO: Revisit this algorithm.
- private EntityConfidence detectLanguages(String text, int start, int end)
- throws FileNotFoundException {
- Preconditions.checkArgument(start >= 0);
- Preconditions.checkArgument(end <= text.length());
- Preconditions.checkArgument(start <= end);
-
- final float[] langIdContextSettings = mSettings.getLangIdContextSettings();
- // The minimum size of text to prefer for detection.
- final int minimumTextSize = (int) langIdContextSettings[0];
- // For reducing the score when text is less than the preferred size.
- final float penalizeRatio = langIdContextSettings[1];
- // Original detection score to surrounding text detection score ratios.
- final float subjectTextScoreRatio = langIdContextSettings[2];
- final float moreTextScoreRatio = 1f - subjectTextScoreRatio;
- Log.v(LOG_TAG,
- String.format(Locale.US, "LangIdContextSettings: "
- + "minimumTextSize=%d, penalizeRatio=%.2f, "
- + "subjectTextScoreRatio=%.2f, moreTextScoreRatio=%.2f",
- minimumTextSize, penalizeRatio, subjectTextScoreRatio, moreTextScoreRatio));
-
- if (end - start < minimumTextSize && penalizeRatio <= 0) {
- return new EntityConfidence(Collections.emptyMap());
- }
-
- final String subject = text.substring(start, end);
- final EntityConfidence scores = detectLanguages(subject);
-
- if (subject.length() >= minimumTextSize
- || subject.length() == text.length()
- || subjectTextScoreRatio * penalizeRatio >= 1) {
- return scores;
- }
-
- final EntityConfidence moreTextScores;
- if (moreTextScoreRatio >= 0) {
- // Attempt to grow the detection text to be at least minimumTextSize long.
- final String moreText = Utils.getSubString(text, start, end, minimumTextSize);
- moreTextScores = detectLanguages(moreText);
- } else {
- moreTextScores = new EntityConfidence(Collections.emptyMap());
- }
-
- // Combine the original detection scores with the those returned after including more text.
- final Map<String, Float> newScores = new ArrayMap<>();
- final Set<String> languages = new ArraySet<>();
- languages.addAll(scores.getEntities());
- languages.addAll(moreTextScores.getEntities());
- for (String language : languages) {
- final float score = (subjectTextScoreRatio * scores.getConfidenceScore(language)
- + moreTextScoreRatio * moreTextScores.getConfidenceScore(language))
- * penalizeRatio;
- newScores.put(language, score);
- }
- return new EntityConfidence(newScores);
- }
-
- /**
- * Detect languages for the specified text.
- */
- private EntityConfidence detectLanguages(String text) throws FileNotFoundException {
- final LangIdModel langId = getLangIdImpl();
- final LangIdModel.LanguageResult[] langResults = langId.detectLanguages(text);
- final Map<String, Float> languagesMap = new ArrayMap<>();
- for (LanguageResult langResult : langResults) {
- languagesMap.put(langResult.getLanguage(), langResult.getScore());
- }
- return new EntityConfidence(languagesMap);
- }
-
- private float getLangIdThreshold() {
- try {
- return mSettings.getLangIdThresholdOverride() >= 0
- ? mSettings.getLangIdThresholdOverride()
- : getLangIdImpl().getLangIdThreshold();
- } catch (FileNotFoundException e) {
- final float defaultThreshold = 0.5f;
- Log.v(LOG_TAG, "Using default foreign language threshold: " + defaultThreshold);
- return defaultThreshold;
- }
- }
-
- @Override
- public void dump(@NonNull IndentingPrintWriter printWriter) {
- synchronized (mLock) {
- printWriter.println("TextClassifierImpl:");
- printWriter.increaseIndent();
- printWriter.println("Annotator model file(s):");
- printWriter.increaseIndent();
- for (ModelFileManager.ModelFile modelFile :
- mAnnotatorModelFileManager.listModelFiles()) {
- printWriter.println(modelFile.toString());
- }
- printWriter.decreaseIndent();
- printWriter.println("LangID model file(s):");
- printWriter.increaseIndent();
- for (ModelFileManager.ModelFile modelFile :
- mLangIdModelFileManager.listModelFiles()) {
- printWriter.println(modelFile.toString());
- }
- printWriter.decreaseIndent();
- printWriter.println("Actions model file(s):");
- printWriter.increaseIndent();
- for (ModelFileManager.ModelFile modelFile :
- mActionsModelFileManager.listModelFiles()) {
- printWriter.println(modelFile.toString());
- }
- printWriter.decreaseIndent();
- printWriter.printPair("mFallback", mFallback);
- printWriter.decreaseIndent();
- printWriter.println();
- }
- }
-
- /**
- * Closes the ParcelFileDescriptor, if non-null, and logs any errors that occur.
- */
- private static void maybeCloseAndLogError(@Nullable ParcelFileDescriptor fd) {
- if (fd == null) {
- return;
- }
-
- try {
- fd.close();
- } catch (IOException e) {
- Log.e(LOG_TAG, "Error closing file.", e);
- }
- }
-
- /**
- * Returns the locales string for the current resources configuration.
- */
- private String getResourceLocalesString() {
- try {
- return mContext.getResources().getConfiguration().getLocales().toLanguageTags();
- } catch (NullPointerException e) {
- // NPE is unexpected. Erring on the side of caution.
- return LocaleList.getDefault().toLanguageTags();
- }
- }
-}
diff --git a/core/java/android/view/textclassifier/TextLanguage.java b/core/java/android/view/textclassifier/TextLanguage.java
index 58024dc..1e8253d 100644
--- a/core/java/android/view/textclassifier/TextLanguage.java
+++ b/core/java/android/view/textclassifier/TextLanguage.java
@@ -20,12 +20,10 @@
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.icu.util.ULocale;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.util.ArrayMap;
import com.android.internal.annotations.VisibleForTesting;
@@ -227,10 +225,7 @@
private final CharSequence mText;
private final Bundle mExtra;
- @Nullable private String mCallingPackageName;
- @UserIdInt
- private int mUserId = UserHandle.USER_NULL;
- private boolean mUseDefaultTextClassifier;
+ @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
private Request(CharSequence text, Bundle bundle) {
mText = text;
@@ -246,61 +241,33 @@
}
/**
- * Sets the name of the package that is sending this request.
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
- public void setCallingPackageName(@Nullable String callingPackageName) {
- mCallingPackageName = callingPackageName;
- }
-
- /**
* Returns the name of the package that sent this request.
* This returns null if no calling package name is set.
*/
@Nullable
public String getCallingPackageName() {
- return mCallingPackageName;
+ return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
}
/**
- * Sets the id of the user that sent this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
- }
-
- /**
- * Returns the id of the user that sent this request.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
+ @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+ public void setSystemTextClassifierMetadata(
+ @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+ mSystemTcMetadata = systemTcMetadata;
}
/**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
@@ -321,23 +288,17 @@
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeCharSequence(mText);
- dest.writeString(mCallingPackageName);
- dest.writeInt(mUserId);
dest.writeBundle(mExtra);
- dest.writeBoolean(mUseDefaultTextClassifier);
+ dest.writeParcelable(mSystemTcMetadata, flags);
}
private static Request readFromParcel(Parcel in) {
final CharSequence text = in.readCharSequence();
- final String callingPackageName = in.readString();
- final int userId = in.readInt();
final Bundle extra = in.readBundle();
- final boolean useDefaultTextClassifier = in.readBoolean();
+ final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
final Request request = new Request(text, extra);
- request.setCallingPackageName(callingPackageName);
- request.setUserId(userId);
- request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+ request.setSystemTextClassifierMetadata(systemTcMetadata);
return request;
}
diff --git a/core/java/android/view/textclassifier/TextLinks.java b/core/java/android/view/textclassifier/TextLinks.java
index 7430cb3..dea3a90 100644
--- a/core/java/android/view/textclassifier/TextLinks.java
+++ b/core/java/android/view/textclassifier/TextLinks.java
@@ -20,13 +20,11 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.content.Context;
import android.os.Bundle;
import android.os.LocaleList;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.text.Spannable;
import android.text.method.MovementMethod;
import android.text.style.ClickableSpan;
@@ -340,12 +338,9 @@
@Nullable private final LocaleList mDefaultLocales;
@Nullable private final EntityConfig mEntityConfig;
private final boolean mLegacyFallback;
- @Nullable private String mCallingPackageName;
private final Bundle mExtras;
@Nullable private final ZonedDateTime mReferenceTime;
- @UserIdInt
- private int mUserId = UserHandle.USER_NULL;
- private boolean mUseDefaultTextClassifier;
+ @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
private Request(
CharSequence text,
@@ -409,62 +404,33 @@
}
/**
- * Sets the name of the package that is sending this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
- public void setCallingPackageName(@Nullable String callingPackageName) {
- mCallingPackageName = callingPackageName;
- }
-
- /**
* Returns the name of the package that sent this request.
* This returns {@code null} if no calling package name is set.
*/
@Nullable
public String getCallingPackageName() {
- return mCallingPackageName;
+ return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
}
/**
- * Sets the id of the user that sent this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
- }
-
- /**
- * Returns the id of the user that sent this request.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
+ @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+ public void setSystemTextClassifierMetadata(
+ @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+ mSystemTcMetadata = systemTcMetadata;
}
/**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
@@ -585,30 +551,24 @@
dest.writeString(mText.toString());
dest.writeParcelable(mDefaultLocales, flags);
dest.writeParcelable(mEntityConfig, flags);
- dest.writeString(mCallingPackageName);
- dest.writeInt(mUserId);
dest.writeBundle(mExtras);
dest.writeString(mReferenceTime == null ? null : mReferenceTime.toString());
- dest.writeBoolean(mUseDefaultTextClassifier);
+ dest.writeParcelable(mSystemTcMetadata, flags);
}
private static Request readFromParcel(Parcel in) {
final String text = in.readString();
final LocaleList defaultLocales = in.readParcelable(null);
final EntityConfig entityConfig = in.readParcelable(null);
- final String callingPackageName = in.readString();
- final int userId = in.readInt();
final Bundle extras = in.readBundle();
final String referenceTimeString = in.readString();
final ZonedDateTime referenceTime = referenceTimeString == null
? null : ZonedDateTime.parse(referenceTimeString);
- final boolean useDefaultTextClassifier = in.readBoolean();
+ final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
final Request request = new Request(text, defaultLocales, entityConfig,
/* legacyFallback= */ true, referenceTime, extras);
- request.setCallingPackageName(callingPackageName);
- request.setUserId(userId);
- request.setUseDefaultTextClassifier(useDefaultTextClassifier);
+ request.setSystemTextClassifierMetadata(systemTcMetadata);
return request;
}
diff --git a/core/java/android/view/textclassifier/TextSelection.java b/core/java/android/view/textclassifier/TextSelection.java
index 575a072..d8a632d 100644
--- a/core/java/android/view/textclassifier/TextSelection.java
+++ b/core/java/android/view/textclassifier/TextSelection.java
@@ -20,12 +20,10 @@
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.UserIdInt;
import android.os.Bundle;
import android.os.LocaleList;
import android.os.Parcel;
import android.os.Parcelable;
-import android.os.UserHandle;
import android.text.SpannedString;
import android.util.ArrayMap;
import android.view.textclassifier.TextClassifier.EntityType;
@@ -213,10 +211,7 @@
@Nullable private final LocaleList mDefaultLocales;
private final boolean mDarkLaunchAllowed;
private final Bundle mExtras;
- @Nullable private String mCallingPackageName;
- @UserIdInt
- private int mUserId = UserHandle.USER_NULL;
- private boolean mUseDefaultTextClassifier;
+ @Nullable private SystemTextClassifierMetadata mSystemTcMetadata;
private Request(
CharSequence text,
@@ -278,62 +273,33 @@
}
/**
- * Sets the name of the package that is sending this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
- public void setCallingPackageName(@Nullable String callingPackageName) {
- mCallingPackageName = callingPackageName;
- }
-
- /**
* Returns the name of the package that sent this request.
* This returns {@code null} if no calling package name is set.
*/
@Nullable
public String getCallingPackageName() {
- return mCallingPackageName;
+ return mSystemTcMetadata != null ? mSystemTcMetadata.getCallingPackageName() : null;
}
/**
- * Sets the id of the user that sent this request.
- * <p>
- * Package-private for SystemTextClassifier's use.
- * @hide
- */
- void setUserId(@UserIdInt int userId) {
- mUserId = userId;
- }
-
- /**
- * Returns the id of the user that sent this request.
- * @hide
- */
- @UserIdInt
- public int getUserId() {
- return mUserId;
- }
-
- /**
- * Sets whether to use the default text classifier to handle this request.
- * This will be ignored if it is not the system text classifier to handle this request.
+ * Sets the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- void setUseDefaultTextClassifier(boolean useDefaultTextClassifier) {
- mUseDefaultTextClassifier = useDefaultTextClassifier;
+ @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+ public void setSystemTextClassifierMetadata(
+ @Nullable SystemTextClassifierMetadata systemTcMetadata) {
+ mSystemTcMetadata = systemTcMetadata;
}
/**
- * Returns whether to use the default text classifier to handle this request. This
- * will be ignored if it is not the system text classifier to handle this request.
+ * Returns the information about the {@link SystemTextClassifier} that sent this request.
*
* @hide
*/
- public boolean getUseDefaultTextClassifier() {
- return mUseDefaultTextClassifier;
+ @Nullable
+ public SystemTextClassifierMetadata getSystemTextClassifierMetadata() {
+ return mSystemTcMetadata;
}
/**
@@ -438,10 +404,8 @@
dest.writeInt(mStartIndex);
dest.writeInt(mEndIndex);
dest.writeParcelable(mDefaultLocales, flags);
- dest.writeString(mCallingPackageName);
- dest.writeInt(mUserId);
dest.writeBundle(mExtras);
- dest.writeBoolean(mUseDefaultTextClassifier);
+ dest.writeParcelable(mSystemTcMetadata, flags);
}
private static Request readFromParcel(Parcel in) {
@@ -449,16 +413,12 @@
final int startIndex = in.readInt();
final int endIndex = in.readInt();
final LocaleList defaultLocales = in.readParcelable(null);
- final String callingPackageName = in.readString();
- final int userId = in.readInt();
final Bundle extras = in.readBundle();
- final boolean systemTextClassifierType = in.readBoolean();
+ final SystemTextClassifierMetadata systemTcMetadata = in.readParcelable(null);
final Request request = new Request(text, startIndex, endIndex, defaultLocales,
/* darkLaunchAllowed= */ false, extras);
- request.setCallingPackageName(callingPackageName);
- request.setUserId(userId);
- request.setUseDefaultTextClassifier(systemTextClassifierType);
+ request.setSystemTextClassifierMetadata(systemTcMetadata);
return request;
}
diff --git a/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java b/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java
deleted file mode 100644
index 22e374f2..0000000
--- a/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import android.annotation.Nullable;
-import android.content.Context;
-import android.content.Intent;
-
-import com.google.android.textclassifier.AnnotatorModel;
-
-import java.time.Instant;
-import java.util.List;
-
-/**
- * @hide
- */
-public interface ClassificationIntentFactory {
-
- /**
- * Return a list of LabeledIntent from the classification result.
- */
- List<LabeledIntent> create(
- Context context,
- String text,
- boolean foreignText,
- @Nullable Instant referenceTime,
- @Nullable AnnotatorModel.ClassificationResult classification);
-
- /**
- * Inserts translate action to the list if it is a foreign text.
- */
- static void insertTranslateAction(
- List<LabeledIntent> actions, Context context, String text) {
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.translate),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.translate_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_TRANSLATE)
- // TODO: Probably better to introduce a "translate" scheme instead of
- // using EXTRA_TEXT.
- .putExtra(Intent.EXTRA_TEXT, text),
- text.hashCode()));
- }
-}
diff --git a/core/java/android/view/textclassifier/intent/LabeledIntent.java b/core/java/android/view/textclassifier/intent/LabeledIntent.java
deleted file mode 100644
index cbd9d1a..0000000
--- a/core/java/android/view/textclassifier/intent/LabeledIntent.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import android.annotation.Nullable;
-import android.app.PendingIntent;
-import android.app.RemoteAction;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.graphics.drawable.Icon;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.view.textclassifier.ExtrasUtils;
-import android.view.textclassifier.Log;
-import android.view.textclassifier.TextClassification;
-import android.view.textclassifier.TextClassifier;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.util.Objects;
-
-/**
- * Helper class to store the information from which RemoteActions are built.
- *
- * @hide
- */
-@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-public final class LabeledIntent {
- private static final String TAG = "LabeledIntent";
- public static final int DEFAULT_REQUEST_CODE = 0;
- private static final TitleChooser DEFAULT_TITLE_CHOOSER =
- (labeledIntent, resolveInfo) -> {
- if (!TextUtils.isEmpty(labeledIntent.titleWithEntity)) {
- return labeledIntent.titleWithEntity;
- }
- return labeledIntent.titleWithoutEntity;
- };
-
- @Nullable
- public final String titleWithoutEntity;
- @Nullable
- public final String titleWithEntity;
- public final String description;
- @Nullable
- public final String descriptionWithAppName;
- // Do not update this intent.
- public final Intent intent;
- public final int requestCode;
-
- /**
- * Initializes a LabeledIntent.
- *
- * <p>NOTE: {@code requestCode} is required to not be {@link #DEFAULT_REQUEST_CODE}
- * if distinguishing info (e.g. the classified text) is represented in intent extras only.
- * In such circumstances, the request code should represent the distinguishing info
- * (e.g. by generating a hashcode) so that the generated PendingIntent is (somewhat)
- * unique. To be correct, the PendingIntent should be definitely unique but we try a
- * best effort approach that avoids spamming the system with PendingIntents.
- */
- // TODO: Fix the issue mentioned above so the behaviour is correct.
- public LabeledIntent(
- @Nullable String titleWithoutEntity,
- @Nullable String titleWithEntity,
- String description,
- @Nullable String descriptionWithAppName,
- Intent intent,
- int requestCode) {
- if (TextUtils.isEmpty(titleWithEntity) && TextUtils.isEmpty(titleWithoutEntity)) {
- throw new IllegalArgumentException(
- "titleWithEntity and titleWithoutEntity should not be both null");
- }
- this.titleWithoutEntity = titleWithoutEntity;
- this.titleWithEntity = titleWithEntity;
- this.description = Objects.requireNonNull(description);
- this.descriptionWithAppName = descriptionWithAppName;
- this.intent = Objects.requireNonNull(intent);
- this.requestCode = requestCode;
- }
-
- /**
- * Return the resolved result.
- *
- * @param context the context to resolve the result's intent and action
- * @param titleChooser for choosing an action title
- * @param textLanguagesBundle containing language detection information
- */
- @Nullable
- public Result resolve(
- Context context,
- @Nullable TitleChooser titleChooser,
- @Nullable Bundle textLanguagesBundle) {
- final PackageManager pm = context.getPackageManager();
- final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
-
- if (resolveInfo == null || resolveInfo.activityInfo == null) {
- Log.w(TAG, "resolveInfo or activityInfo is null");
- return null;
- }
- final String packageName = resolveInfo.activityInfo.packageName;
- final String className = resolveInfo.activityInfo.name;
- if (packageName == null || className == null) {
- Log.w(TAG, "packageName or className is null");
- return null;
- }
- Intent resolvedIntent = new Intent(intent);
- resolvedIntent.putExtra(
- TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER,
- getFromTextClassifierExtra(textLanguagesBundle));
- boolean shouldShowIcon = false;
- Icon icon = null;
- if (!"android".equals(packageName)) {
- // We only set the component name when the package name is not resolved to "android"
- // to workaround a bug that explicit intent with component name == ResolverActivity
- // can't be launched on keyguard.
- resolvedIntent.setComponent(new ComponentName(packageName, className));
- if (resolveInfo.activityInfo.getIconResource() != 0) {
- icon = Icon.createWithResource(
- packageName, resolveInfo.activityInfo.getIconResource());
- shouldShowIcon = true;
- }
- }
- if (icon == null) {
- // RemoteAction requires that there be an icon.
- icon = Icon.createWithResource(
- "android", com.android.internal.R.drawable.ic_more_items);
- }
- final PendingIntent pendingIntent =
- TextClassification.createPendingIntent(context, resolvedIntent, requestCode);
- titleChooser = titleChooser == null ? DEFAULT_TITLE_CHOOSER : titleChooser;
- CharSequence title = titleChooser.chooseTitle(this, resolveInfo);
- if (TextUtils.isEmpty(title)) {
- Log.w(TAG, "Custom titleChooser return null, fallback to the default titleChooser");
- title = DEFAULT_TITLE_CHOOSER.chooseTitle(this, resolveInfo);
- }
- final RemoteAction action =
- new RemoteAction(icon, title, resolveDescription(resolveInfo, pm), pendingIntent);
- action.setShouldShowIcon(shouldShowIcon);
- return new Result(resolvedIntent, action);
- }
-
- private String resolveDescription(ResolveInfo resolveInfo, PackageManager packageManager) {
- if (!TextUtils.isEmpty(descriptionWithAppName)) {
- // Example string format of descriptionWithAppName: "Use %1$s to open map".
- String applicationName = getApplicationName(resolveInfo, packageManager);
- if (!TextUtils.isEmpty(applicationName)) {
- return String.format(descriptionWithAppName, applicationName);
- }
- }
- return description;
- }
-
- @Nullable
- private String getApplicationName(
- ResolveInfo resolveInfo, PackageManager packageManager) {
- if (resolveInfo.activityInfo == null) {
- return null;
- }
- if ("android".equals(resolveInfo.activityInfo.packageName)) {
- return null;
- }
- if (resolveInfo.activityInfo.applicationInfo == null) {
- return null;
- }
- return (String) packageManager.getApplicationLabel(
- resolveInfo.activityInfo.applicationInfo);
- }
-
- private Bundle getFromTextClassifierExtra(@Nullable Bundle textLanguagesBundle) {
- if (textLanguagesBundle != null) {
- final Bundle bundle = new Bundle();
- ExtrasUtils.putTextLanguagesExtra(bundle, textLanguagesBundle);
- return bundle;
- } else {
- return Bundle.EMPTY;
- }
- }
-
- /**
- * Data class that holds the result.
- */
- public static final class Result {
- public final Intent resolvedIntent;
- public final RemoteAction remoteAction;
-
- public Result(Intent resolvedIntent, RemoteAction remoteAction) {
- this.resolvedIntent = Objects.requireNonNull(resolvedIntent);
- this.remoteAction = Objects.requireNonNull(remoteAction);
- }
- }
-
- /**
- * An object to choose a title from resolved info. If {@code null} is returned,
- * {@link #titleWithEntity} will be used if it exists, {@link #titleWithoutEntity} otherwise.
- */
- public interface TitleChooser {
- /**
- * Picks a title from a {@link LabeledIntent} by looking into resolved info.
- * {@code resolveInfo} is guaranteed to have a non-null {@code activityInfo}.
- */
- @Nullable
- CharSequence chooseTitle(LabeledIntent labeledIntent, ResolveInfo resolveInfo);
- }
-}
diff --git a/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java b/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java
deleted file mode 100644
index 8d60ad8..0000000
--- a/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import static java.time.temporal.ChronoUnit.MILLIS;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.SearchManager;
-import android.content.ContentUris;
-import android.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.UserManager;
-import android.provider.Browser;
-import android.provider.CalendarContract;
-import android.provider.ContactsContract;
-import android.view.textclassifier.Log;
-import android.view.textclassifier.TextClassifier;
-
-import com.google.android.textclassifier.AnnotatorModel;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Creates intents based on the classification type.
- * @hide
- */
-// TODO: Consider to support {@code descriptionWithAppName}.
-public final class LegacyClassificationIntentFactory implements ClassificationIntentFactory {
-
- private static final String TAG = "LegacyClassificationIntentFactory";
- private static final long MIN_EVENT_FUTURE_MILLIS = TimeUnit.MINUTES.toMillis(5);
- private static final long DEFAULT_EVENT_DURATION = TimeUnit.HOURS.toMillis(1);
-
- @NonNull
- @Override
- public List<LabeledIntent> create(Context context, String text, boolean foreignText,
- @Nullable Instant referenceTime,
- AnnotatorModel.ClassificationResult classification) {
- final String type = classification != null
- ? classification.getCollection().trim().toLowerCase(Locale.ENGLISH)
- : "";
- text = text.trim();
- final List<LabeledIntent> actions;
- switch (type) {
- case TextClassifier.TYPE_EMAIL:
- actions = createForEmail(context, text);
- break;
- case TextClassifier.TYPE_PHONE:
- actions = createForPhone(context, text);
- break;
- case TextClassifier.TYPE_ADDRESS:
- actions = createForAddress(context, text);
- break;
- case TextClassifier.TYPE_URL:
- actions = createForUrl(context, text);
- break;
- case TextClassifier.TYPE_DATE: // fall through
- case TextClassifier.TYPE_DATE_TIME:
- if (classification.getDatetimeResult() != null) {
- final Instant parsedTime = Instant.ofEpochMilli(
- classification.getDatetimeResult().getTimeMsUtc());
- actions = createForDatetime(context, type, referenceTime, parsedTime);
- } else {
- actions = new ArrayList<>();
- }
- break;
- case TextClassifier.TYPE_FLIGHT_NUMBER:
- actions = createForFlight(context, text);
- break;
- case TextClassifier.TYPE_DICTIONARY:
- actions = createForDictionary(context, text);
- break;
- default:
- actions = new ArrayList<>();
- break;
- }
- if (foreignText) {
- ClassificationIntentFactory.insertTranslateAction(actions, context, text);
- }
- return actions;
- }
-
- @NonNull
- private static List<LabeledIntent> createForEmail(Context context, String text) {
- final List<LabeledIntent> actions = new ArrayList<>();
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.email),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.email_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_SENDTO)
- .setData(Uri.parse(String.format("mailto:%s", text))),
- LabeledIntent.DEFAULT_REQUEST_CODE));
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.add_contact),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.add_contact_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_INSERT_OR_EDIT)
- .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
- .putExtra(ContactsContract.Intents.Insert.EMAIL, text),
- text.hashCode()));
- return actions;
- }
-
- @NonNull
- private static List<LabeledIntent> createForPhone(Context context, String text) {
- final List<LabeledIntent> actions = new ArrayList<>();
- final UserManager userManager = context.getSystemService(UserManager.class);
- final Bundle userRestrictions = userManager != null
- ? userManager.getUserRestrictions() : new Bundle();
- if (!userRestrictions.getBoolean(UserManager.DISALLOW_OUTGOING_CALLS, false)) {
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.dial),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.dial_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_DIAL).setData(
- Uri.parse(String.format("tel:%s", text))),
- LabeledIntent.DEFAULT_REQUEST_CODE));
- }
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.add_contact),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.add_contact_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_INSERT_OR_EDIT)
- .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
- .putExtra(ContactsContract.Intents.Insert.PHONE, text),
- text.hashCode()));
- if (!userRestrictions.getBoolean(UserManager.DISALLOW_SMS, false)) {
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.sms),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.sms_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_SENDTO)
- .setData(Uri.parse(String.format("smsto:%s", text))),
- LabeledIntent.DEFAULT_REQUEST_CODE));
- }
- return actions;
- }
-
- @NonNull
- private static List<LabeledIntent> createForAddress(Context context, String text) {
- final List<LabeledIntent> actions = new ArrayList<>();
- try {
- final String encText = URLEncoder.encode(text, "UTF-8");
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.map),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.map_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_VIEW)
- .setData(Uri.parse(String.format("geo:0,0?q=%s", encText))),
- LabeledIntent.DEFAULT_REQUEST_CODE));
- } catch (UnsupportedEncodingException e) {
- Log.e(TAG, "Could not encode address", e);
- }
- return actions;
- }
-
- @NonNull
- private static List<LabeledIntent> createForUrl(Context context, String text) {
- if (Uri.parse(text).getScheme() == null) {
- text = "http://" + text;
- }
- final List<LabeledIntent> actions = new ArrayList<>();
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.browse),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.browse_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_VIEW)
- .setDataAndNormalize(Uri.parse(text))
- .putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()),
- LabeledIntent.DEFAULT_REQUEST_CODE));
- return actions;
- }
-
- @NonNull
- private static List<LabeledIntent> createForDatetime(
- Context context, String type, @Nullable Instant referenceTime,
- Instant parsedTime) {
- if (referenceTime == null) {
- // If no reference time was given, use now.
- referenceTime = Instant.now();
- }
- List<LabeledIntent> actions = new ArrayList<>();
- actions.add(createCalendarViewIntent(context, parsedTime));
- final long millisUntilEvent = referenceTime.until(parsedTime, MILLIS);
- if (millisUntilEvent > MIN_EVENT_FUTURE_MILLIS) {
- actions.add(createCalendarCreateEventIntent(context, parsedTime, type));
- }
- return actions;
- }
-
- @NonNull
- private static List<LabeledIntent> createForFlight(Context context, String text) {
- final List<LabeledIntent> actions = new ArrayList<>();
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.view_flight),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.view_flight_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_WEB_SEARCH)
- .putExtra(SearchManager.QUERY, text),
- text.hashCode()));
- return actions;
- }
-
- @NonNull
- private static LabeledIntent createCalendarViewIntent(Context context, Instant parsedTime) {
- Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
- builder.appendPath("time");
- ContentUris.appendId(builder, parsedTime.toEpochMilli());
- return new LabeledIntent(
- context.getString(com.android.internal.R.string.view_calendar),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.view_calendar_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_VIEW).setData(builder.build()),
- LabeledIntent.DEFAULT_REQUEST_CODE);
- }
-
- @NonNull
- private static LabeledIntent createCalendarCreateEventIntent(
- Context context, Instant parsedTime, @TextClassifier.EntityType String type) {
- final boolean isAllDay = TextClassifier.TYPE_DATE.equals(type);
- return new LabeledIntent(
- context.getString(com.android.internal.R.string.add_calendar_event),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.add_calendar_event_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_INSERT)
- .setData(CalendarContract.Events.CONTENT_URI)
- .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, isAllDay)
- .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
- parsedTime.toEpochMilli())
- .putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
- parsedTime.toEpochMilli() + DEFAULT_EVENT_DURATION),
- parsedTime.hashCode());
- }
-
- @NonNull
- private static List<LabeledIntent> createForDictionary(Context context, String text) {
- final List<LabeledIntent> actions = new ArrayList<>();
- actions.add(new LabeledIntent(
- context.getString(com.android.internal.R.string.define),
- /* titleWithEntity */ null,
- context.getString(com.android.internal.R.string.define_desc),
- /* descriptionWithAppName */ null,
- new Intent(Intent.ACTION_DEFINE)
- .putExtra(Intent.EXTRA_TEXT, text),
- text.hashCode()));
- return actions;
- }
-}
diff --git a/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java b/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java
deleted file mode 100644
index aef4bd6..0000000
--- a/core/java/android/view/textclassifier/intent/TemplateClassificationIntentFactory.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.view.textclassifier.Log;
-import android.view.textclassifier.TextClassifier;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
-
-import com.google.android.textclassifier.AnnotatorModel;
-import com.google.android.textclassifier.RemoteActionTemplate;
-
-import java.time.Instant;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Creates intents based on {@link RemoteActionTemplate} objects for a ClassificationResult.
- *
- * @hide
- */
-@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-public final class TemplateClassificationIntentFactory implements ClassificationIntentFactory {
- private static final String TAG = TextClassifier.DEFAULT_LOG_TAG;
- private final TemplateIntentFactory mTemplateIntentFactory;
- private final ClassificationIntentFactory mFallback;
-
- public TemplateClassificationIntentFactory(TemplateIntentFactory templateIntentFactory,
- ClassificationIntentFactory fallback) {
- mTemplateIntentFactory = Objects.requireNonNull(templateIntentFactory);
- mFallback = Objects.requireNonNull(fallback);
- }
-
- /**
- * Returns a list of {@link LabeledIntent}
- * that are constructed from the classification result.
- */
- @NonNull
- @Override
- public List<LabeledIntent> create(
- Context context,
- String text,
- boolean foreignText,
- @Nullable Instant referenceTime,
- @Nullable AnnotatorModel.ClassificationResult classification) {
- if (classification == null) {
- return Collections.emptyList();
- }
- RemoteActionTemplate[] remoteActionTemplates = classification.getRemoteActionTemplates();
- if (remoteActionTemplates == null) {
- // RemoteActionTemplate is missing, fallback.
- Log.w(TAG, "RemoteActionTemplate is missing, fallback to"
- + " LegacyClassificationIntentFactory.");
- return mFallback.create(context, text, foreignText, referenceTime, classification);
- }
- final List<LabeledIntent> labeledIntents =
- mTemplateIntentFactory.create(remoteActionTemplates);
- if (foreignText) {
- ClassificationIntentFactory.insertTranslateAction(labeledIntents, context, text.trim());
- }
- return labeledIntents;
- }
-}
diff --git a/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java b/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java
deleted file mode 100644
index 7a39569..0000000
--- a/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.view.textclassifier.Log;
-import android.view.textclassifier.TextClassifier;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import com.google.android.textclassifier.NamedVariant;
-import com.google.android.textclassifier.RemoteActionTemplate;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Creates intents based on {@link RemoteActionTemplate} objects.
- *
- * @hide
- */
-@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
-public final class TemplateIntentFactory {
- private static final String TAG = TextClassifier.DEFAULT_LOG_TAG;
-
- /**
- * Constructs and returns a list of {@link LabeledIntent} based on the given templates.
- */
- @Nullable
- public List<LabeledIntent> create(
- @NonNull RemoteActionTemplate[] remoteActionTemplates) {
- if (remoteActionTemplates.length == 0) {
- return new ArrayList<>();
- }
- final List<LabeledIntent> labeledIntents = new ArrayList<>();
- for (RemoteActionTemplate remoteActionTemplate : remoteActionTemplates) {
- if (!isValidTemplate(remoteActionTemplate)) {
- Log.w(TAG, "Invalid RemoteActionTemplate skipped.");
- continue;
- }
- labeledIntents.add(
- new LabeledIntent(
- remoteActionTemplate.titleWithoutEntity,
- remoteActionTemplate.titleWithEntity,
- remoteActionTemplate.description,
- remoteActionTemplate.descriptionWithAppName,
- createIntent(remoteActionTemplate),
- remoteActionTemplate.requestCode == null
- ? LabeledIntent.DEFAULT_REQUEST_CODE
- : remoteActionTemplate.requestCode));
- }
- return labeledIntents;
- }
-
- private static boolean isValidTemplate(@Nullable RemoteActionTemplate remoteActionTemplate) {
- if (remoteActionTemplate == null) {
- Log.w(TAG, "Invalid RemoteActionTemplate: is null");
- return false;
- }
- if (TextUtils.isEmpty(remoteActionTemplate.titleWithEntity)
- && TextUtils.isEmpty(remoteActionTemplate.titleWithoutEntity)) {
- Log.w(TAG, "Invalid RemoteActionTemplate: title is null");
- return false;
- }
- if (TextUtils.isEmpty(remoteActionTemplate.description)) {
- Log.w(TAG, "Invalid RemoteActionTemplate: description is null");
- return false;
- }
- if (!TextUtils.isEmpty(remoteActionTemplate.packageName)) {
- Log.w(TAG, "Invalid RemoteActionTemplate: package name is set");
- return false;
- }
- if (TextUtils.isEmpty(remoteActionTemplate.action)) {
- Log.w(TAG, "Invalid RemoteActionTemplate: intent action not set");
- return false;
- }
- return true;
- }
-
- private static Intent createIntent(RemoteActionTemplate remoteActionTemplate) {
- final Intent intent = new Intent(remoteActionTemplate.action);
- final Uri uri = TextUtils.isEmpty(remoteActionTemplate.data)
- ? null : Uri.parse(remoteActionTemplate.data).normalizeScheme();
- final String type = TextUtils.isEmpty(remoteActionTemplate.type)
- ? null : Intent.normalizeMimeType(remoteActionTemplate.type);
- intent.setDataAndType(uri, type);
- intent.setFlags(remoteActionTemplate.flags == null ? 0 : remoteActionTemplate.flags);
- if (remoteActionTemplate.category != null) {
- for (String category : remoteActionTemplate.category) {
- if (category != null) {
- intent.addCategory(category);
- }
- }
- }
- intent.putExtras(nameVariantsToBundle(remoteActionTemplate.extras));
- return intent;
- }
-
- /**
- * Converts an array of {@link NamedVariant} to a Bundle and returns it.
- */
- public static Bundle nameVariantsToBundle(@Nullable NamedVariant[] namedVariants) {
- if (namedVariants == null) {
- return Bundle.EMPTY;
- }
- Bundle bundle = new Bundle();
- for (NamedVariant namedVariant : namedVariants) {
- if (namedVariant == null) {
- continue;
- }
- switch (namedVariant.getType()) {
- case NamedVariant.TYPE_INT:
- bundle.putInt(namedVariant.getName(), namedVariant.getInt());
- break;
- case NamedVariant.TYPE_LONG:
- bundle.putLong(namedVariant.getName(), namedVariant.getLong());
- break;
- case NamedVariant.TYPE_FLOAT:
- bundle.putFloat(namedVariant.getName(), namedVariant.getFloat());
- break;
- case NamedVariant.TYPE_DOUBLE:
- bundle.putDouble(namedVariant.getName(), namedVariant.getDouble());
- break;
- case NamedVariant.TYPE_BOOL:
- bundle.putBoolean(namedVariant.getName(), namedVariant.getBool());
- break;
- case NamedVariant.TYPE_STRING:
- bundle.putString(namedVariant.getName(), namedVariant.getString());
- break;
- default:
- Log.w(TAG,
- "Unsupported type found in nameVariantsToBundle : "
- + namedVariant.getType());
- }
- }
- return bundle;
- }
-}
diff --git a/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java b/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java
deleted file mode 100644
index 28cb80d..0000000
--- a/core/java/android/view/textclassifier/logging/SmartSelectionEventTracker.java
+++ /dev/null
@@ -1,599 +0,0 @@
-/*
- * Copyright (C) 2017 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.view.textclassifier.logging;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.Context;
-import android.metrics.LogMaker;
-import android.os.Build;
-import android.util.Log;
-import android.view.textclassifier.TextClassification;
-import android.view.textclassifier.TextClassifier;
-import android.view.textclassifier.TextSelection;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.internal.util.Preconditions;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-import java.util.UUID;
-
-/**
- * A selection event tracker.
- * @hide
- */
-//TODO: Do not allow any crashes from this class.
-public final class SmartSelectionEventTracker {
-
- private static final String LOG_TAG = "SmartSelectEventTracker";
- private static final boolean DEBUG_LOG_ENABLED = true;
-
- private static final int START_EVENT_DELTA = MetricsEvent.FIELD_SELECTION_SINCE_START;
- private static final int PREV_EVENT_DELTA = MetricsEvent.FIELD_SELECTION_SINCE_PREVIOUS;
- private static final int INDEX = MetricsEvent.FIELD_SELECTION_SESSION_INDEX;
- private static final int WIDGET_TYPE = MetricsEvent.FIELD_SELECTION_WIDGET_TYPE;
- private static final int WIDGET_VERSION = MetricsEvent.FIELD_SELECTION_WIDGET_VERSION;
- private static final int MODEL_NAME = MetricsEvent.FIELD_TEXTCLASSIFIER_MODEL;
- private static final int ENTITY_TYPE = MetricsEvent.FIELD_SELECTION_ENTITY_TYPE;
- private static final int SMART_START = MetricsEvent.FIELD_SELECTION_SMART_RANGE_START;
- private static final int SMART_END = MetricsEvent.FIELD_SELECTION_SMART_RANGE_END;
- private static final int EVENT_START = MetricsEvent.FIELD_SELECTION_RANGE_START;
- private static final int EVENT_END = MetricsEvent.FIELD_SELECTION_RANGE_END;
- private static final int SESSION_ID = MetricsEvent.FIELD_SELECTION_SESSION_ID;
-
- private static final String ZERO = "0";
- private static final String TEXTVIEW = "textview";
- private static final String EDITTEXT = "edittext";
- private static final String UNSELECTABLE_TEXTVIEW = "nosel-textview";
- private static final String WEBVIEW = "webview";
- private static final String EDIT_WEBVIEW = "edit-webview";
- private static final String CUSTOM_TEXTVIEW = "customview";
- private static final String CUSTOM_EDITTEXT = "customedit";
- private static final String CUSTOM_UNSELECTABLE_TEXTVIEW = "nosel-customview";
- private static final String UNKNOWN = "unknown";
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef({WidgetType.UNSPECIFIED, WidgetType.TEXTVIEW, WidgetType.WEBVIEW,
- WidgetType.EDITTEXT, WidgetType.EDIT_WEBVIEW})
- public @interface WidgetType {
- int UNSPECIFIED = 0;
- int TEXTVIEW = 1;
- int WEBVIEW = 2;
- int EDITTEXT = 3;
- int EDIT_WEBVIEW = 4;
- int UNSELECTABLE_TEXTVIEW = 5;
- int CUSTOM_TEXTVIEW = 6;
- int CUSTOM_EDITTEXT = 7;
- int CUSTOM_UNSELECTABLE_TEXTVIEW = 8;
- }
-
- private final MetricsLogger mMetricsLogger = new MetricsLogger();
- private final int mWidgetType;
- @Nullable private final String mWidgetVersion;
- private final Context mContext;
-
- @Nullable private String mSessionId;
- private final int[] mSmartIndices = new int[2];
- private final int[] mPrevIndices = new int[2];
- private int mOrigStart;
- private int mIndex;
- private long mSessionStartTime;
- private long mLastEventTime;
- private boolean mSmartSelectionTriggered;
- private String mModelName;
-
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public SmartSelectionEventTracker(@NonNull Context context, @WidgetType int widgetType) {
- mWidgetType = widgetType;
- mWidgetVersion = null;
- mContext = Objects.requireNonNull(context);
- }
-
- public SmartSelectionEventTracker(
- @NonNull Context context, @WidgetType int widgetType, @Nullable String widgetVersion) {
- mWidgetType = widgetType;
- mWidgetVersion = widgetVersion;
- mContext = Objects.requireNonNull(context);
- }
-
- /**
- * Logs a selection event.
- *
- * @param event the selection event
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public void logEvent(@NonNull SelectionEvent event) {
- Objects.requireNonNull(event);
-
- if (event.mEventType != SelectionEvent.EventType.SELECTION_STARTED && mSessionId == null
- && DEBUG_LOG_ENABLED) {
- Log.d(LOG_TAG, "Selection session not yet started. Ignoring event");
- return;
- }
-
- final long now = System.currentTimeMillis();
- switch (event.mEventType) {
- case SelectionEvent.EventType.SELECTION_STARTED:
- mSessionId = startNewSession();
- Preconditions.checkArgument(event.mEnd == event.mStart + 1);
- mOrigStart = event.mStart;
- mSessionStartTime = now;
- break;
- case SelectionEvent.EventType.SMART_SELECTION_SINGLE: // fall through
- case SelectionEvent.EventType.SMART_SELECTION_MULTI:
- mSmartSelectionTriggered = true;
- mModelName = getModelName(event);
- mSmartIndices[0] = event.mStart;
- mSmartIndices[1] = event.mEnd;
- break;
- case SelectionEvent.EventType.SELECTION_MODIFIED: // fall through
- case SelectionEvent.EventType.AUTO_SELECTION:
- if (mPrevIndices[0] == event.mStart && mPrevIndices[1] == event.mEnd) {
- // Selection did not change. Ignore event.
- return;
- }
- }
- writeEvent(event, now);
-
- if (event.isTerminal()) {
- endSession();
- }
- }
-
- private void writeEvent(SelectionEvent event, long now) {
- final long prevEventDelta = mLastEventTime == 0 ? 0 : now - mLastEventTime;
- final LogMaker log = new LogMaker(MetricsEvent.TEXT_SELECTION_SESSION)
- .setType(getLogType(event))
- .setSubtype(MetricsEvent.TEXT_SELECTION_INVOCATION_MANUAL)
- .setPackageName(mContext.getPackageName())
- .addTaggedData(START_EVENT_DELTA, now - mSessionStartTime)
- .addTaggedData(PREV_EVENT_DELTA, prevEventDelta)
- .addTaggedData(INDEX, mIndex)
- .addTaggedData(WIDGET_TYPE, getWidgetTypeName())
- .addTaggedData(WIDGET_VERSION, mWidgetVersion)
- .addTaggedData(MODEL_NAME, mModelName)
- .addTaggedData(ENTITY_TYPE, event.mEntityType)
- .addTaggedData(SMART_START, getSmartRangeDelta(mSmartIndices[0]))
- .addTaggedData(SMART_END, getSmartRangeDelta(mSmartIndices[1]))
- .addTaggedData(EVENT_START, getRangeDelta(event.mStart))
- .addTaggedData(EVENT_END, getRangeDelta(event.mEnd))
- .addTaggedData(SESSION_ID, mSessionId);
- mMetricsLogger.write(log);
- debugLog(log);
- mLastEventTime = now;
- mPrevIndices[0] = event.mStart;
- mPrevIndices[1] = event.mEnd;
- mIndex++;
- }
-
- private String startNewSession() {
- endSession();
- mSessionId = createSessionId();
- return mSessionId;
- }
-
- private void endSession() {
- // Reset fields.
- mOrigStart = 0;
- mSmartIndices[0] = mSmartIndices[1] = 0;
- mPrevIndices[0] = mPrevIndices[1] = 0;
- mIndex = 0;
- mSessionStartTime = 0;
- mLastEventTime = 0;
- mSmartSelectionTriggered = false;
- mModelName = getModelName(null);
- mSessionId = null;
- }
-
- private static int getLogType(SelectionEvent event) {
- switch (event.mEventType) {
- case SelectionEvent.ActionType.OVERTYPE:
- return MetricsEvent.ACTION_TEXT_SELECTION_OVERTYPE;
- case SelectionEvent.ActionType.COPY:
- return MetricsEvent.ACTION_TEXT_SELECTION_COPY;
- case SelectionEvent.ActionType.PASTE:
- return MetricsEvent.ACTION_TEXT_SELECTION_PASTE;
- case SelectionEvent.ActionType.CUT:
- return MetricsEvent.ACTION_TEXT_SELECTION_CUT;
- case SelectionEvent.ActionType.SHARE:
- return MetricsEvent.ACTION_TEXT_SELECTION_SHARE;
- case SelectionEvent.ActionType.SMART_SHARE:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE;
- case SelectionEvent.ActionType.DRAG:
- return MetricsEvent.ACTION_TEXT_SELECTION_DRAG;
- case SelectionEvent.ActionType.ABANDON:
- return MetricsEvent.ACTION_TEXT_SELECTION_ABANDON;
- case SelectionEvent.ActionType.OTHER:
- return MetricsEvent.ACTION_TEXT_SELECTION_OTHER;
- case SelectionEvent.ActionType.SELECT_ALL:
- return MetricsEvent.ACTION_TEXT_SELECTION_SELECT_ALL;
- case SelectionEvent.ActionType.RESET:
- return MetricsEvent.ACTION_TEXT_SELECTION_RESET;
- case SelectionEvent.EventType.SELECTION_STARTED:
- return MetricsEvent.ACTION_TEXT_SELECTION_START;
- case SelectionEvent.EventType.SELECTION_MODIFIED:
- return MetricsEvent.ACTION_TEXT_SELECTION_MODIFY;
- case SelectionEvent.EventType.SMART_SELECTION_SINGLE:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_SINGLE;
- case SelectionEvent.EventType.SMART_SELECTION_MULTI:
- return MetricsEvent.ACTION_TEXT_SELECTION_SMART_MULTI;
- case SelectionEvent.EventType.AUTO_SELECTION:
- return MetricsEvent.ACTION_TEXT_SELECTION_AUTO;
- default:
- return MetricsEvent.VIEW_UNKNOWN;
- }
- }
-
- private static String getLogTypeString(int logType) {
- switch (logType) {
- case MetricsEvent.ACTION_TEXT_SELECTION_OVERTYPE:
- return "OVERTYPE";
- case MetricsEvent.ACTION_TEXT_SELECTION_COPY:
- return "COPY";
- case MetricsEvent.ACTION_TEXT_SELECTION_PASTE:
- return "PASTE";
- case MetricsEvent.ACTION_TEXT_SELECTION_CUT:
- return "CUT";
- case MetricsEvent.ACTION_TEXT_SELECTION_SHARE:
- return "SHARE";
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE:
- return "SMART_SHARE";
- case MetricsEvent.ACTION_TEXT_SELECTION_DRAG:
- return "DRAG";
- case MetricsEvent.ACTION_TEXT_SELECTION_ABANDON:
- return "ABANDON";
- case MetricsEvent.ACTION_TEXT_SELECTION_OTHER:
- return "OTHER";
- case MetricsEvent.ACTION_TEXT_SELECTION_SELECT_ALL:
- return "SELECT_ALL";
- case MetricsEvent.ACTION_TEXT_SELECTION_RESET:
- return "RESET";
- case MetricsEvent.ACTION_TEXT_SELECTION_START:
- return "SELECTION_STARTED";
- case MetricsEvent.ACTION_TEXT_SELECTION_MODIFY:
- return "SELECTION_MODIFIED";
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_SINGLE:
- return "SMART_SELECTION_SINGLE";
- case MetricsEvent.ACTION_TEXT_SELECTION_SMART_MULTI:
- return "SMART_SELECTION_MULTI";
- case MetricsEvent.ACTION_TEXT_SELECTION_AUTO:
- return "AUTO_SELECTION";
- default:
- return UNKNOWN;
- }
- }
-
- private int getRangeDelta(int offset) {
- return offset - mOrigStart;
- }
-
- private int getSmartRangeDelta(int offset) {
- return mSmartSelectionTriggered ? getRangeDelta(offset) : 0;
- }
-
- private String getWidgetTypeName() {
- switch (mWidgetType) {
- case WidgetType.TEXTVIEW:
- return TEXTVIEW;
- case WidgetType.WEBVIEW:
- return WEBVIEW;
- case WidgetType.EDITTEXT:
- return EDITTEXT;
- case WidgetType.EDIT_WEBVIEW:
- return EDIT_WEBVIEW;
- case WidgetType.UNSELECTABLE_TEXTVIEW:
- return UNSELECTABLE_TEXTVIEW;
- case WidgetType.CUSTOM_TEXTVIEW:
- return CUSTOM_TEXTVIEW;
- case WidgetType.CUSTOM_EDITTEXT:
- return CUSTOM_EDITTEXT;
- case WidgetType.CUSTOM_UNSELECTABLE_TEXTVIEW:
- return CUSTOM_UNSELECTABLE_TEXTVIEW;
- default:
- return UNKNOWN;
- }
- }
-
- private String getModelName(@Nullable SelectionEvent event) {
- return event == null
- ? SelectionEvent.NO_VERSION_TAG
- : Objects.toString(event.mVersionTag, SelectionEvent.NO_VERSION_TAG);
- }
-
- private static String createSessionId() {
- return UUID.randomUUID().toString();
- }
-
- private static void debugLog(LogMaker log) {
- if (!DEBUG_LOG_ENABLED) return;
-
- final String widgetType = Objects.toString(log.getTaggedData(WIDGET_TYPE), UNKNOWN);
- final String widgetVersion = Objects.toString(log.getTaggedData(WIDGET_VERSION), "");
- final String widget = widgetVersion.isEmpty()
- ? widgetType : widgetType + "-" + widgetVersion;
- final int index = Integer.parseInt(Objects.toString(log.getTaggedData(INDEX), ZERO));
- if (log.getType() == MetricsEvent.ACTION_TEXT_SELECTION_START) {
- String sessionId = Objects.toString(log.getTaggedData(SESSION_ID), "");
- sessionId = sessionId.substring(sessionId.lastIndexOf("-") + 1);
- Log.d(LOG_TAG, String.format("New selection session: %s (%s)", widget, sessionId));
- }
-
- final String model = Objects.toString(log.getTaggedData(MODEL_NAME), UNKNOWN);
- final String entity = Objects.toString(log.getTaggedData(ENTITY_TYPE), UNKNOWN);
- final String type = getLogTypeString(log.getType());
- final int smartStart = Integer.parseInt(
- Objects.toString(log.getTaggedData(SMART_START), ZERO));
- final int smartEnd = Integer.parseInt(
- Objects.toString(log.getTaggedData(SMART_END), ZERO));
- final int eventStart = Integer.parseInt(
- Objects.toString(log.getTaggedData(EVENT_START), ZERO));
- final int eventEnd = Integer.parseInt(
- Objects.toString(log.getTaggedData(EVENT_END), ZERO));
-
- Log.d(LOG_TAG, String.format("%2d: %s/%s, range=%d,%d - smart_range=%d,%d (%s/%s)",
- index, type, entity, eventStart, eventEnd, smartStart, smartEnd, widget, model));
- }
-
- /**
- * A selection event.
- * Specify index parameters as word token indices.
- */
- public static final class SelectionEvent {
-
- /**
- * Use this to specify an indeterminate positive index.
- */
- public static final int OUT_OF_BOUNDS = Integer.MAX_VALUE;
-
- /**
- * Use this to specify an indeterminate negative index.
- */
- public static final int OUT_OF_BOUNDS_NEGATIVE = Integer.MIN_VALUE;
-
- private static final String NO_VERSION_TAG = "";
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef({ActionType.OVERTYPE, ActionType.COPY, ActionType.PASTE, ActionType.CUT,
- ActionType.SHARE, ActionType.SMART_SHARE, ActionType.DRAG, ActionType.ABANDON,
- ActionType.OTHER, ActionType.SELECT_ALL, ActionType.RESET})
- public @interface ActionType {
- /** User typed over the selection. */
- int OVERTYPE = 100;
- /** User copied the selection. */
- int COPY = 101;
- /** User pasted over the selection. */
- int PASTE = 102;
- /** User cut the selection. */
- int CUT = 103;
- /** User shared the selection. */
- int SHARE = 104;
- /** User clicked the textAssist menu item. */
- int SMART_SHARE = 105;
- /** User dragged+dropped the selection. */
- int DRAG = 106;
- /** User abandoned the selection. */
- int ABANDON = 107;
- /** User performed an action on the selection. */
- int OTHER = 108;
-
- /* Non-terminal actions. */
- /** User activated Select All */
- int SELECT_ALL = 200;
- /** User reset the smart selection. */
- int RESET = 201;
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef({ActionType.OVERTYPE, ActionType.COPY, ActionType.PASTE, ActionType.CUT,
- ActionType.SHARE, ActionType.SMART_SHARE, ActionType.DRAG, ActionType.ABANDON,
- ActionType.OTHER, ActionType.SELECT_ALL, ActionType.RESET,
- EventType.SELECTION_STARTED, EventType.SELECTION_MODIFIED,
- EventType.SMART_SELECTION_SINGLE, EventType.SMART_SELECTION_MULTI,
- EventType.AUTO_SELECTION})
- private @interface EventType {
- /** User started a new selection. */
- int SELECTION_STARTED = 1;
- /** User modified an existing selection. */
- int SELECTION_MODIFIED = 2;
- /** Smart selection triggered for a single token (word). */
- int SMART_SELECTION_SINGLE = 3;
- /** Smart selection triggered spanning multiple tokens (words). */
- int SMART_SELECTION_MULTI = 4;
- /** Something else other than User or the default TextClassifier triggered a selection. */
- int AUTO_SELECTION = 5;
- }
-
- private final int mStart;
- private final int mEnd;
- private @EventType int mEventType;
- private final @TextClassifier.EntityType String mEntityType;
- private final String mVersionTag;
-
- private SelectionEvent(
- int start, int end, int eventType,
- @TextClassifier.EntityType String entityType, String versionTag) {
- Preconditions.checkArgument(end >= start, "end cannot be less than start");
- mStart = start;
- mEnd = end;
- mEventType = eventType;
- mEntityType = Objects.requireNonNull(entityType);
- mVersionTag = Objects.requireNonNull(versionTag);
- }
-
- /**
- * Creates a "selection started" event.
- *
- * @param start the word index of the selected word
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public static SelectionEvent selectionStarted(int start) {
- return new SelectionEvent(
- start, start + 1, EventType.SELECTION_STARTED,
- TextClassifier.TYPE_UNKNOWN, NO_VERSION_TAG);
- }
-
- /**
- * Creates a "selection modified" event.
- * Use when the user modifies the selection.
- *
- * @param start the start word (inclusive) index of the selection
- * @param end the end word (exclusive) index of the selection
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public static SelectionEvent selectionModified(int start, int end) {
- return new SelectionEvent(
- start, end, EventType.SELECTION_MODIFIED,
- TextClassifier.TYPE_UNKNOWN, NO_VERSION_TAG);
- }
-
- /**
- * Creates a "selection modified" event.
- * Use when the user modifies the selection and the selection's entity type is known.
- *
- * @param start the start word (inclusive) index of the selection
- * @param end the end word (exclusive) index of the selection
- * @param classification the TextClassification object returned by the TextClassifier that
- * classified the selected text
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public static SelectionEvent selectionModified(
- int start, int end, @NonNull TextClassification classification) {
- final String entityType = classification.getEntityCount() > 0
- ? classification.getEntity(0)
- : TextClassifier.TYPE_UNKNOWN;
- final String versionTag = getVersionInfo(classification.getId());
- return new SelectionEvent(
- start, end, EventType.SELECTION_MODIFIED, entityType, versionTag);
- }
-
- /**
- * Creates a "selection modified" event.
- * Use when a TextClassifier modifies the selection.
- *
- * @param start the start word (inclusive) index of the selection
- * @param end the end word (exclusive) index of the selection
- * @param selection the TextSelection object returned by the TextClassifier for the
- * specified selection
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public static SelectionEvent selectionModified(
- int start, int end, @NonNull TextSelection selection) {
- final boolean smartSelection = getSourceClassifier(selection.getId())
- .equals(TextClassifier.DEFAULT_LOG_TAG);
- final int eventType;
- if (smartSelection) {
- eventType = end - start > 1
- ? EventType.SMART_SELECTION_MULTI
- : EventType.SMART_SELECTION_SINGLE;
-
- } else {
- eventType = EventType.AUTO_SELECTION;
- }
- final String entityType = selection.getEntityCount() > 0
- ? selection.getEntity(0)
- : TextClassifier.TYPE_UNKNOWN;
- final String versionTag = getVersionInfo(selection.getId());
- return new SelectionEvent(start, end, eventType, entityType, versionTag);
- }
-
- /**
- * Creates an event specifying an action taken on a selection.
- * Use when the user clicks on an action to act on the selected text.
- *
- * @param start the start word (inclusive) index of the selection
- * @param end the end word (exclusive) index of the selection
- * @param actionType the action that was performed on the selection
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public static SelectionEvent selectionAction(
- int start, int end, @ActionType int actionType) {
- return new SelectionEvent(
- start, end, actionType, TextClassifier.TYPE_UNKNOWN, NO_VERSION_TAG);
- }
-
- /**
- * Creates an event specifying an action taken on a selection.
- * Use when the user clicks on an action to act on the selected text and the selection's
- * entity type is known.
- *
- * @param start the start word (inclusive) index of the selection
- * @param end the end word (exclusive) index of the selection
- * @param actionType the action that was performed on the selection
- * @param classification the TextClassification object returned by the TextClassifier that
- * classified the selected text
- */
- @UnsupportedAppUsage(trackingBug = 136637107, maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "See {@link android.view.textclassifier.TextClassifier}.")
- public static SelectionEvent selectionAction(
- int start, int end, @ActionType int actionType,
- @NonNull TextClassification classification) {
- final String entityType = classification.getEntityCount() > 0
- ? classification.getEntity(0)
- : TextClassifier.TYPE_UNKNOWN;
- final String versionTag = getVersionInfo(classification.getId());
- return new SelectionEvent(start, end, actionType, entityType, versionTag);
- }
-
- @VisibleForTesting
- public static String getVersionInfo(String signature) {
- final int start = signature.indexOf("|") + 1;
- final int end = signature.indexOf("|", start);
- if (start >= 1 && end >= start) {
- return signature.substring(start, end);
- }
- return "";
- }
-
- private static String getSourceClassifier(String signature) {
- final int end = signature.indexOf("|");
- if (end >= 0) {
- return signature.substring(0, end);
- }
- return "";
- }
-
- private boolean isTerminal() {
- switch (mEventType) {
- case ActionType.OVERTYPE: // fall through
- case ActionType.COPY: // fall through
- case ActionType.PASTE: // fall through
- case ActionType.CUT: // fall through
- case ActionType.SHARE: // fall through
- case ActionType.SMART_SHARE: // fall through
- case ActionType.DRAG: // fall through
- case ActionType.ABANDON: // fall through
- case ActionType.OTHER: // fall through
- return true;
- default:
- return false;
- }
- }
- }
-}
diff --git a/core/java/android/webkit/CookieManager.java b/core/java/android/webkit/CookieManager.java
index ff80ef7..f62a28e 100644
--- a/core/java/android/webkit/CookieManager.java
+++ b/core/java/android/webkit/CookieManager.java
@@ -268,17 +268,28 @@
protected abstract boolean allowFileSchemeCookiesImpl();
/**
- * Sets whether the application's {@link WebView} instances should send and
- * accept cookies for file scheme URLs.
- * Use of cookies with file scheme URLs is potentially insecure and turned
- * off by default.
- * Do not use this feature unless you can be sure that no unintentional
- * sharing of cookie data can take place.
+ * Sets whether the application's {@link WebView} instances should send and accept cookies for
+ * file scheme URLs.
* <p>
- * Note that calls to this method will have no effect if made after a
- * {@link WebView} or CookieManager instance has been created.
+ * Use of cookies with file scheme URLs is potentially insecure and turned off by default. All
+ * {@code file://} URLs share all their cookies, which may lead to leaking private app cookies
+ * (ex. any malicious file can access cookies previously set by other (trusted) files).
+ * <p class="note">
+ * Loading content via {@code file://} URLs is generally discouraged. See the note in
+ * {@link WebSettings#setAllowFileAccess}.
+ * Using <a href="{@docRoot}reference/androidx/webkit/WebViewAssetLoader.html">
+ * androidx.webkit.WebViewAssetLoader</a> to load files over {@code http(s)://} URLs allows
+ * the standard web security model to be used for setting and sharing cookies for local files.
+ * <p>
+ * Note that calls to this method will have no effect if made after calling other
+ * {@link CookieManager} APIs.
+ *
+ * @deprecated This setting is not secure, please use
+ * <a href="{@docRoot}reference/androidx/webkit/WebViewAssetLoader.html">
+ * androidx.webkit.WebViewAssetLoader</a> instead.
*/
// Static for backward compatibility.
+ @Deprecated
public static void setAcceptFileSchemeCookies(boolean accept) {
getInstance().setAcceptFileSchemeCookiesImpl(accept);
}
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 53541f7..35dd576 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -983,48 +983,63 @@
public abstract void setJavaScriptEnabled(boolean flag);
/**
- * Sets whether JavaScript running in the context of a file scheme URL
- * should be allowed to access content from any origin. This includes
- * access to content from other file scheme URLs. See
- * {@link #setAllowFileAccessFromFileURLs}. To enable the most restrictive,
- * and therefore secure policy, this setting should be disabled.
- * Note that this setting affects only JavaScript access to file scheme
- * resources. Other access to such resources, for example, from image HTML
- * elements, is unaffected. To prevent possible violation of same domain policy
- * when targeting {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and earlier,
- * you should explicitly set this value to {@code false}.
+ * Sets whether cross-origin requests in the context of a file scheme URL should be allowed to
+ * access content from <i>any</i> origin. This includes access to content from other file
+ * scheme URLs or web contexts. Note that some access such as image HTML elements doesn't
+ * follow same-origin rules and isn't affected by this setting.
+ * <p>
+ * <b>Don't</b> enable this setting if you open files that may be created or altered by
+ * external sources. Enabling this setting allows malicious scripts loaded in a {@code file://}
+ * context to launch cross-site scripting attacks, either accessing arbitrary local files
+ * including WebView cookies, app private data or even credentials used on arbitrary web sites.
+ * <p class="note">
+ * Loading content via {@code file://} URLs is generally discouraged. See the note in
+ * {@link #setAllowFileAccess}.
* <p>
* The default value is {@code true} for apps targeting
- * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and below,
- * and {@code false} when targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
- * and above.
+ * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and below, and {@code false}
+ * when targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN} and above. To prevent
+ * possible violation of same domain policy when targeting
+ * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and earlier, you should
+ * explicitly set this value to {@code false}.
*
- * @param flag whether JavaScript running in the context of a file scheme
- * URL should be allowed to access content from any origin
+ * @param flag whether JavaScript running in the context of a file scheme URL should be allowed
+ * to access content from any origin
+ * @deprecated This setting is not secure, please use
+ * <a href="{@docRoot}reference/androidx/webkit/WebViewAssetLoader.html">
+ * androidx.webkit.WebViewAssetLoader</a> to load file content securely.
*/
+ @Deprecated
public abstract void setAllowUniversalAccessFromFileURLs(boolean flag);
/**
- * Sets whether JavaScript running in the context of a file scheme URL
- * should be allowed to access content from other file scheme URLs. To
- * enable the most restrictive, and therefore secure, policy this setting
- * should be disabled. Note that the value of this setting is ignored if
- * the value of {@link #getAllowUniversalAccessFromFileURLs} is {@code true}.
- * Note too, that this setting affects only JavaScript access to file scheme
- * resources. Other access to such resources, for example, from image HTML
- * elements, is unaffected. To prevent possible violation of same domain policy
- * when targeting {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and earlier,
- * you should explicitly set this value to {@code false}.
+ * Sets whether cross-origin requests in the context of a file scheme URL should be allowed to
+ * access content from other file scheme URLs. Note that some accesses such as image HTML
+ * elements don't follow same-origin rules and aren't affected by this setting.
* <p>
- * The default value is {@code true} for apps targeting
- * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and below,
- * and {@code false} when targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
- * and above.
+ * <b>Don't</b> enable this setting if you open files that may be created or altered by
+ * external sources. Enabling this setting allows malicious scripts loaded in a {@code file://}
+ * context to access arbitrary local files including WebView cookies and app private data.
+ * <p class="note">
+ * Loading content via {@code file://} URLs is generally discouraged. See the note in
+ * {@link #setAllowFileAccess}.
+ * <p>
+ * Note that the value of this setting is ignored if the value of
+ * {@link #getAllowUniversalAccessFromFileURLs} is {@code true}. The default value is
+ * {@code true} for apps targeting {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1}
+ * and below, and {@code false} when targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN}
+ * and above. To prevent possible violation of same domain policy when targeting
+ * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH_MR1} and earlier, you should
+ * explicitly set this value to {@code false}.
*
* @param flag whether JavaScript running in the context of a file scheme
* URL should be allowed to access content from other file
* scheme URLs
+ * @deprecated This setting is not secure, please use
+ * <a href="{@docRoot}reference/androidx/webkit/WebViewAssetLoader.html">
+ * androidx.webkit.WebViewAssetLoader</a> to load file content securely.
*/
+ @Deprecated
public abstract void setAllowFileAccessFromFileURLs(boolean flag);
/**
diff --git a/core/java/android/widget/AnalogClock.java b/core/java/android/widget/AnalogClock.java
index d165bd0..ffdb89d 100644
--- a/core/java/android/widget/AnalogClock.java
+++ b/core/java/android/widget/AnalogClock.java
@@ -261,7 +261,7 @@
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
- String tz = intent.getStringExtra("time-zone");
+ String tz = intent.getStringExtra(Intent.EXTRA_TIMEZONE);
mClock = Clock.system(ZoneId.of(tz));
}
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index 13c1f67..16d9ed3 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -4587,8 +4587,9 @@
protected int mHorizontalGravity;
// Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up
private float mTouchOffsetY;
- // Where the touch position should be on the handle to ensure a maximum cursor visibility
- private float mIdealVerticalOffset;
+ // Where the touch position should be on the handle to ensure a maximum cursor visibility.
+ // This is the distance in pixels from the top of the handle view.
+ private final float mIdealVerticalOffset;
// Parent's (TextView) previous position in window
private int mLastParentX, mLastParentY;
// Parent's (TextView) previous position on screen
@@ -4612,6 +4613,11 @@
// when magnifier is used.
private float mTextViewScaleX;
private float mTextViewScaleY;
+ /**
+ * The vertical distance in pixels from finger to the cursor Y while dragging.
+ * See {@link Editor.InsertionPointCursorController#getLineDuringDrag}.
+ */
+ private final int mIdealFingerToCursorOffset;
private HandleView(Drawable drawableLtr, Drawable drawableRtl, final int id) {
super(mTextView.getContext());
@@ -4632,13 +4638,28 @@
final int handleHeight = getPreferredHeight();
mTouchOffsetY = -0.3f * handleHeight;
- mIdealVerticalOffset = 0.7f * handleHeight;
+ final int distance = AppGlobals.getIntCoreSetting(
+ WidgetFlags.KEY_FINGER_TO_CURSOR_DISTANCE,
+ WidgetFlags.FINGER_TO_CURSOR_DISTANCE_DEFAULT);
+ if (distance < 0 || distance > 100) {
+ mIdealVerticalOffset = 0.7f * handleHeight;
+ mIdealFingerToCursorOffset = (int)(mIdealVerticalOffset - mTouchOffsetY);
+ } else {
+ mIdealFingerToCursorOffset = (int) TypedValue.applyDimension(
+ TypedValue.COMPLEX_UNIT_DIP, distance,
+ mTextView.getContext().getResources().getDisplayMetrics());
+ mIdealVerticalOffset = mIdealFingerToCursorOffset + mTouchOffsetY;
+ }
}
public float getIdealVerticalOffset() {
return mIdealVerticalOffset;
}
+ final int getIdealFingerToCursorOffset() {
+ return mIdealFingerToCursorOffset;
+ }
+
void setDrawables(final Drawable drawableLtr, final Drawable drawableRtl) {
mDrawableLtr = drawableLtr;
mDrawableRtl = drawableRtl;
@@ -6123,36 +6144,34 @@
*/
private int getLineDuringDrag(MotionEvent event) {
final Layout layout = mTextView.getLayout();
- if (mTouchState.isOnHandle()) {
- // The drag was initiated from the handle, so no need to apply the snap logic. See
- // InsertionHandleView.touchThrough().
+ if (mPrevLineDuringDrag == UNSET_LINE) {
return getCurrentLineAdjustedForSlop(layout, mPrevLineDuringDrag, event.getY());
}
+ // In case of touch through on handle (when isOnHandle() returns true), event.getY()
+ // returns the midpoint of the cursor vertical bar, while event.getRawY() returns the
+ // finger location on the screen. See {@link InsertionHandleView#touchThrough}.
+ final float fingerY = mTouchState.isOnHandle()
+ ? event.getRawY() - mTextView.getLocationOnScreen()[1]
+ : event.getY();
+ final float cursorY = fingerY - getHandle().getIdealFingerToCursorOffset();
+ int line = getCurrentLineAdjustedForSlop(layout, mPrevLineDuringDrag, cursorY);
if (mIsTouchSnappedToHandleDuringDrag) {
- float cursorY = event.getY() - getHandle().getIdealVerticalOffset();
- return getCurrentLineAdjustedForSlop(layout, mPrevLineDuringDrag, cursorY);
- }
- int line = getCurrentLineAdjustedForSlop(layout, mPrevLineDuringDrag, event.getY());
- if (mPrevLineDuringDrag == UNSET_LINE || line <= mPrevLineDuringDrag) {
- // User's finger is on the same line or moving up; continue positioning the cursor
- // directly at the touch location.
+ // Just returns the line hit by cursor Y when already snapped.
return line;
}
- // User's finger is moving downwards; delay jumping to the lower line to allow the
- // touch to move to the handle.
- float cursorY = event.getY() - getHandle().getIdealVerticalOffset();
- line = getCurrentLineAdjustedForSlop(layout, mPrevLineDuringDrag, cursorY);
if (line < mPrevLineDuringDrag) {
- return mPrevLineDuringDrag;
+ // The cursor Y aims too high & not yet snapped, check the finger Y.
+ // If finger Y is moving downwards, don't jump to lower line (until snap).
+ // If finger Y is moving upwards, can jump to upper line.
+ return Math.min(mPrevLineDuringDrag,
+ getCurrentLineAdjustedForSlop(layout, mPrevLineDuringDrag, fingerY));
}
- // User's finger is now over the handle, at the ideal offset from the cursor. From now
- // on, position the cursor higher up from the actual touch location so that the user's
- // finger stays "snapped" to the handle. This provides better visibility of the text.
+ // The cursor Y aims not too high, so snap!
mIsTouchSnappedToHandleDuringDrag = true;
if (TextView.DEBUG_CURSOR) {
logCursor("InsertionPointCursorController",
- "snapped touch to handle: eventY=%d, cursorY=%d, mLastLine=%d, line=%d",
- (int) event.getY(), (int) cursorY, mPrevLineDuringDrag, line);
+ "snapped touch to handle: fingerY=%d, cursorY=%d, mLastLine=%d, line=%d",
+ (int) fingerY, (int) cursorY, mPrevLineDuringDrag, line);
}
return line;
}
@@ -6252,7 +6271,7 @@
}
}
- private InsertionHandleView getHandle() {
+ public InsertionHandleView getHandle() {
if (mHandle == null) {
loadHandleDrawables(false /* overwrite */);
mHandle = new InsertionHandleView(mSelectHandleCenter);
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 01a0e9b..7f6c0d2 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -2818,7 +2818,7 @@
/**
* When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very
- * costly to set PendingIntents on the individual items, and is hence not permitted. Instead
+ * costly to set PendingIntents on the individual items, and is hence not recommended. Instead
* this method should be used to set a single PendingIntent template on the collection, and
* individual items can differentiate their on-click behavior using
* {@link RemoteViews#setOnClickFillInIntent(int, Intent)}.
@@ -2834,7 +2834,7 @@
/**
* When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very
- * costly to set PendingIntents on the individual items, and is hence not permitted. Instead
+ * costly to set PendingIntents on the individual items, and is hence not recommended. Instead
* a single PendingIntent template can be set on the collection, see {@link
* RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click
* action of a given item can be distinguished by setting a fillInIntent on that item. The
@@ -3960,7 +3960,7 @@
/**
* When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is
- * very costly to set PendingIntents on the individual items, and is hence not permitted.
+ * very costly to set PendingIntents on the individual items, and is hence not recommended.
* Instead a single PendingIntent template can be set on the collection, see {@link
* RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click
* action of a given item can be distinguished by setting a fillInIntent on that item. The
diff --git a/core/java/android/widget/SelectionActionModeHelper.java b/core/java/android/widget/SelectionActionModeHelper.java
index 4ef3f61..45943f5 100644
--- a/core/java/android/widget/SelectionActionModeHelper.java
+++ b/core/java/android/widget/SelectionActionModeHelper.java
@@ -39,7 +39,6 @@
import android.view.textclassifier.ExtrasUtils;
import android.view.textclassifier.SelectionEvent;
import android.view.textclassifier.SelectionEvent.InvocationMethod;
-import android.view.textclassifier.SelectionSessionLogger;
import android.view.textclassifier.TextClassification;
import android.view.textclassifier.TextClassificationConstants;
import android.view.textclassifier.TextClassificationContext;
@@ -705,7 +704,7 @@
SelectionMetricsLogger(TextView textView) {
Objects.requireNonNull(textView);
mEditTextLogger = textView.isTextEditable();
- mTokenIterator = SelectionSessionLogger.getTokenIterator(textView.getTextLocale());
+ mTokenIterator = BreakIterator.getWordInstance(textView.getTextLocale());
}
public void logSelectionStarted(
diff --git a/core/java/android/widget/TextClock.java b/core/java/android/widget/TextClock.java
index 8565493..6432438 100644
--- a/core/java/android/widget/TextClock.java
+++ b/core/java/android/widget/TextClock.java
@@ -173,7 +173,7 @@
return; // Test disabled the clock ticks
}
if (mTimeZone == null && Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
- final String timeZone = intent.getStringExtra("time-zone");
+ final String timeZone = intent.getStringExtra(Intent.EXTRA_TIMEZONE);
createTime(timeZone);
} else if (!mShouldRunTicker && (Intent.ACTION_TIME_TICK.equals(intent.getAction())
|| Intent.ACTION_TIME_CHANGED.equals(intent.getAction()))) {
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index f3243aa..2168018 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -6607,6 +6607,16 @@
return mTransformation instanceof PasswordTransformationMethod;
}
+ /**
+ * Returns true if the current inputType is any type of password.
+ *
+ * @hide
+ */
+ public boolean isAnyPasswordInputType() {
+ final int inputType = getInputType();
+ return isPasswordInputType(inputType) || isVisiblePasswordInputType(inputType);
+ }
+
static boolean isPasswordInputType(int inputType) {
final int variation =
inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
@@ -11763,13 +11773,8 @@
if (isTextEditable() && isFocused()) {
CharSequence imeActionLabel = mContext.getResources().getString(
com.android.internal.R.string.keyboardview_keycode_enter);
- if (getImeActionId() != 0 && getImeActionLabel() != null) {
+ if (getImeActionLabel() != null) {
imeActionLabel = getImeActionLabel();
- final int imeActionId = getImeActionId();
- // put ime action id into the extra data with ACTION_ARGUMENT_IME_ACTION_ID_INT.
- final Bundle argument = info.getExtras();
- argument.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_IME_ACTION_ID_INT,
- imeActionId);
}
AccessibilityNodeInfo.AccessibilityAction action =
new AccessibilityNodeInfo.AccessibilityAction(
@@ -11881,7 +11886,7 @@
if (extraDataKey.equals(AccessibilityNodeInfo.EXTRA_DATA_RENDERING_INFO_KEY)) {
final AccessibilityNodeInfo.ExtraRenderingInfo extraRenderingInfo =
AccessibilityNodeInfo.ExtraRenderingInfo.obtain();
- extraRenderingInfo.setLayoutParams(getLayoutParams().width, getLayoutParams().height);
+ extraRenderingInfo.setLayoutSize(getLayoutParams().width, getLayoutParams().height);
extraRenderingInfo.setTextSizeInPx(getTextSize());
extraRenderingInfo.setTextSizeUnit(getTextSizeUnit());
info.setExtraRenderingInfo(extraRenderingInfo);
@@ -12100,13 +12105,7 @@
} return true;
case R.id.accessibilityActionImeEnter: {
if (isFocused() && isTextEditable()) {
- final int imeActionId = (arguments != null) ? arguments.getInt(
- AccessibilityNodeInfo.ACTION_ARGUMENT_IME_ACTION_ID_INT,
- EditorInfo.IME_ACTION_UNSPECIFIED)
- : EditorInfo.IME_ACTION_UNSPECIFIED;
- if (imeActionId == getImeActionId()) {
- onEditorAction(imeActionId);
- }
+ onEditorAction(getImeActionId());
}
} return true;
default: {
diff --git a/core/java/android/widget/WidgetFlags.java b/core/java/android/widget/WidgetFlags.java
index bce5497..09ab5aa 100644
--- a/core/java/android/widget/WidgetFlags.java
+++ b/core/java/android/widget/WidgetFlags.java
@@ -41,6 +41,25 @@
public static final boolean ENABLE_CURSOR_DRAG_FROM_ANYWHERE_DEFAULT = true;
/**
+ * The flag of finger-to-cursor distance in DP for cursor dragging.
+ * The value unit is DP and the range is {0..100}. If the value is out of range, the legacy
+ * value, which is based on handle size, will be used.
+ */
+ public static final String FINGER_TO_CURSOR_DISTANCE =
+ "CursorControlFeature__finger_to_cursor_distance";
+
+ /**
+ * The key used in app core settings for the flag {@link #FINGER_TO_CURSOR_DISTANCE}.
+ */
+ public static final String KEY_FINGER_TO_CURSOR_DISTANCE =
+ "widget__finger_to_cursor_distance";
+
+ /**
+ * Default value for the flag {@link #FINGER_TO_CURSOR_DISTANCE}.
+ */
+ public static final int FINGER_TO_CURSOR_DISTANCE_DEFAULT = -1;
+
+ /**
* Whether additional gestures should be enabled for the insertion cursor handle (e.g.
* long-press or double-tap on the handle to trigger selection).
*/
diff --git a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
index 5cdcab0..54ea57a 100644
--- a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
+++ b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java
@@ -56,6 +56,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
@@ -133,7 +134,7 @@
// Keep track of state of shortcut settings
final ContentObserver co = new ContentObserver(handler) {
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags, int userId) {
if (userId == mUserId) {
onSettingsChanged();
}
diff --git a/core/java/com/android/internal/accessibility/common/ShortcutConstants.java b/core/java/com/android/internal/accessibility/common/ShortcutConstants.java
index 1daa505..79b34c0 100644
--- a/core/java/com/android/internal/accessibility/common/ShortcutConstants.java
+++ b/core/java/com/android/internal/accessibility/common/ShortcutConstants.java
@@ -28,8 +28,6 @@
private ShortcutConstants() {}
public static final char SERVICES_SEPARATOR = ':';
- public static final float DISABLED_ALPHA = 0.5f;
- public static final float ENABLED_ALPHA = 1.0f;
/**
* Annotation for different user shortcut type UI type.
@@ -80,6 +78,21 @@
}
/**
+ * Annotation for different shortcut target.
+ */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({
+ TargetType.ACCESSIBILITY_SERVICE,
+ TargetType.ACCESSIBILITY_ACTIVITY,
+ TargetType.WHITE_LISTING,
+ })
+ public @interface TargetType {
+ int ACCESSIBILITY_SERVICE = 0;
+ int ACCESSIBILITY_ACTIVITY = 1;
+ int WHITE_LISTING = 2;
+ }
+
+ /**
* Annotation for different shortcut menu mode.
*
* {@code LAUNCH} for clicking list item to trigger the service callback.
diff --git a/core/java/com/android/internal/accessibility/util/ShortcutUtils.java b/core/java/com/android/internal/accessibility/util/ShortcutUtils.java
index 7df712f..717e780 100644
--- a/core/java/com/android/internal/accessibility/util/ShortcutUtils.java
+++ b/core/java/com/android/internal/accessibility/util/ShortcutUtils.java
@@ -39,6 +39,33 @@
new TextUtils.SimpleStringSplitter(SERVICES_SEPARATOR);
/**
+ * Opts in component name into colon-separated {@link UserShortcutType}
+ * key's string in Settings.
+ *
+ * @param context The current context.
+ * @param shortcutType The preferred shortcut type user selected.
+ * @param componentId The component id that need to be opted out from Settings.
+ */
+ public static void optInValueToSettings(Context context, @UserShortcutType int shortcutType,
+ String componentId) {
+ final StringJoiner joiner = new StringJoiner(String.valueOf(SERVICES_SEPARATOR));
+ final String targetKey = convertToKey(shortcutType);
+ final String targetString = Settings.Secure.getString(context.getContentResolver(),
+ targetKey);
+
+ if (hasValueInSettings(context, shortcutType, componentId)) {
+ return;
+ }
+
+ if (!TextUtils.isEmpty(targetString)) {
+ joiner.add(targetString);
+ }
+ joiner.add(componentId);
+
+ Settings.Secure.putString(context.getContentResolver(), targetKey, joiner.toString());
+ }
+
+ /**
* Opts out component name into colon-separated {@code shortcutType} key's string in Settings.
*
* @param context The current context.
diff --git a/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java b/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java
index bcf731d..ec2653f 100644
--- a/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java
+++ b/core/java/com/android/internal/app/AbstractMultiProfilePagerAdapter.java
@@ -26,6 +26,7 @@
import android.content.Intent;
import android.content.pm.IPackageManager;
import android.content.pm.ResolveInfo;
+import android.os.AsyncTask;
import android.os.UserHandle;
import android.os.UserManager;
import android.stats.devicepolicy.DevicePolicyEnums;
@@ -90,7 +91,9 @@
@Override
public void requestQuietModeEnabled(boolean enabled, UserHandle workProfileUserHandle) {
- userManager.requestQuietModeEnabled(enabled, workProfileUserHandle);
+ AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
+ userManager.requestQuietModeEnabled(enabled, workProfileUserHandle);
+ });
mIsWaitingToEnableWorkProfile = true;
}
};
@@ -284,7 +287,7 @@
}
private int userHandleToPageIndex(UserHandle userHandle) {
- if (userHandle == getPersonalListAdapter().mResolverListController.getUserHandle()) {
+ if (userHandle.equals(getPersonalListAdapter().mResolverListController.getUserHandle())) {
return PROFILE_PERSONAL;
} else {
return PROFILE_WORK;
@@ -293,17 +296,14 @@
private boolean rebuildTab(ResolverListAdapter activeListAdapter, boolean doPostProcessing) {
UserHandle listUserHandle = activeListAdapter.getUserHandle();
- if (listUserHandle == mWorkProfileUserHandle
+ if (listUserHandle.equals(mWorkProfileUserHandle)
&& mInjector.isQuietModeEnabled(mWorkProfileUserHandle)) {
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.RESOLVER_EMPTY_STATE_WORK_APPS_DISABLED)
.setStrings(getMetricsCategory())
.write();
- showEmptyState(activeListAdapter,
- R.drawable.ic_work_apps_off,
- R.string.resolver_turn_on_work_apps,
- R.string.resolver_turn_on_work_apps_explanation,
- (View.OnClickListener) v -> {
+ showWorkProfileOffEmptyState(activeListAdapter,
+ v -> {
ProfileDescriptor descriptor = getItem(
userHandleToPageIndex(activeListAdapter.getUserHandle()));
showSpinner(descriptor.getEmptyStateView());
@@ -314,32 +314,34 @@
if (UserHandle.myUserId() != listUserHandle.getIdentifier()) {
if (!mInjector.hasCrossProfileIntents(activeListAdapter.getIntents(),
UserHandle.myUserId(), listUserHandle.getIdentifier())) {
- if (listUserHandle == mPersonalProfileUserHandle) {
+ if (listUserHandle.equals(mPersonalProfileUserHandle)) {
DevicePolicyEventLogger.createEvent(
DevicePolicyEnums.RESOLVER_EMPTY_STATE_NO_SHARING_TO_PERSONAL)
.setStrings(getMetricsCategory())
.write();
- showEmptyState(activeListAdapter,
- R.drawable.ic_sharing_disabled,
- R.string.resolver_cant_share_with_personal_apps,
- R.string.resolver_cant_share_cross_profile_explanation);
+ showNoWorkToPersonalIntentsEmptyState(activeListAdapter);
} else {
DevicePolicyEventLogger.createEvent(
DevicePolicyEnums.RESOLVER_EMPTY_STATE_NO_SHARING_TO_WORK)
.setStrings(getMetricsCategory())
.write();
- showEmptyState(activeListAdapter,
- R.drawable.ic_sharing_disabled,
- R.string.resolver_cant_share_with_work_apps,
- R.string.resolver_cant_share_cross_profile_explanation);
+ showNoPersonalToWorkIntentsEmptyState(activeListAdapter);
}
return false;
}
}
- showListView(activeListAdapter);
return activeListAdapter.rebuildList(doPostProcessing);
}
+ protected abstract void showWorkProfileOffEmptyState(
+ ResolverListAdapter activeListAdapter, View.OnClickListener listener);
+
+ protected abstract void showNoPersonalToWorkIntentsEmptyState(
+ ResolverListAdapter activeListAdapter);
+
+ protected abstract void showNoWorkToPersonalIntentsEmptyState(
+ ResolverListAdapter activeListAdapter);
+
void showEmptyState(ResolverListAdapter listAdapter) {
UserHandle listUserHandle = listAdapter.getUserHandle();
if (UserHandle.myUserId() == listUserHandle.getIdentifier()
@@ -353,16 +355,16 @@
showEmptyState(listAdapter,
R.drawable.ic_no_apps,
R.string.resolver_no_apps_available,
- R.string.resolver_no_apps_available_explanation);
+ /* subtitleRes */ 0);
}
}
- private void showEmptyState(ResolverListAdapter activeListAdapter,
+ protected void showEmptyState(ResolverListAdapter activeListAdapter,
@DrawableRes int iconRes, @StringRes int titleRes, @StringRes int subtitleRes) {
showEmptyState(activeListAdapter, iconRes, titleRes, subtitleRes, /* buttonOnClick */ null);
}
- private void showEmptyState(ResolverListAdapter activeListAdapter,
+ protected void showEmptyState(ResolverListAdapter activeListAdapter,
@DrawableRes int iconRes, @StringRes int titleRes, @StringRes int subtitleRes,
View.OnClickListener buttonOnClick) {
ProfileDescriptor descriptor = getItem(
@@ -379,11 +381,18 @@
title.setText(titleRes);
TextView subtitle = emptyStateView.findViewById(R.id.resolver_empty_state_subtitle);
- subtitle.setText(subtitleRes);
+ if (subtitleRes != 0) {
+ subtitle.setVisibility(View.VISIBLE);
+ subtitle.setText(subtitleRes);
+ } else {
+ subtitle.setVisibility(View.GONE);
+ }
Button button = emptyStateView.findViewById(R.id.resolver_empty_state_button);
button.setVisibility(buttonOnClick != null ? View.VISIBLE : View.GONE);
button.setOnClickListener(buttonOnClick);
+
+ activeListAdapter.markTabLoaded();
}
private void showSpinner(View emptyStateView) {
@@ -403,7 +412,7 @@
emptyStateView.findViewById(R.id.resolver_empty_state_progress).setVisibility(View.GONE);
}
- private void showListView(ResolverListAdapter activeListAdapter) {
+ protected void showListView(ResolverListAdapter activeListAdapter) {
ProfileDescriptor descriptor = getItem(
userHandleToPageIndex(activeListAdapter.getUserHandle()));
descriptor.rootView.findViewById(R.id.resolver_list).setVisibility(View.VISIBLE);
@@ -446,7 +455,7 @@
mEmptyStateView = rootView.findViewById(R.id.resolver_empty_state);
}
- private ViewGroup getEmptyStateView() {
+ protected ViewGroup getEmptyStateView() {
return mEmptyStateView;
}
}
diff --git a/core/java/com/android/internal/app/AbstractResolverComparator.java b/core/java/com/android/internal/app/AbstractResolverComparator.java
index eb74612..e0bbc04 100644
--- a/core/java/com/android/internal/app/AbstractResolverComparator.java
+++ b/core/java/com/android/internal/app/AbstractResolverComparator.java
@@ -221,6 +221,12 @@
*/
abstract float getScore(ComponentName name);
+ /**
+ * Returns the list of top K component names which have highest
+ * {@link #getScore(ComponentName)}
+ */
+ abstract List<ComponentName> getTopComponentNames(int topK);
+
/** Handles result message sent to mHandler. */
abstract void handleResultMessage(Message message);
diff --git a/core/java/com/android/internal/app/AccessibilityButtonChooserActivity.java b/core/java/com/android/internal/app/AccessibilityButtonChooserActivity.java
index 852deb2..c408641 100644
--- a/core/java/com/android/internal/app/AccessibilityButtonChooserActivity.java
+++ b/core/java/com/android/internal/app/AccessibilityButtonChooserActivity.java
@@ -23,10 +23,10 @@
import static com.android.internal.accessibility.AccessibilityShortcutController.DALTONIZER_COMPONENT_NAME;
import static com.android.internal.accessibility.AccessibilityShortcutController.MAGNIFICATION_CONTROLLER_NAME;
import static com.android.internal.accessibility.common.ShortcutConstants.AccessibilityServiceFragmentType;
-import static com.android.internal.accessibility.common.ShortcutConstants.DISABLED_ALPHA;
-import static com.android.internal.accessibility.common.ShortcutConstants.ENABLED_ALPHA;
import static com.android.internal.accessibility.common.ShortcutConstants.ShortcutMenuMode;
+import static com.android.internal.accessibility.common.ShortcutConstants.TargetType;
import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType;
+import static com.android.internal.accessibility.common.ShortcutConstants.UserShortcutType.HARDWARE;
import static com.android.internal.accessibility.common.ShortcutConstants.WhiteListingFeatureElementIndex.COMPONENT_ID;
import static com.android.internal.accessibility.common.ShortcutConstants.WhiteListingFeatureElementIndex.FRAGMENT_TYPE;
import static com.android.internal.accessibility.common.ShortcutConstants.WhiteListingFeatureElementIndex.ICON_ID;
@@ -36,6 +36,7 @@
import static com.android.internal.accessibility.util.AccessibilityUtils.setAccessibilityServiceState;
import static com.android.internal.accessibility.util.ShortcutUtils.convertToUserType;
import static com.android.internal.accessibility.util.ShortcutUtils.hasValuesInSettings;
+import static com.android.internal.accessibility.util.ShortcutUtils.optInValueToSettings;
import static com.android.internal.accessibility.util.ShortcutUtils.optOutValueFromSettings;
import static com.android.internal.util.Preconditions.checkArgument;
@@ -50,11 +51,12 @@
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
-import android.graphics.ColorMatrix;
-import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
+import android.os.Build;
import android.os.Bundle;
+import android.os.storage.StorageManager;
import android.provider.Settings;
+import android.text.BidiFormatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -62,28 +64,33 @@
import android.view.accessibility.AccessibilityManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
-import android.widget.FrameLayout;
+import android.widget.Button;
+import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
+import android.widget.Toast;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
/**
* Activity used to display and persist a service or feature target for the Accessibility button.
*/
public class AccessibilityButtonChooserActivity extends Activity {
@ShortcutType
- private int mShortcutType;
+ private static int sShortcutType;
@UserShortcutType
private int mShortcutUserType;
private final List<AccessibilityButtonTarget> mTargets = new ArrayList<>();
private AlertDialog mAlertDialog;
+ private AlertDialog mEnableDialog;
private TargetAdapter mTargetAdapter;
+ private AccessibilityButtonTarget mCurrentCheckedTarget;
private static final String[][] WHITE_LISTING_FEATURES = {
{
@@ -118,19 +125,19 @@
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
- mShortcutType = getIntent().getIntExtra(AccessibilityManager.EXTRA_SHORTCUT_TYPE,
+ sShortcutType = getIntent().getIntExtra(AccessibilityManager.EXTRA_SHORTCUT_TYPE,
/* unexpectedShortcutType */ -1);
- final boolean existInShortcutType = (mShortcutType == ACCESSIBILITY_BUTTON)
- || (mShortcutType == ACCESSIBILITY_SHORTCUT_KEY);
- checkArgument(existInShortcutType, "Unexpected shortcut type: " + mShortcutType);
+ final boolean existInShortcutType = (sShortcutType == ACCESSIBILITY_BUTTON)
+ || (sShortcutType == ACCESSIBILITY_SHORTCUT_KEY);
+ checkArgument(existInShortcutType, "Unexpected shortcut type: " + sShortcutType);
- mShortcutUserType = convertToUserType(mShortcutType);
+ mShortcutUserType = convertToUserType(sShortcutType);
- mTargets.addAll(getServiceTargets(this, mShortcutType));
+ mTargets.addAll(getServiceTargets(this, sShortcutType));
final String selectDialogTitle =
getString(R.string.accessibility_select_shortcut_menu_title);
- mTargetAdapter = new TargetAdapter(mTargets, mShortcutType);
+ mTargetAdapter = new TargetAdapter(mTargets);
mAlertDialog = new AlertDialog.Builder(this)
.setTitle(selectDialogTitle)
.setAdapter(mTargetAdapter, /* listener= */ null)
@@ -151,15 +158,21 @@
private static List<AccessibilityButtonTarget> getServiceTargets(@NonNull Context context,
@ShortcutType int shortcutType) {
+ final List<AccessibilityButtonTarget> targets = getInstalledServiceTargets(context);
+ final AccessibilityManager ams = context.getSystemService(AccessibilityManager.class);
+ final List<String> requiredTargets = ams.getAccessibilityShortcutTargets(shortcutType);
+ targets.removeIf(target -> !requiredTargets.contains(target.getId()));
+
+ return targets;
+ }
+
+ private static List<AccessibilityButtonTarget> getInstalledServiceTargets(
+ @NonNull Context context) {
final List<AccessibilityButtonTarget> targets = new ArrayList<>();
targets.addAll(getAccessibilityServiceTargets(context));
targets.addAll(getAccessibilityActivityTargets(context));
targets.addAll(getWhiteListingServiceTargets(context));
- final AccessibilityManager ams = context.getSystemService(AccessibilityManager.class);
- final List<String> requiredTargets = ams.getAccessibilityShortcutTargets(shortcutType);
- targets.removeIf(target -> !requiredTargets.contains(target.getId()));
-
return targets;
}
@@ -174,6 +187,14 @@
final List<AccessibilityButtonTarget> targets = new ArrayList<>(installedServices.size());
for (AccessibilityServiceInfo info : installedServices) {
+ final int targetSdk =
+ info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion;
+ final boolean hasRequestAccessibilityButtonFlag =
+ (info.flags & AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON) != 0;
+ if ((targetSdk < Build.VERSION_CODES.R) && !hasRequestAccessibilityButtonFlag
+ && (sShortcutType == ACCESSIBILITY_BUTTON)) {
+ continue;
+ }
targets.add(new AccessibilityButtonTarget(context, info));
}
@@ -249,35 +270,31 @@
}
}
- private void disableService(String componentId) {
+ private void setServiceEnabled(String componentId, boolean enabled) {
if (isWhiteListingService(componentId)) {
- setWhiteListingServiceEnabled(componentId, /* settingsValueOff */ 0);
+ setWhiteListingServiceEnabled(componentId,
+ enabled ? /* settingsValueOn */ 1 : /* settingsValueOff */ 0);
} else {
final ComponentName componentName = ComponentName.unflattenFromString(componentId);
- setAccessibilityServiceState(this, componentName, /* enabled= */ false);
+ setAccessibilityServiceState(this, componentName, enabled);
}
}
private static class ViewHolder {
View mItemView;
+ CheckBox mCheckBox;
ImageView mIconView;
TextView mLabelView;
- FrameLayout mItemContainer;
- ImageView mActionViewItem;
Switch mSwitchItem;
}
private static class TargetAdapter extends BaseAdapter {
@ShortcutMenuMode
private int mShortcutMenuMode = ShortcutMenuMode.LAUNCH;
- @ShortcutType
- private int mShortcutButtonType;
private List<AccessibilityButtonTarget> mButtonTargets;
- TargetAdapter(List<AccessibilityButtonTarget> targets,
- @ShortcutType int shortcutButtonType) {
+ TargetAdapter(List<AccessibilityButtonTarget> targets) {
this.mButtonTargets = targets;
- this.mShortcutButtonType = shortcutButtonType;
}
void setShortcutMenuMode(@ShortcutMenuMode int shortcutMenuMode) {
@@ -314,13 +331,11 @@
false);
holder = new ViewHolder();
holder.mItemView = convertView;
+ holder.mCheckBox = convertView.findViewById(
+ R.id.accessibility_button_target_checkbox);
holder.mIconView = convertView.findViewById(R.id.accessibility_button_target_icon);
holder.mLabelView = convertView.findViewById(
R.id.accessibility_button_target_label);
- holder.mItemContainer = convertView.findViewById(
- R.id.accessibility_button_target_item_container);
- holder.mActionViewItem = convertView.findViewById(
- R.id.accessibility_button_target_view_item);
holder.mSwitchItem = convertView.findViewById(
R.id.accessibility_button_target_switch_item);
convertView.setTag(holder);
@@ -329,9 +344,6 @@
}
final AccessibilityButtonTarget target = mButtonTargets.get(position);
- holder.mIconView.setImageDrawable(target.getDrawable());
- holder.mLabelView.setText(target.getLabel());
-
updateActionItem(context, holder, target);
return convertView;
@@ -342,58 +354,42 @@
switch (target.getFragmentType()) {
case AccessibilityServiceFragmentType.LEGACY:
- updateLegacyActionItemVisibility(context, holder);
+ updateLegacyActionItemVisibility(holder, target);
break;
case AccessibilityServiceFragmentType.INVISIBLE:
- updateInvisibleActionItemVisibility(context, holder);
+ updateInvisibleActionItemVisibility(holder, target);
break;
case AccessibilityServiceFragmentType.INTUITIVE:
updateIntuitiveActionItemVisibility(context, holder, target);
break;
case AccessibilityServiceFragmentType.BOUNCE:
- updateBounceActionItemVisibility(context, holder);
+ updateBounceActionItemVisibility(holder, target);
break;
default:
throw new IllegalStateException("Unexpected fragment type");
}
}
- private void updateLegacyActionItemVisibility(@NonNull Context context,
- @NonNull ViewHolder holder) {
+ private void updateLegacyActionItemVisibility(@NonNull ViewHolder holder,
+ AccessibilityButtonTarget target) {
final boolean isLaunchMenuMode = (mShortcutMenuMode == ShortcutMenuMode.LAUNCH);
- final boolean isHardwareButtonTriggered =
- (mShortcutButtonType == ACCESSIBILITY_SHORTCUT_KEY);
- final boolean enabledState = (isLaunchMenuMode || isHardwareButtonTriggered);
- final ColorMatrix grayScaleMatrix = new ColorMatrix();
- grayScaleMatrix.setSaturation(/* grayScale */0);
- holder.mIconView.setColorFilter(enabledState
- ? null : new ColorMatrixColorFilter(grayScaleMatrix));
- holder.mIconView.setAlpha(enabledState
- ? ENABLED_ALPHA : DISABLED_ALPHA);
- holder.mLabelView.setEnabled(enabledState);
- holder.mActionViewItem.setEnabled(enabledState);
- holder.mActionViewItem.setImageDrawable(context.getDrawable(R.drawable.ic_delete_item));
- holder.mActionViewItem.setVisibility(View.VISIBLE);
+ holder.mCheckBox.setChecked(!isLaunchMenuMode && target.isChecked());
+ holder.mCheckBox.setVisibility(isLaunchMenuMode ? View.GONE : View.VISIBLE);
+ holder.mIconView.setImageDrawable(target.getDrawable());
+ holder.mLabelView.setText(target.getLabel());
holder.mSwitchItem.setVisibility(View.GONE);
- holder.mItemContainer.setVisibility(isLaunchMenuMode ? View.GONE : View.VISIBLE);
- holder.mItemView.setEnabled(enabledState);
- holder.mItemView.setClickable(!enabledState);
}
- private void updateInvisibleActionItemVisibility(@NonNull Context context,
- @NonNull ViewHolder holder) {
- holder.mIconView.setColorFilter(null);
- holder.mIconView.setAlpha(ENABLED_ALPHA);
- holder.mLabelView.setEnabled(true);
- holder.mActionViewItem.setEnabled(true);
- holder.mActionViewItem.setImageDrawable(context.getDrawable(R.drawable.ic_delete_item));
- holder.mActionViewItem.setVisibility(View.VISIBLE);
+ private void updateInvisibleActionItemVisibility(@NonNull ViewHolder holder,
+ AccessibilityButtonTarget target) {
+ final boolean isEditMenuMode = (mShortcutMenuMode == ShortcutMenuMode.EDIT);
+
+ holder.mCheckBox.setChecked(isEditMenuMode && target.isChecked());
+ holder.mCheckBox.setVisibility(isEditMenuMode ? View.VISIBLE : View.GONE);
+ holder.mIconView.setImageDrawable(target.getDrawable());
+ holder.mLabelView.setText(target.getLabel());
holder.mSwitchItem.setVisibility(View.GONE);
- holder.mItemContainer.setVisibility((mShortcutMenuMode == ShortcutMenuMode.EDIT)
- ? View.VISIBLE : View.GONE);
- holder.mItemView.setEnabled(true);
- holder.mItemView.setClickable(false);
}
private void updateIntuitiveActionItemVisibility(@NonNull Context context,
@@ -403,37 +399,31 @@
? isWhiteListingServiceEnabled(context, target)
: isAccessibilityServiceEnabled(context, target);
- holder.mIconView.setColorFilter(null);
- holder.mIconView.setAlpha(ENABLED_ALPHA);
- holder.mLabelView.setEnabled(true);
- holder.mActionViewItem.setEnabled(true);
- holder.mActionViewItem.setImageDrawable(context.getDrawable(R.drawable.ic_delete_item));
- holder.mActionViewItem.setVisibility(isEditMenuMode ? View.VISIBLE : View.GONE);
+ holder.mCheckBox.setChecked(isEditMenuMode && target.isChecked());
+ holder.mCheckBox.setVisibility(isEditMenuMode ? View.VISIBLE : View.GONE);
+ holder.mIconView.setImageDrawable(target.getDrawable());
+ holder.mLabelView.setText(target.getLabel());
holder.mSwitchItem.setVisibility(isEditMenuMode ? View.GONE : View.VISIBLE);
holder.mSwitchItem.setChecked(!isEditMenuMode && isServiceEnabled);
- holder.mItemContainer.setVisibility(View.VISIBLE);
- holder.mItemView.setEnabled(true);
- holder.mItemView.setClickable(false);
}
- private void updateBounceActionItemVisibility(@NonNull Context context,
- @NonNull ViewHolder holder) {
- holder.mIconView.setColorFilter(null);
- holder.mIconView.setAlpha(ENABLED_ALPHA);
- holder.mLabelView.setEnabled(true);
- holder.mActionViewItem.setEnabled(true);
- holder.mActionViewItem.setImageDrawable(context.getDrawable(R.drawable.ic_delete_item));
- holder.mActionViewItem.setVisibility((mShortcutMenuMode == ShortcutMenuMode.EDIT)
- ? View.VISIBLE : View.GONE);
+ private void updateBounceActionItemVisibility(@NonNull ViewHolder holder,
+ AccessibilityButtonTarget target) {
+ final boolean isEditMenuMode = (mShortcutMenuMode == ShortcutMenuMode.EDIT);
+
+ holder.mCheckBox.setChecked(isEditMenuMode && target.isChecked());
+ holder.mCheckBox.setVisibility(isEditMenuMode ? View.VISIBLE : View.GONE);
+ holder.mIconView.setImageDrawable(target.getDrawable());
+ holder.mLabelView.setText(target.getLabel());
holder.mSwitchItem.setVisibility(View.GONE);
- holder.mItemContainer.setVisibility(View.VISIBLE);
- holder.mItemView.setEnabled(true);
- holder.mItemView.setClickable(false);
}
}
private static class AccessibilityButtonTarget {
private String mId;
+ @TargetType
+ private int mType;
+ private boolean mChecked;
private CharSequence mLabel;
private Drawable mDrawable;
@AccessibilityServiceFragmentType
@@ -442,6 +432,8 @@
AccessibilityButtonTarget(@NonNull Context context,
@NonNull AccessibilityServiceInfo serviceInfo) {
this.mId = serviceInfo.getComponentName().flattenToString();
+ this.mType = TargetType.ACCESSIBILITY_SERVICE;
+ this.mChecked = isTargetShortcutUsed(context, mId);
this.mLabel = serviceInfo.getResolveInfo().loadLabel(context.getPackageManager());
this.mDrawable = serviceInfo.getResolveInfo().loadIcon(context.getPackageManager());
this.mFragmentType = getAccessibilityServiceFragmentType(serviceInfo);
@@ -450,6 +442,8 @@
AccessibilityButtonTarget(@NonNull Context context,
@NonNull AccessibilityShortcutInfo shortcutInfo) {
this.mId = shortcutInfo.getComponentName().flattenToString();
+ this.mType = TargetType.ACCESSIBILITY_ACTIVITY;
+ this.mChecked = isTargetShortcutUsed(context, mId);
this.mLabel = shortcutInfo.getActivityInfo().loadLabel(context.getPackageManager());
this.mDrawable = shortcutInfo.getActivityInfo().loadIcon(context.getPackageManager());
this.mFragmentType = AccessibilityServiceFragmentType.BOUNCE;
@@ -458,15 +452,29 @@
AccessibilityButtonTarget(Context context, @NonNull String id, int labelResId,
int iconRes, @AccessibilityServiceFragmentType int fragmentType) {
this.mId = id;
+ this.mType = TargetType.WHITE_LISTING;
+ this.mChecked = isTargetShortcutUsed(context, mId);
this.mLabel = context.getText(labelResId);
this.mDrawable = context.getDrawable(iconRes);
this.mFragmentType = fragmentType;
}
+ public void setChecked(boolean checked) {
+ mChecked = checked;
+ }
+
public String getId() {
return mId;
}
+ public int getType() {
+ return mType;
+ }
+
+ public boolean isChecked() {
+ return mChecked;
+ }
+
public CharSequence getLabel() {
return mLabel;
}
@@ -519,19 +527,19 @@
}
private void onLegacyTargetSelected(AccessibilityButtonTarget target) {
- if (mShortcutType == ACCESSIBILITY_BUTTON) {
+ if (sShortcutType == ACCESSIBILITY_BUTTON) {
final AccessibilityManager ams = getSystemService(AccessibilityManager.class);
ams.notifyAccessibilityButtonClicked(getDisplayId(), target.getId());
- } else if (mShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
+ } else if (sShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
switchServiceState(target);
}
}
private void onInvisibleTargetSelected(AccessibilityButtonTarget target) {
final AccessibilityManager ams = getSystemService(AccessibilityManager.class);
- if (mShortcutType == ACCESSIBILITY_BUTTON) {
+ if (sShortcutType == ACCESSIBILITY_BUTTON) {
ams.notifyAccessibilityButtonClicked(getDisplayId(), target.getId());
- } else if (mShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
+ } else if (sShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
ams.performAccessibilityShortcut(target.getId());
}
}
@@ -542,9 +550,9 @@
private void onBounceTargetSelected(AccessibilityButtonTarget target) {
final AccessibilityManager ams = getSystemService(AccessibilityManager.class);
- if (mShortcutType == ACCESSIBILITY_BUTTON) {
+ if (sShortcutType == ACCESSIBILITY_BUTTON) {
ams.notifyAccessibilityButtonClicked(getDisplayId(), target.getId());
- } else if (mShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
+ } else if (sShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
ams.performAccessibilityShortcut(target.getId());
}
}
@@ -565,66 +573,101 @@
}
}
- private void onTargetDeleted(AdapterView<?> parent, View view, int position, long id) {
- final AccessibilityButtonTarget target = mTargets.get(position);
- final String componentId = target.getId();
+ private void onTargetChecked(AdapterView<?> parent, View view, int position, long id) {
+ mCurrentCheckedTarget = mTargets.get(position);
+ if ((mCurrentCheckedTarget.getType() == TargetType.ACCESSIBILITY_SERVICE)
+ && !mCurrentCheckedTarget.isChecked()) {
+ mEnableDialog = new AlertDialog.Builder(this)
+ .setView(createEnableDialogContentView(this, mCurrentCheckedTarget,
+ this::onPermissionAllowButtonClicked,
+ this::onPermissionDenyButtonClicked))
+ .create();
+ mEnableDialog.show();
+ return;
+ }
+
+ onTargetChecked(mCurrentCheckedTarget, !mCurrentCheckedTarget.isChecked());
+ }
+
+ private void onTargetChecked(AccessibilityButtonTarget target, boolean checked) {
switch (target.getFragmentType()) {
case AccessibilityServiceFragmentType.LEGACY:
- onLegacyTargetDeleted(position, componentId);
+ onLegacyTargetChecked(checked);
break;
case AccessibilityServiceFragmentType.INVISIBLE:
- onInvisibleTargetDeleted(position, componentId);
+ onInvisibleTargetChecked(checked);
break;
case AccessibilityServiceFragmentType.INTUITIVE:
- onIntuitiveTargetDeleted(position, componentId);
+ onIntuitiveTargetChecked(checked);
break;
case AccessibilityServiceFragmentType.BOUNCE:
- onBounceTargetDeleted(position, componentId);
+ onBounceTargetChecked(checked);
break;
default:
throw new IllegalStateException("Unexpected fragment type");
}
+ }
+ private void onLegacyTargetChecked(boolean checked) {
+ if (sShortcutType == ACCESSIBILITY_BUTTON) {
+ setServiceEnabled(mCurrentCheckedTarget.getId(), checked);
+ if (!checked) {
+ optOutValueFromSettings(this, HARDWARE, mCurrentCheckedTarget.getId());
+ final String warningText =
+ getString(R.string.accessibility_uncheck_legacy_item_warning,
+ mCurrentCheckedTarget.getLabel());
+ Toast.makeText(this, warningText, Toast.LENGTH_SHORT).show();
+ }
+ } else if (sShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
+ updateValueToSettings(mCurrentCheckedTarget.getId(), checked);
+ } else {
+ throw new IllegalStateException("Unexpected shortcut type");
+ }
+
+ mCurrentCheckedTarget.setChecked(checked);
+ mTargetAdapter.notifyDataSetChanged();
+ }
+
+ private void onInvisibleTargetChecked(boolean checked) {
+ final int shortcutTypes = UserShortcutType.SOFTWARE | HARDWARE;
+ if (!hasValuesInSettings(this, shortcutTypes, mCurrentCheckedTarget.getId())) {
+ setServiceEnabled(mCurrentCheckedTarget.getId(), checked);
+ }
+
+ updateValueToSettings(mCurrentCheckedTarget.getId(), checked);
+ mCurrentCheckedTarget.setChecked(checked);
+ mTargetAdapter.notifyDataSetChanged();
+ }
+
+ private void onIntuitiveTargetChecked(boolean checked) {
+ updateValueToSettings(mCurrentCheckedTarget.getId(), checked);
+ mCurrentCheckedTarget.setChecked(checked);
+ mTargetAdapter.notifyDataSetChanged();
+ }
+
+ private void onBounceTargetChecked(boolean checked) {
+ updateValueToSettings(mCurrentCheckedTarget.getId(), checked);
+ mCurrentCheckedTarget.setChecked(checked);
+ mTargetAdapter.notifyDataSetChanged();
+ }
+
+ private void updateValueToSettings(String componentId, boolean checked) {
+ if (checked) {
+ optInValueToSettings(this, mShortcutUserType, componentId);
+ } else {
+ optOutValueFromSettings(this, mShortcutUserType, componentId);
+ }
+ }
+
+ private void onDoneButtonClicked() {
+ mTargets.clear();
+ mTargets.addAll(getServiceTargets(this, sShortcutType));
if (mTargets.isEmpty()) {
mAlertDialog.dismiss();
- }
- }
-
- private void onLegacyTargetDeleted(int position, String componentId) {
- if (mShortcutType == ACCESSIBILITY_SHORTCUT_KEY) {
- optOutValueFromSettings(this, mShortcutUserType, componentId);
-
- mTargets.remove(position);
- mTargetAdapter.notifyDataSetChanged();
- }
- }
-
- private void onInvisibleTargetDeleted(int position, String componentId) {
- optOutValueFromSettings(this, mShortcutUserType, componentId);
-
- final int shortcutTypes = UserShortcutType.SOFTWARE | UserShortcutType.HARDWARE;
- if (!hasValuesInSettings(this, shortcutTypes, componentId)) {
- disableService(componentId);
+ return;
}
- mTargets.remove(position);
- mTargetAdapter.notifyDataSetChanged();
- }
-
- private void onIntuitiveTargetDeleted(int position, String componentId) {
- optOutValueFromSettings(this, mShortcutUserType, componentId);
- mTargets.remove(position);
- mTargetAdapter.notifyDataSetChanged();
- }
-
- private void onBounceTargetDeleted(int position, String componentId) {
- optOutValueFromSettings(this, mShortcutUserType, componentId);
- mTargets.remove(position);
- mTargetAdapter.notifyDataSetChanged();
- }
-
- private void onCancelButtonClicked() {
mTargetAdapter.setShortcutMenuMode(ShortcutMenuMode.LAUNCH);
mTargetAdapter.notifyDataSetChanged();
@@ -635,11 +678,13 @@
}
private void onEditButtonClicked() {
+ mTargets.clear();
+ mTargets.addAll(getInstalledServiceTargets(this));
mTargetAdapter.setShortcutMenuMode(ShortcutMenuMode.EDIT);
mTargetAdapter.notifyDataSetChanged();
mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setText(
- getString(R.string.cancel_accessibility_shortcut_menu_button));
+ getString(R.string.done_accessibility_shortcut_menu_button));
updateDialogListeners();
}
@@ -649,15 +694,78 @@
(mTargetAdapter.getShortcutMenuMode() == ShortcutMenuMode.EDIT);
final int selectDialogTitleId = R.string.accessibility_select_shortcut_menu_title;
final int editDialogTitleId =
- (mShortcutType == ACCESSIBILITY_BUTTON)
+ (sShortcutType == ACCESSIBILITY_BUTTON)
? R.string.accessibility_edit_shortcut_menu_button_title
: R.string.accessibility_edit_shortcut_menu_volume_title;
mAlertDialog.setTitle(getString(isEditMenuMode ? editDialogTitleId : selectDialogTitleId));
-
mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(
- isEditMenuMode ? view -> onCancelButtonClicked() : view -> onEditButtonClicked());
+ isEditMenuMode ? view -> onDoneButtonClicked() : view -> onEditButtonClicked());
mAlertDialog.getListView().setOnItemClickListener(
- isEditMenuMode ? this::onTargetDeleted : this::onTargetSelected);
+ isEditMenuMode ? this::onTargetChecked : this::onTargetSelected);
+ }
+
+ private static boolean isTargetShortcutUsed(@NonNull Context context, String id) {
+ final AccessibilityManager ams = context.getSystemService(AccessibilityManager.class);
+ final List<String> requiredTargets = ams.getAccessibilityShortcutTargets(sShortcutType);
+ return requiredTargets.contains(id);
+ }
+
+ private void onPermissionAllowButtonClicked(View view) {
+ if (mCurrentCheckedTarget.getFragmentType() != AccessibilityServiceFragmentType.LEGACY) {
+ updateValueToSettings(mCurrentCheckedTarget.getId(), /* checked= */ true);
+ }
+ onTargetChecked(mCurrentCheckedTarget, /* checked= */ true);
+ mEnableDialog.dismiss();
+ }
+
+ private void onPermissionDenyButtonClicked(View view) {
+ mEnableDialog.dismiss();
+ }
+
+ private static View createEnableDialogContentView(Context context,
+ AccessibilityButtonTarget target, View.OnClickListener allowListener,
+ View.OnClickListener denyListener) {
+ final LayoutInflater inflater = (LayoutInflater) context.getSystemService(
+ Context.LAYOUT_INFLATER_SERVICE);
+
+ final View content = inflater.inflate(
+ R.layout.accessibility_enable_service_encryption_warning, /* root= */ null);
+
+ final TextView encryptionWarningView = (TextView) content.findViewById(
+ R.id.accessibility_encryption_warning);
+ if (StorageManager.isNonDefaultBlockEncrypted()) {
+ final String text = context.getString(
+ R.string.accessibility_enable_service_encryption_warning,
+ getServiceName(context, target.getLabel()));
+ encryptionWarningView.setText(text);
+ encryptionWarningView.setVisibility(View.VISIBLE);
+ } else {
+ encryptionWarningView.setVisibility(View.GONE);
+ }
+
+ final ImageView permissionDialogIcon = content.findViewById(
+ R.id.accessibility_permissionDialog_icon);
+ permissionDialogIcon.setImageDrawable(target.getDrawable());
+
+ final TextView permissionDialogTitle = content.findViewById(
+ R.id.accessibility_permissionDialog_title);
+ permissionDialogTitle.setText(context.getString(R.string.accessibility_enable_service_title,
+ getServiceName(context, target.getLabel())));
+
+ final Button permissionAllowButton = content.findViewById(
+ R.id.accessibility_permission_enable_allow_button);
+ final Button permissionDenyButton = content.findViewById(
+ R.id.accessibility_permission_enable_deny_button);
+ permissionAllowButton.setOnClickListener(allowListener);
+ permissionDenyButton.setOnClickListener(denyListener);
+
+ return content;
+ }
+
+ // Gets the service name and bidi wrap it to protect from bidi side effects.
+ private static CharSequence getServiceName(Context context, CharSequence label) {
+ final Locale locale = context.getResources().getConfiguration().getLocales().get(0);
+ return BidiFormatter.getInstance(locale).unicodeWrap(label);
}
}
diff --git a/core/java/com/android/internal/app/AppPredictionServiceResolverComparator.java b/core/java/com/android/internal/app/AppPredictionServiceResolverComparator.java
index 04ad7e9..ba8c7b3 100644
--- a/core/java/com/android/internal/app/AppPredictionServiceResolverComparator.java
+++ b/core/java/com/android/internal/app/AppPredictionServiceResolverComparator.java
@@ -36,7 +36,9 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.concurrent.Executors;
+import java.util.stream.Collectors;
/**
* Uses an {@link AppPredictor} to sort Resolver targets. If the AppPredictionService appears to be
@@ -160,6 +162,15 @@
}
@Override
+ List<ComponentName> getTopComponentNames(int topK) {
+ return mTargetRanks.entrySet().stream()
+ .sorted(Entry.comparingByValue())
+ .limit(topK)
+ .map(Entry::getKey)
+ .collect(Collectors.toList());
+ }
+
+ @Override
void updateModel(ComponentName componentName) {
if (mResolverRankerService != null) {
mResolverRankerService.updateModel(componentName);
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index c487e96..3696c83 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -223,6 +223,11 @@
SystemUiDeviceConfigFlags.HASH_SALT_MAX_DAYS,
DEFAULT_SALT_EXPIRATION_DAYS);
+ private boolean mAppendDirectShareEnabled = DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_SYSTEMUI,
+ SystemUiDeviceConfigFlags.APPEND_DIRECT_SHARE_ENABLED,
+ false);
+
private Bundle mReplacementExtras;
private IntentSender mChosenComponentSender;
private IntentSender mRefinementIntentSender;
@@ -409,6 +414,11 @@
private static final int WATCHDOG_TIMEOUT_MAX_MILLIS = 10000;
private static final int WATCHDOG_TIMEOUT_MIN_MILLIS = 3000;
+ private static final int DEFAULT_DIRECT_SHARE_TIMEOUT_MILLIS = 1500;
+ private int mDirectShareTimeout = DeviceConfig.getInt(DeviceConfig.NAMESPACE_SYSTEMUI,
+ SystemUiDeviceConfigFlags.SHARE_SHEET_DIRECT_SHARE_TIMEOUT,
+ DEFAULT_DIRECT_SHARE_TIMEOUT_MILLIS);
+
private boolean mMinTimeoutPassed = false;
private void removeAllMessages() {
@@ -427,15 +437,14 @@
if (DEBUG) {
Log.d(TAG, "queryTargets setting watchdog timer for "
- + WATCHDOG_TIMEOUT_MIN_MILLIS + "-"
+ + mDirectShareTimeout + "-"
+ WATCHDOG_TIMEOUT_MAX_MILLIS + "ms");
}
sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_MIN_TIMEOUT,
WATCHDOG_TIMEOUT_MIN_MILLIS);
sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT,
- WATCHDOG_TIMEOUT_MAX_MILLIS);
-
+ mAppendDirectShareEnabled ? mDirectShareTimeout : WATCHDOG_TIMEOUT_MAX_MILLIS);
}
private void maybeStopServiceRequestTimer() {
@@ -463,6 +472,7 @@
final ServiceResultInfo sri = (ServiceResultInfo) msg.obj;
if (!mServiceConnections.contains(sri.connection)) {
Log.w(TAG, "ChooserTargetServiceConnection " + sri.connection
+ + sri.originalTarget.getResolveInfo().activityInfo.packageName
+ " returned after being removed from active connections."
+ " Have you considered returning results faster?");
break;
@@ -474,7 +484,7 @@
if (adapterForUserHandle != null) {
adapterForUserHandle.addServiceResults(sri.originalTarget,
sri.resultTargets, TARGET_TYPE_CHOOSER_TARGET,
- /* directShareShortcutInfoCache */ null);
+ /* directShareShortcutInfoCache */ null, mServiceConnections);
}
}
unbindService(sri.connection);
@@ -489,6 +499,7 @@
break;
case CHOOSER_TARGET_SERVICE_WATCHDOG_MAX_TIMEOUT:
+ mMinTimeoutPassed = true;
unbindRemainingServices();
maybeStopServiceRequestTimer();
break;
@@ -513,7 +524,7 @@
if (adapterForUserHandle != null) {
adapterForUserHandle.addServiceResults(
resultInfo.originalTarget, resultInfo.resultTargets, msg.arg1,
- mDirectShareShortcutInfoCache);
+ mDirectShareShortcutInfoCache, mServiceConnections);
}
}
break;
@@ -1481,7 +1492,7 @@
/* origTarget */ null,
Lists.newArrayList(mCallerChooserTargets),
TARGET_TYPE_DEFAULT,
- /* directShareShortcutInfoCache */ null);
+ /* directShareShortcutInfoCache */ null, mServiceConnections);
}
}
@@ -2129,7 +2140,7 @@
return null;
}
- if (getPersonalProfileUserHandle() == userHandle) {
+ if (getPersonalProfileUserHandle().equals(userHandle)) {
if (mPersonalAppPredictor != null) {
return mPersonalAppPredictor;
}
@@ -2155,7 +2166,7 @@
.getSystemService(AppPredictionManager.class);
AppPredictor appPredictionSession = appPredictionManager.createAppPredictionSession(
appPredictionContext);
- if (getPersonalProfileUserHandle() == userHandle) {
+ if (getPersonalProfileUserHandle().equals(userHandle)) {
mPersonalAppPredictor = appPredictionSession;
} else {
mWorkAppPredictor = appPredictionSession;
@@ -2398,17 +2409,22 @@
}
final int availableWidth = right - left - v.getPaddingLeft() - v.getPaddingRight();
- if (mChooserMultiProfilePagerAdapter.getCurrentUserHandle() != getUser()) {
- gridAdapter.calculateChooserTargetWidth(availableWidth);
- return;
- }
-
- if (gridAdapter.consumeLayoutRequest()
+ boolean isLayoutUpdated = gridAdapter.consumeLayoutRequest()
|| gridAdapter.calculateChooserTargetWidth(availableWidth)
|| recyclerView.getAdapter() == null
- || mLastNumberOfChildren != recyclerView.getChildCount()
- || availableWidth != mCurrAvailableWidth) {
+ || availableWidth != mCurrAvailableWidth;
+ if (isLayoutUpdated
+ || mLastNumberOfChildren != recyclerView.getChildCount()) {
mCurrAvailableWidth = availableWidth;
+ if (isLayoutUpdated
+ && mChooserMultiProfilePagerAdapter.getCurrentUserHandle() != getUser()) {
+ // This fixes b/150936654 - empty work tab in share sheet when swiping
+ mChooserMultiProfilePagerAdapter.getActiveAdapterView()
+ .setAdapter(mChooserMultiProfilePagerAdapter.getCurrentRootAdapter());
+ return;
+ } else if (mChooserMultiProfilePagerAdapter.getCurrentUserHandle() != getUser()) {
+ return;
+ }
getMainThreadHandler().post(() -> {
if (mResolverDrawerLayout == null || gridAdapter == null) {
@@ -2452,39 +2468,46 @@
offset += tabDivider.getHeight();
}
- int directShareHeight = 0;
- rowsToShow = Math.min(4, rowsToShow);
- mLastNumberOfChildren = recyclerView.getChildCount();
- for (int i = 0, childCount = recyclerView.getChildCount();
- i < childCount && rowsToShow > 0; i++) {
- View child = recyclerView.getChildAt(i);
- if (((GridLayoutManager.LayoutParams)
- child.getLayoutParams()).getSpanIndex() != 0) {
- continue;
+ if (recyclerView.getVisibility() == View.VISIBLE) {
+ int directShareHeight = 0;
+ rowsToShow = Math.min(4, rowsToShow);
+ mLastNumberOfChildren = recyclerView.getChildCount();
+ for (int i = 0, childCount = recyclerView.getChildCount();
+ i < childCount && rowsToShow > 0; i++) {
+ View child = recyclerView.getChildAt(i);
+ if (((GridLayoutManager.LayoutParams)
+ child.getLayoutParams()).getSpanIndex() != 0) {
+ continue;
+ }
+ int height = child.getHeight();
+ offset += height;
+
+ if (gridAdapter.getTargetType(
+ recyclerView.getChildAdapterPosition(child))
+ == ChooserListAdapter.TARGET_SERVICE) {
+ directShareHeight = height;
+ }
+ rowsToShow--;
}
- int height = child.getHeight();
- offset += height;
- if (gridAdapter.getTargetType(
- recyclerView.getChildAdapterPosition(child))
- == ChooserListAdapter.TARGET_SERVICE) {
- directShareHeight = height;
+ boolean isExpandable = getResources().getConfiguration().orientation
+ == Configuration.ORIENTATION_PORTRAIT && !isInMultiWindowMode();
+ if (directShareHeight != 0 && isSendAction(getTargetIntent())
+ && isExpandable) {
+ // make sure to leave room for direct share 4->8 expansion
+ int requiredExpansionHeight =
+ (int) (directShareHeight / DIRECT_SHARE_EXPANSION_RATE);
+ int topInset = mSystemWindowInsets != null ? mSystemWindowInsets.top : 0;
+ int minHeight = bottom - top - mResolverDrawerLayout.getAlwaysShowHeight()
+ - requiredExpansionHeight - topInset - bottomInset;
+
+ offset = Math.min(offset, minHeight);
}
- rowsToShow--;
- }
-
- boolean isExpandable = getResources().getConfiguration().orientation
- == Configuration.ORIENTATION_PORTRAIT && !isInMultiWindowMode();
- if (directShareHeight != 0 && isSendAction(getTargetIntent())
- && isExpandable) {
- // make sure to leave room for direct share 4->8 expansion
- int requiredExpansionHeight =
- (int) (directShareHeight / DIRECT_SHARE_EXPANSION_RATE);
- int topInset = mSystemWindowInsets != null ? mSystemWindowInsets.top : 0;
- int minHeight = bottom - top - mResolverDrawerLayout.getAlwaysShowHeight()
- - requiredExpansionHeight - topInset - bottomInset;
-
- offset = Math.min(offset, minHeight);
+ } else {
+ ViewGroup currentEmptyStateView = getCurrentEmptyStateView();
+ if (currentEmptyStateView.getVisibility() == View.VISIBLE) {
+ offset += currentEmptyStateView.getHeight();
+ }
}
mResolverDrawerLayout.setCollapsibleHeightReserved(Math.min(offset, bottom - top));
@@ -2492,6 +2515,11 @@
}
}
+ private ViewGroup getCurrentEmptyStateView() {
+ int currentPage = mChooserMultiProfilePagerAdapter.getCurrentPage();
+ return mChooserMultiProfilePagerAdapter.getItem(currentPage).getEmptyStateView();
+ }
+
static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
@Override
public int compare(ChooserTarget lhs, ChooserTarget rhs) {
@@ -2538,7 +2566,7 @@
ChooserListAdapter chooserListAdapter = (ChooserListAdapter) listAdapter;
if (chooserListAdapter.getUserHandle()
- == mChooserMultiProfilePagerAdapter.getCurrentUserHandle()) {
+ .equals(mChooserMultiProfilePagerAdapter.getCurrentUserHandle())) {
mChooserMultiProfilePagerAdapter.getActiveAdapterView()
.setAdapter(mChooserMultiProfilePagerAdapter.getCurrentRootAdapter());
mChooserMultiProfilePagerAdapter
@@ -3567,6 +3595,10 @@
? mOriginalTarget.getResolveInfo().activityInfo.toString()
: "<connection destroyed>") + "}";
}
+
+ public ComponentName getComponentName() {
+ return mOriginalTarget.getResolveInfo().activityInfo.getComponentName();
+ }
}
static class ServiceResultInfo {
diff --git a/core/java/com/android/internal/app/ChooserListAdapter.java b/core/java/com/android/internal/app/ChooserListAdapter.java
index 74ae291..0ea855a 100644
--- a/core/java/com/android/internal/app/ChooserListAdapter.java
+++ b/core/java/com/android/internal/app/ChooserListAdapter.java
@@ -32,8 +32,10 @@
import android.os.AsyncTask;
import android.os.UserHandle;
import android.os.UserManager;
+import android.provider.DeviceConfig;
import android.service.chooser.ChooserTarget;
import android.util.Log;
+import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
@@ -44,17 +46,26 @@
import com.android.internal.app.chooser.MultiDisplayResolveInfo;
import com.android.internal.app.chooser.SelectableTargetInfo;
import com.android.internal.app.chooser.TargetInfo;
+import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
public class ChooserListAdapter extends ResolverListAdapter {
private static final String TAG = "ChooserListAdapter";
private static final boolean DEBUG = false;
+ private boolean mAppendDirectShareEnabled = DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_SYSTEMUI,
+ SystemUiDeviceConfigFlags.APPEND_DIRECT_SHARE_ENABLED,
+ false);
+
private boolean mEnableStackedApps = true;
public static final int NO_POSITION = -1;
@@ -84,6 +95,11 @@
// Reserve spots for incoming direct share targets by adding placeholders
private ChooserTargetInfo
mPlaceHolderTargetInfo = new ChooserActivity.PlaceHolderTargetInfo();
+ private int mValidServiceTargetsNum = 0;
+ private final Map<ComponentName, Pair<List<ChooserTargetInfo>, Integer>>
+ mParkingDirectShareTargets = new HashMap<>();
+ private Set<ComponentName> mPendingChooserTargetService = new HashSet<>();
+ private Set<ComponentName> mShortcutComponents = new HashSet<>();
private final List<ChooserTargetInfo> mServiceTargets = new ArrayList<>();
private final List<TargetInfo> mCallerTargets = new ArrayList<>();
@@ -189,6 +205,9 @@
void refreshListView() {
if (mListViewDataChanged) {
+ if (mAppendDirectShareEnabled) {
+ appendServiceTargetsWithQuota();
+ }
super.notifyDataSetChanged();
}
mListViewDataChanged = false;
@@ -198,6 +217,10 @@
private void createPlaceHolders() {
mNumShortcutResults = 0;
mServiceTargets.clear();
+ mValidServiceTargetsNum = 0;
+ mParkingDirectShareTargets.clear();
+ mPendingChooserTargetService.clear();
+ mShortcutComponents.clear();
for (int i = 0; i < MAX_SERVICE_TARGETS; i++) {
mServiceTargets.add(mPlaceHolderTargetInfo);
}
@@ -393,12 +416,19 @@
*/
public void addServiceResults(DisplayResolveInfo origTarget, List<ChooserTarget> targets,
@ChooserActivity.ShareTargetType int targetType,
- Map<ChooserTarget, ShortcutInfo> directShareToShortcutInfos) {
+ Map<ChooserTarget, ShortcutInfo> directShareToShortcutInfos,
+ List<ChooserActivity.ChooserTargetServiceConnection>
+ pendingChooserTargetServiceConnections) {
if (DEBUG) {
- Log.d(TAG, "addServiceResults " + origTarget + ", " + targets.size()
+ Log.d(TAG, "addServiceResults " + origTarget.getResolvedComponentName() + ", "
+ + targets.size()
+ " targets");
}
-
+ if (mAppendDirectShareEnabled) {
+ parkTargetIntoMemory(origTarget, targets, targetType, directShareToShortcutInfos,
+ pendingChooserTargetServiceConnections);
+ return;
+ }
if (targets.size() == 0) {
return;
}
@@ -449,6 +479,126 @@
}
}
+ /**
+ * Park {@code targets} into memory for the moment to surface them later when view is refreshed.
+ * Components pending on ChooserTargetService query are also recorded.
+ */
+ private void parkTargetIntoMemory(DisplayResolveInfo origTarget, List<ChooserTarget> targets,
+ @ChooserActivity.ShareTargetType int targetType,
+ Map<ChooserTarget, ShortcutInfo> directShareToShortcutInfos,
+ List<ChooserActivity.ChooserTargetServiceConnection>
+ pendingChooserTargetServiceConnections) {
+ ComponentName origComponentName = origTarget.getResolvedComponentName();
+ mPendingChooserTargetService = pendingChooserTargetServiceConnections.stream()
+ .map(ChooserActivity.ChooserTargetServiceConnection::getComponentName)
+ .filter(componentName -> !componentName.equals(origComponentName))
+ .collect(Collectors.toSet());
+ // Park targets in memory
+ if (!targets.isEmpty() && !mParkingDirectShareTargets.containsKey(origComponentName)) {
+ final boolean isShortcutResult =
+ (targetType == TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER
+ || targetType == TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE);
+ Context contextAsUser = mContext.createContextAsUser(getUserHandle(),
+ 0 /* flags */);
+ List<ChooserTargetInfo> parkingTargetInfos = targets.stream()
+ .map(target ->
+ new SelectableTargetInfo(
+ contextAsUser, origTarget, target, target.getScore(),
+ mSelectableTargetInfoComunicator,
+ (isShortcutResult ? directShareToShortcutInfos.get(target)
+ : null))
+ )
+ .collect(Collectors.toList());
+ mParkingDirectShareTargets.put(origComponentName,
+ new Pair<>(parkingTargetInfos, 0));
+ if (isShortcutResult) {
+ mShortcutComponents.add(origComponentName);
+ }
+ }
+ notifyDataSetChanged();
+ }
+
+ /**
+ * Append targets of top ranked share app into direct share row with quota limit. Remove
+ * appended ones from memory.
+ */
+ private void appendServiceTargetsWithQuota() {
+ int maxRankedTargets = mChooserListCommunicator.getMaxRankedTargets();
+ List<ComponentName> topComponentNames = getTopComponentNames(maxRankedTargets);
+ int appRank = 0;
+ for (ComponentName component : topComponentNames) {
+ if (!mPendingChooserTargetService.contains(component)
+ && !mParkingDirectShareTargets.containsKey(component)) {
+ continue;
+ }
+ appRank++;
+ Pair<List<ChooserTargetInfo>, Integer> parkingTargetsItem =
+ mParkingDirectShareTargets.get(component);
+ if (parkingTargetsItem != null && parkingTargetsItem.second == 0) {
+ List<ChooserTargetInfo> parkingTargets = parkingTargetsItem.first;
+ int initTargetsQuota = appRank <= maxRankedTargets / 2 ? 2 : 1;
+ int insertedNum = 0;
+ while (insertedNum < initTargetsQuota && !parkingTargets.isEmpty()) {
+ if (!checkDuplicateTarget(parkingTargets.get(0))) {
+ mServiceTargets.add(mValidServiceTargetsNum, parkingTargets.get(0));
+ mValidServiceTargetsNum++;
+ insertedNum++;
+ }
+ parkingTargets.remove(0);
+ }
+ mParkingDirectShareTargets.put(component, new Pair<>(parkingTargets, insertedNum));
+ if (mShortcutComponents.contains(component)) {
+ mNumShortcutResults += insertedNum;
+ }
+ }
+ }
+ }
+
+ /**
+ * Append all remaining targets (parking in memory) into direct share row as per their ranking.
+ */
+ private void fillAllServiceTargets() {
+ int maxRankedTargets = mChooserListCommunicator.getMaxRankedTargets();
+ List<ComponentName> topComponentNames = getTopComponentNames(maxRankedTargets);
+ // Append all remaining targets of top recommended components into direct share row.
+ for (ComponentName component : topComponentNames) {
+ if (!mParkingDirectShareTargets.containsKey(component)) {
+ continue;
+ }
+ mParkingDirectShareTargets.get(component).first.stream()
+ .filter(target -> !checkDuplicateTarget(target))
+ .forEach(target -> {
+ if (mShortcutComponents.contains(component)) {
+ mNumShortcutResults++;
+ }
+ mServiceTargets.add(target);
+ });
+ mParkingDirectShareTargets.remove(component);
+ }
+ // Append all remaining shortcuts targets into direct share row.
+ List<ChooserTargetInfo> remainingTargets = new ArrayList<>();
+ mParkingDirectShareTargets.entrySet().stream()
+ .filter(entry -> mShortcutComponents.contains(entry.getKey()))
+ .map(entry -> entry.getValue())
+ .map(pair -> pair.first)
+ .forEach(remainingTargets::addAll);
+ remainingTargets.sort(
+ (t1, t2) -> -Float.compare(t1.getModifiedScore(), t2.getModifiedScore()));
+ mServiceTargets.addAll(remainingTargets);
+ mNumShortcutResults += remainingTargets.size();
+ mParkingDirectShareTargets.clear();
+ }
+
+ private boolean checkDuplicateTarget(ChooserTargetInfo chooserTargetInfo) {
+ // Check for duplicates and abort if found
+ for (ChooserTargetInfo otherTargetInfo : mServiceTargets) {
+ if (chooserTargetInfo.isSimilar(otherTargetInfo)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
int getNumShortcutResults() {
return mNumShortcutResults;
}
@@ -487,7 +637,9 @@
*/
public void completeServiceTargetLoading() {
mServiceTargets.removeIf(o -> o instanceof ChooserActivity.PlaceHolderTargetInfo);
-
+ if (mAppendDirectShareEnabled) {
+ fillAllServiceTargets();
+ }
if (mServiceTargets.isEmpty()) {
mServiceTargets.add(new ChooserActivity.EmptyTargetInfo());
}
diff --git a/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java b/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java
index b39d42ec..c6a00f3 100644
--- a/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java
+++ b/core/java/com/android/internal/app/ChooserMultiProfilePagerAdapter.java
@@ -20,6 +20,7 @@
import android.content.Context;
import android.os.UserHandle;
import android.view.LayoutInflater;
+import android.view.View;
import android.view.ViewGroup;
import com.android.internal.R;
@@ -92,10 +93,10 @@
@Override
@Nullable
ChooserListAdapter getListAdapterForUserHandle(UserHandle userHandle) {
- if (getActiveListAdapter().getUserHandle() == userHandle) {
+ if (getActiveListAdapter().getUserHandle().equals(userHandle)) {
return getActiveListAdapter();
} else if (getInactiveListAdapter() != null
- && getInactiveListAdapter().getUserHandle() == userHandle) {
+ && getInactiveListAdapter().getUserHandle().equals(userHandle)) {
return getInactiveListAdapter();
}
return null;
@@ -169,6 +170,32 @@
return ResolverActivity.METRICS_CATEGORY_CHOOSER;
}
+ @Override
+ protected void showWorkProfileOffEmptyState(ResolverListAdapter activeListAdapter,
+ View.OnClickListener listener) {
+ showEmptyState(activeListAdapter,
+ R.drawable.ic_work_apps_off,
+ R.string.resolver_turn_on_work_apps_share,
+ /* subtitleRes */ 0,
+ listener);
+ }
+
+ @Override
+ protected void showNoPersonalToWorkIntentsEmptyState(ResolverListAdapter activeListAdapter) {
+ showEmptyState(activeListAdapter,
+ R.drawable.ic_sharing_disabled,
+ R.string.resolver_cant_share_with_work_apps,
+ R.string.resolver_cant_share_cross_profile_explanation);
+ }
+
+ @Override
+ protected void showNoWorkToPersonalIntentsEmptyState(ResolverListAdapter activeListAdapter) {
+ showEmptyState(activeListAdapter,
+ R.drawable.ic_sharing_disabled,
+ R.string.resolver_cant_share_with_personal_apps,
+ R.string.resolver_cant_share_cross_profile_explanation);
+ }
+
class ChooserProfileDescriptor extends ProfileDescriptor {
private ChooserActivity.ChooserGridAdapter chooserGridAdapter;
private RecyclerView recyclerView;
diff --git a/core/java/com/android/internal/app/IAppOpsService.aidl b/core/java/com/android/internal/app/IAppOpsService.aidl
index 1c1c254..9218823 100644
--- a/core/java/com/android/internal/app/IAppOpsService.aidl
+++ b/core/java/com/android/internal/app/IAppOpsService.aidl
@@ -34,14 +34,14 @@
// be kept in sync with frameworks/native/libs/binder/include/binder/IAppOpsService.h
// and not be reordered
int checkOperation(int code, int uid, String packageName);
- int noteOperation(int code, int uid, String packageName, @nullable String featureId,
+ int noteOperation(int code, int uid, String packageName, @nullable String attributionTag,
boolean shouldCollectAsyncNotedOp, String message);
int startOperation(IBinder clientId, int code, int uid, String packageName,
- @nullable String featureId, boolean startIfModeDefault,
+ @nullable String attributionTag, boolean startIfModeDefault,
boolean shouldCollectAsyncNotedOp, String message);
@UnsupportedAppUsage
void finishOperation(IBinder clientId, int code, int uid, String packageName,
- @nullable String featureId);
+ @nullable String attributionTag);
void startWatchingMode(int op, String packageName, IAppOpsCallback callback);
void stopWatchingMode(IAppOpsCallback callback);
int permissionToOpCode(String permission);
@@ -52,8 +52,8 @@
// Any new method exposed to native must be added after the last one, do not reorder
int noteProxyOperation(int code, int proxiedUid, String proxiedPackageName,
- String proxiedFeatureId, int proxyUid, String proxyPackageName,
- String proxyFeatureId, boolean shouldCollectAsyncNotedOp, String message);
+ String proxiedAttributionTag, int proxyUid, String proxyPackageName,
+ String proxyAttributionTag, boolean shouldCollectAsyncNotedOp, String message);
// Remaining methods are only used in Java.
int checkPackage(int uid, String packageName);
@@ -64,10 +64,10 @@
List<AppOpsManager.PackageOps> getPackagesForOps(in int[] ops);
@UnsupportedAppUsage
List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName, in int[] ops);
- void getHistoricalOps(int uid, String packageName, String featureId, in List<String> ops,
+ void getHistoricalOps(int uid, String packageName, String attributionTag, in List<String> ops,
int filter, long beginTimeMillis, long endTimeMillis, int flags,
in RemoteCallback callback);
- void getHistoricalOpsFromDiskRaw(int uid, String packageName, String featureId,
+ void getHistoricalOpsFromDiskRaw(int uid, String packageName, String attributionTag,
in List<String> ops, int filter, long beginTimeMillis, long endTimeMillis, int flags,
in RemoteCallback callback);
void offsetHistory(long duration);
@@ -103,4 +103,6 @@
int checkOperationRaw(int code, int uid, String packageName);
void reloadNonHistoricalState();
+
+ void collectNoteOpCallsForValidation(String stackTrace, int op, String packageName, long version);
}
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 6ab6185..086a718 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -163,7 +163,7 @@
* TODO(arangelov): Remove a couple of weeks after work/personal tabs are finalized.
*/
@VisibleForTesting
- public static boolean ENABLE_TABBED_VIEW = false;
+ public static boolean ENABLE_TABBED_VIEW = true;
private static final String TAB_TAG_PERSONAL = "personal";
private static final String TAB_TAG_WORK = "work";
@@ -989,6 +989,8 @@
}
if (shouldShowEmptyState(listAdapter)) {
mMultiProfilePagerAdapter.showEmptyState(listAdapter);
+ } else {
+ mMultiProfilePagerAdapter.showListView(listAdapter);
}
if (doPostProcessing) {
if (mMultiProfilePagerAdapter.getCurrentUserHandle().getIdentifier()
@@ -1240,12 +1242,12 @@
}
private void maybeLogCrossProfileTargetLaunch(TargetInfo cti, UserHandle currentUserHandle) {
- if (!hasWorkProfile() || currentUserHandle == getUser()) {
+ if (!hasWorkProfile() || currentUserHandle.equals(getUser())) {
return;
}
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.RESOLVER_CROSS_PROFILE_TARGET_OPENED)
- .setBoolean(currentUserHandle == getPersonalProfileUserHandle())
+ .setBoolean(currentUserHandle.equals(getPersonalProfileUserHandle()))
.setStrings(getMetricsCategory(),
cti instanceof ChooserTargetInfo ? "direct_share" : "other_target")
.write();
@@ -1337,9 +1339,12 @@
+ "cannot be null.");
}
// We partially rebuild the inactive adapter to determine if we should auto launch
- boolean rebuildCompleted = mMultiProfilePagerAdapter.rebuildActiveTab(true);
+ // isTabLoaded will be true here if the empty state screen is shown instead of the list.
+ boolean rebuildCompleted = mMultiProfilePagerAdapter.rebuildActiveTab(true)
+ || mMultiProfilePagerAdapter.getActiveListAdapter().isTabLoaded();
if (shouldShowTabs()) {
- boolean rebuildInactiveCompleted = mMultiProfilePagerAdapter.rebuildInactiveTab(false);
+ boolean rebuildInactiveCompleted = mMultiProfilePagerAdapter.rebuildInactiveTab(false)
+ || mMultiProfilePagerAdapter.getInactiveListAdapter().isTabLoaded();
rebuildCompleted = rebuildCompleted && rebuildInactiveCompleted;
}
@@ -1399,8 +1404,8 @@
if (numberOfProfiles == 1 && maybeAutolaunchIfSingleTarget()) {
return true;
} else if (numberOfProfiles == 2
- && mMultiProfilePagerAdapter.getActiveListAdapter().isListLoaded()
- && mMultiProfilePagerAdapter.getInactiveListAdapter().isListLoaded()
+ && mMultiProfilePagerAdapter.getActiveListAdapter().isTabLoaded()
+ && mMultiProfilePagerAdapter.getInactiveListAdapter().isTabLoaded()
&& (maybeAutolaunchIfNoAppsOnInactiveTab()
|| maybeAutolaunchIfCrossProfileSupported())) {
return true;
@@ -1481,7 +1486,8 @@
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.RESOLVER_AUTOLAUNCH_CROSS_PROFILE_TARGET)
- .setBoolean(activeListAdapter.getUserHandle() == getPersonalProfileUserHandle())
+ .setBoolean(activeListAdapter.getUserHandle()
+ .equals(getPersonalProfileUserHandle()))
.setStrings(getMetricsCategory())
.write();
safelyStartActivity(activeProfileTarget);
@@ -1595,9 +1601,17 @@
}
private void resetTabsHeaderStyle(TabWidget tabWidget) {
+ String workContentDescription = getString(R.string.resolver_work_tab_accessibility);
+ String personalContentDescription = getString(R.string.resolver_personal_tab_accessibility);
for (int i = 0; i < tabWidget.getChildCount(); i++) {
- TextView title = tabWidget.getChildAt(i).findViewById(android.R.id.title);
+ View tabView = tabWidget.getChildAt(i);
+ TextView title = tabView.findViewById(android.R.id.title);
title.setTextColor(getColor(R.color.resolver_tabs_inactive_color));
+ if (title.getText().equals(getString(R.string.resolver_personal_tab))) {
+ tabView.setContentDescription(personalContentDescription);
+ } else if (title.getText().equals(getString(R.string.resolver_work_tab))) {
+ tabView.setContentDescription(workContentDescription);
+ }
}
}
@@ -1765,7 +1779,7 @@
@Override // ResolverListCommunicator
public void onHandlePackagesChanged(ResolverListAdapter listAdapter) {
if (listAdapter == mMultiProfilePagerAdapter.getActiveListAdapter()) {
- if (listAdapter.getUserHandle() == getWorkProfileUserHandle()
+ if (listAdapter.getUserHandle().equals(getWorkProfileUserHandle())
&& mMultiProfilePagerAdapter.isWaitingToEnableWorkProfile()) {
// We have just turned on the work profile and entered the pass code to start it,
// now we are waiting to receive the ACTION_USER_UNLOCKED broadcast. There is no
@@ -1806,7 +1820,7 @@
mMultiProfilePagerAdapter.markWorkProfileEnabledBroadcastReceived();
}
if (mMultiProfilePagerAdapter.getCurrentUserHandle()
- == getWorkProfileUserHandle()) {
+ .equals(getWorkProfileUserHandle())) {
mMultiProfilePagerAdapter.rebuildActiveTab(true);
} else {
mMultiProfilePagerAdapter.clearInactiveProfileCache();
diff --git a/core/java/com/android/internal/app/ResolverListAdapter.java b/core/java/com/android/internal/app/ResolverListAdapter.java
index 54453d0..579abee 100644
--- a/core/java/com/android/internal/app/ResolverListAdapter.java
+++ b/core/java/com/android/internal/app/ResolverListAdapter.java
@@ -87,7 +87,7 @@
private final ResolverListCommunicator mResolverListCommunicator;
private Runnable mPostListReadyRunnable;
private final boolean mIsAudioCaptureDevice;
- private boolean mIsListLoaded;
+ private boolean mIsTabLoaded;
public ResolverListAdapter(Context context, List<Intent> payloadIntents,
Intent[] initialIntents, List<ResolveInfo> rList,
@@ -153,6 +153,14 @@
return mResolverListController.getScore(target);
}
+ /**
+ * Returns the list of top K component names which have highest
+ * {@link #getScore(DisplayResolveInfo)}
+ */
+ public List<ComponentName> getTopComponentNames(int topK) {
+ return mResolverListController.getTopComponentNames(topK);
+ }
+
public void updateModel(ComponentName componentName) {
mResolverListController.updateModel(componentName);
}
@@ -192,7 +200,7 @@
mLastChosenPosition = -1;
mAllTargetsAreBrowsers = false;
mDisplayList.clear();
- mIsListLoaded = false;
+ mIsTabLoaded = false;
if (mBaseResolveList != null) {
currentResolveList = mUnfilteredResolveList = new ArrayList<>();
@@ -354,7 +362,7 @@
mResolverListCommunicator.sendVoiceChoicesIfNeeded();
postListReadyRunnable(doPostProcessing);
- mIsListLoaded = true;
+ mIsTabLoaded = true;
}
/**
@@ -614,8 +622,12 @@
return mIntents;
}
- protected boolean isListLoaded() {
- return mIsListLoaded;
+ protected boolean isTabLoaded() {
+ return mIsTabLoaded;
+ }
+
+ protected void markTabLoaded() {
+ mIsTabLoaded = true;
}
/**
diff --git a/core/java/com/android/internal/app/ResolverListController.java b/core/java/com/android/internal/app/ResolverListController.java
index 022aded..51dce55 100644
--- a/core/java/com/android/internal/app/ResolverListController.java
+++ b/core/java/com/android/internal/app/ResolverListController.java
@@ -367,6 +367,14 @@
return mResolverComparator.getScore(target.getResolvedComponentName());
}
+ /**
+ * Returns the list of top K component names which have highest
+ * {@link #getScore(DisplayResolveInfo)}
+ */
+ public List<ComponentName> getTopComponentNames(int topK) {
+ return mResolverComparator.getTopComponentNames(topK);
+ }
+
public void updateModel(ComponentName componentName) {
mResolverComparator.updateModel(componentName);
}
diff --git a/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java b/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java
index f6382d3..578f6ae 100644
--- a/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java
+++ b/core/java/com/android/internal/app/ResolverMultiProfilePagerAdapter.java
@@ -20,6 +20,7 @@
import android.content.Context;
import android.os.UserHandle;
import android.view.LayoutInflater;
+import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
@@ -102,10 +103,10 @@
@Override
@Nullable
ResolverListAdapter getListAdapterForUserHandle(UserHandle userHandle) {
- if (getActiveListAdapter().getUserHandle() == userHandle) {
+ if (getActiveListAdapter().getUserHandle().equals(userHandle)) {
return getActiveListAdapter();
} else if (getInactiveListAdapter() != null
- && getInactiveListAdapter().getUserHandle() == userHandle) {
+ && getInactiveListAdapter().getUserHandle().equals(userHandle)) {
return getInactiveListAdapter();
}
return null;
@@ -161,6 +162,32 @@
return ResolverActivity.METRICS_CATEGORY_RESOLVER;
}
+ @Override
+ protected void showWorkProfileOffEmptyState(ResolverListAdapter activeListAdapter,
+ View.OnClickListener listener) {
+ showEmptyState(activeListAdapter,
+ R.drawable.ic_work_apps_off,
+ R.string.resolver_turn_on_work_apps_view,
+ /* subtitleRes */ 0,
+ listener);
+ }
+
+ @Override
+ protected void showNoPersonalToWorkIntentsEmptyState(ResolverListAdapter activeListAdapter) {
+ showEmptyState(activeListAdapter,
+ R.drawable.ic_sharing_disabled,
+ R.string.resolver_cant_access_work_apps,
+ R.string.resolver_cant_access_work_apps_explanation);
+ }
+
+ @Override
+ protected void showNoWorkToPersonalIntentsEmptyState(ResolverListAdapter activeListAdapter) {
+ showEmptyState(activeListAdapter,
+ R.drawable.ic_sharing_disabled,
+ R.string.resolver_cant_access_personal_apps,
+ R.string.resolver_cant_access_personal_apps_explanation);
+ }
+
class ResolverProfileDescriptor extends ProfileDescriptor {
private ResolverListAdapter resolverListAdapter;
final ListView listView;
diff --git a/core/java/com/android/internal/app/ResolverRankerServiceResolverComparator.java b/core/java/com/android/internal/app/ResolverRankerServiceResolverComparator.java
index 01e0622..2869450 100644
--- a/core/java/com/android/internal/app/ResolverRankerServiceResolverComparator.java
+++ b/core/java/com/android/internal/app/ResolverRankerServiceResolverComparator.java
@@ -48,6 +48,7 @@
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
/**
* Ranks and compares packages based on usage stats and uses the {@link ResolverRankerService}.
@@ -252,6 +253,15 @@
return 0;
}
+ @Override
+ List<ComponentName> getTopComponentNames(int topK) {
+ return mTargetsDict.entrySet().stream()
+ .sorted((o1, o2) -> -Float.compare(getScore(o1.getKey()), getScore(o2.getKey())))
+ .limit(topK)
+ .map(Map.Entry::getKey)
+ .collect(Collectors.toList());
+ }
+
// update ranking model when the connection to it is valid.
@Override
public void updateModel(ComponentName componentName) {
diff --git a/core/java/com/android/internal/compat/CompatibilityChangeInfo.java b/core/java/com/android/internal/compat/CompatibilityChangeInfo.java
index 16628d7..ab890d2 100644
--- a/core/java/com/android/internal/compat/CompatibilityChangeInfo.java
+++ b/core/java/com/android/internal/compat/CompatibilityChangeInfo.java
@@ -30,6 +30,7 @@
private final @Nullable String mName;
private final int mEnableAfterTargetSdk;
private final boolean mDisabled;
+ private final boolean mLoggingOnly;
private final @Nullable String mDescription;
public long getId() {
@@ -49,17 +50,22 @@
return mDisabled;
}
+ public boolean getLoggingOnly() {
+ return mLoggingOnly;
+ }
+
public String getDescription() {
return mDescription;
}
public CompatibilityChangeInfo(
Long changeId, String name, int enableAfterTargetSdk, boolean disabled,
- String description) {
+ boolean loggingOnly, String description) {
this.mChangeId = changeId;
this.mName = name;
this.mEnableAfterTargetSdk = enableAfterTargetSdk;
this.mDisabled = disabled;
+ this.mLoggingOnly = loggingOnly;
this.mDescription = description;
}
@@ -68,6 +74,7 @@
mName = in.readString();
mEnableAfterTargetSdk = in.readInt();
mDisabled = in.readBoolean();
+ mLoggingOnly = in.readBoolean();
mDescription = in.readString();
}
@@ -82,6 +89,7 @@
dest.writeString(mName);
dest.writeInt(mEnableAfterTargetSdk);
dest.writeBoolean(mDisabled);
+ dest.writeBoolean(mLoggingOnly);
dest.writeString(mDescription);
}
diff --git a/core/java/com/android/internal/compat/IPlatformCompat.aidl b/core/java/com/android/internal/compat/IPlatformCompat.aidl
index 4c203d3..523ed6f 100644
--- a/core/java/com/android/internal/compat/IPlatformCompat.aidl
+++ b/core/java/com/android/internal/compat/IPlatformCompat.aidl
@@ -164,6 +164,30 @@
boolean clearOverride(long changeId, String packageName);
/**
+ * Enable all compatibility changes which have enabledAfterTargetSdk ==
+ * {@param targetSdkVersion} for an app, subject to the policy. Kills the app to allow the
+ * changes to take effect.
+ *
+ * @param packageName The package name of the app whose compatibility changes will be enabled.
+ * @param targetSdkVersion The targetSdkVersion for filtering the changes to be enabled.
+ *
+ * @return The number of changes that were enabled.
+ */
+ int enableTargetSdkChanges(in String packageName, int targetSdkVersion);
+
+ /**
+ * Disable all compatibility changes which have enabledAfterTargetSdk ==
+ * {@param targetSdkVersion} for an app, subject to the policy. Kills the app to allow the
+ * changes to take effect.
+ *
+ * @param packageName The package name of the app whose compatibility changes will be disabled.
+ * @param targetSdkVersion The targetSdkVersion for filtering the changes to be disabled.
+ *
+ * @return The number of changes that were disabled.
+ */
+ int disableTargetSdkChanges(in String packageName, int targetSdkVersion);
+
+ /**
* Revert overrides to compatibility changes. Kills the app to allow the changes to take effect.
*
* @param packageName The package name of the app whose overrides will be cleared.
diff --git a/core/java/com/android/internal/compat/OverrideAllowedState.java b/core/java/com/android/internal/compat/OverrideAllowedState.java
index 56216c2..9a78ad2 100644
--- a/core/java/com/android/internal/compat/OverrideAllowedState.java
+++ b/core/java/com/android/internal/compat/OverrideAllowedState.java
@@ -33,7 +33,8 @@
DISABLED_NOT_DEBUGGABLE,
DISABLED_NON_TARGET_SDK,
DISABLED_TARGET_SDK_TOO_HIGH,
- PACKAGE_DOES_NOT_EXIST
+ PACKAGE_DOES_NOT_EXIST,
+ LOGGING_ONLY_CHANGE
})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
@@ -49,7 +50,7 @@
public static final int DISABLED_NOT_DEBUGGABLE = 1;
/**
* Change cannot be overridden, due to the build being non-debuggable and the change being
- * non-targetSdk.
+ * enabled regardless of targetSdk.
*/
public static final int DISABLED_NON_TARGET_SDK = 2;
/**
@@ -60,6 +61,10 @@
* Package does not exist.
*/
public static final int PACKAGE_DOES_NOT_EXIST = 4;
+ /**
+ * Change is marked as logging only, and cannot be toggled.
+ */
+ public static final int LOGGING_ONLY_CHANGE = 5;
@State
public final int state;
@@ -118,6 +123,10 @@
"Cannot override %1$d for %2$s because the package does not exist, and "
+ "the change is targetSdk gated.",
changeId, packageName));
+ case LOGGING_ONLY_CHANGE:
+ throw new SecurityException(String.format(
+ "Cannot override %1$d because it is marked as a logging-only change.",
+ changeId));
}
}
@@ -150,4 +159,28 @@
&& appTargetSdk == otherState.appTargetSdk
&& changeIdTargetSdk == otherState.changeIdTargetSdk;
}
+
+ private String stateName() {
+ switch (state) {
+ case ALLOWED:
+ return "ALLOWED";
+ case DISABLED_NOT_DEBUGGABLE:
+ return "DISABLED_NOT_DEBUGGABLE";
+ case DISABLED_NON_TARGET_SDK:
+ return "DISABLED_NON_TARGET_SDK";
+ case DISABLED_TARGET_SDK_TOO_HIGH:
+ return "DISABLED_TARGET_SDK_TOO_HIGH";
+ case PACKAGE_DOES_NOT_EXIST:
+ return "PACKAGE_DOES_NOT_EXIST";
+ case LOGGING_ONLY_CHANGE:
+ return "LOGGING_ONLY_CHANGE";
+ }
+ return "UNKNOWN";
+ }
+
+ @Override
+ public String toString() {
+ return "OverrideAllowedState(state=" + stateName() + "; appTargetSdk=" + appTargetSdk
+ + "; changeIdTargetSdk=" + changeIdTargetSdk + ")";
+ }
}
diff --git a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
index 086b9d8..837cc46 100644
--- a/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
+++ b/core/java/com/android/internal/config/sysui/SystemUiDeviceConfigFlags.java
@@ -378,6 +378,17 @@
"nav_bar_handle_show_over_lockscreen";
/**
+ * (int) Timeout threshold, in millisecond, that Sharesheet waits for direct share targets.
+ */
+ public static final String SHARE_SHEET_DIRECT_SHARE_TIMEOUT =
+ "share_sheet_direct_share_timeout";
+
+ /**
+ * (boolean) Whether append direct share on Sharesheet is enabled.
+ */
+ public static final String APPEND_DIRECT_SHARE_ENABLED = "append_direct_share_enabled";
+
+ /**
* (boolean) Whether to enable user-drag resizing for PIP.
*/
public static final String PIP_USER_RESIZE = "pip_user_resize";
diff --git a/core/java/com/android/internal/content/FileSystemProvider.java b/core/java/com/android/internal/content/FileSystemProvider.java
index 73ef8c6..2f048c9 100644
--- a/core/java/com/android/internal/content/FileSystemProvider.java
+++ b/core/java/com/android/internal/content/FileSystemProvider.java
@@ -430,7 +430,7 @@
if (shouldHide(file)) continue;
if (file.isDirectory()) {
- for (File child : file.listFiles()) {
+ for (File child : FileUtils.listFilesOrEmpty(file)) {
pending.add(child);
}
}
diff --git a/core/java/com/android/internal/logging/InstanceId.java b/core/java/com/android/internal/logging/InstanceId.java
index 85643fc..c90d8512 100644
--- a/core/java/com/android/internal/logging/InstanceId.java
+++ b/core/java/com/android/internal/logging/InstanceId.java
@@ -48,6 +48,17 @@
return mId;
}
+ /**
+ * Create a fake instance ID for testing purposes. Not for production use. See also
+ * InstanceIdSequenceFake, which is a testing replacement for InstanceIdSequence.
+ * @param id The ID you want to assign.
+ * @return new InstanceId.
+ */
+ @VisibleForTesting
+ public static InstanceId fakeInstanceId(int id) {
+ return new InstanceId(id);
+ }
+
@Override
public int hashCode() {
return mId;
diff --git a/core/java/com/android/internal/logging/testing/UiEventLoggerFake.java b/core/java/com/android/internal/logging/testing/UiEventLoggerFake.java
index 130ee64..91ba0df 100644
--- a/core/java/com/android/internal/logging/testing/UiEventLoggerFake.java
+++ b/core/java/com/android/internal/logging/testing/UiEventLoggerFake.java
@@ -20,7 +20,7 @@
import com.android.internal.logging.UiEventLogger;
import java.util.LinkedList;
-import java.util.Queue;
+import java.util.List;
/**
* Fake logger that queues up logged events for inspection.
@@ -52,11 +52,24 @@
}
}
- private Queue<FakeUiEvent> mLogs = new LinkedList<>();
+ private List<FakeUiEvent> mLogs = new LinkedList<>();
- public Queue<FakeUiEvent> getLogs() {
+ /** Returns list of all logging events recorded. */
+ public List<FakeUiEvent> getLogs() {
return mLogs;
}
+ /** Returns number of logging events recorded. */
+ public int numLogs() {
+ return mLogs.size();
+ }
+ /** Returns a particular logging event. */
+ public FakeUiEvent get(int index) {
+ return mLogs.get(index);
+ }
+ /** Returns event id (as integer) of a particular logging event. */
+ public int eventId(int index) {
+ return mLogs.get(index).eventId;
+ }
@Override
public void log(UiEventEnum event) {
@@ -67,7 +80,7 @@
public void log(UiEventEnum event, int uid, String packageName) {
final int eventId = event.getId();
if (eventId > 0) {
- mLogs.offer(new FakeUiEvent(eventId, uid, packageName));
+ mLogs.add(new FakeUiEvent(eventId, uid, packageName));
}
}
@@ -76,7 +89,7 @@
InstanceId instance) {
final int eventId = event.getId();
if (eventId > 0) {
- mLogs.offer(new FakeUiEvent(eventId, uid, packageName, instance));
+ mLogs.add(new FakeUiEvent(eventId, uid, packageName, instance));
}
}
}
diff --git a/core/java/com/android/internal/notification/SystemNotificationChannels.java b/core/java/com/android/internal/notification/SystemNotificationChannels.java
index 91ef0b5..1296ddc 100644
--- a/core/java/com/android/internal/notification/SystemNotificationChannels.java
+++ b/core/java/com/android/internal/notification/SystemNotificationChannels.java
@@ -116,6 +116,7 @@
NETWORK_STATUS,
context.getString(R.string.notification_channel_network_status),
NotificationManager.IMPORTANCE_LOW);
+ network.setBlockableSystem(true);
channelsList.add(network);
final NotificationChannel networkAlertsChannel = new NotificationChannel(
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java b/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
index f8c0d9e..fdcc8a8 100644
--- a/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
+++ b/core/java/com/android/internal/os/KernelCpuThreadReaderSettingsObserver.java
@@ -29,6 +29,7 @@
import com.android.internal.annotations.VisibleForTesting;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Matcher;
@@ -99,7 +100,7 @@
}
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags, int userId) {
updateReader();
}
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index 94924a5..ff03f1a 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -140,6 +140,33 @@
*/
public static final int MEMORY_TAG_LEVEL_SYNC = 3 << 19;
+ /**
+ * A two-bit field for GWP-ASan level of this process. See the possible values below.
+ */
+ public static final int GWP_ASAN_LEVEL_MASK = (1 << 21) | (1 << 22);
+
+ /**
+ * Disable GWP-ASan in this process.
+ * GWP-ASan is a low-overhead memory bug detector using guard pages on a small
+ * subset of heap allocations.
+ */
+ public static final int GWP_ASAN_LEVEL_NEVER = 0 << 21;
+
+ /**
+ * Enable GWP-ASan in this process with a small sampling rate.
+ * With approx. 1% chance GWP-ASan will be activated and apply its protection
+ * to a small subset of heap allocations.
+ * Otherwise (~99% chance) this process is unaffected.
+ */
+ public static final int GWP_ASAN_LEVEL_LOTTERY = 1 << 21;
+
+ /**
+ * Always enable GWP-ASan in this process.
+ * GWP-ASan is activated unconditionally (but still, only a small subset of
+ * allocations is protected).
+ */
+ public static final int GWP_ASAN_LEVEL_ALWAYS = 2 << 21;
+
/** No external storage should be mounted. */
public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
/** Default external storage should be mounted. */
@@ -178,6 +205,9 @@
/** List of packages with the same uid, and its app data info: volume uuid and inode. */
public static final String PKG_DATA_INFO_MAP = "--pkg-data-info-map";
+ /** Bind mount app storage dirs to lower fs not via fuse */
+ public static final String BIND_MOUNT_APP_STORAGE_DIRS = "--bind-mount-storage-dirs";
+
/**
* An extraArg passed when a zygote process is forking a child-zygote, specifying a name
* in the abstract socket namespace. This socket name is what the new child zygote
@@ -283,6 +313,7 @@
* @param isTopApp true if the process is for top (high priority) application.
* @param pkgDataInfoList A list that stores related packages and its app data
* info: volume uuid and inode.
+ * @param bindMountAppStorageDirs True if the zygote needs to mount storage dirs.
*
* @return 0 if this is the child, pid of the child
* if this is the parent, or -1 on error.
@@ -290,13 +321,13 @@
static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
- boolean isTopApp, String[] pkgDataInfoList) {
+ boolean isTopApp, String[] pkgDataInfoList, boolean bindMountAppStorageDirs) {
ZygoteHooks.preFork();
int pid = nativeForkAndSpecialize(
uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp,
- pkgDataInfoList);
+ pkgDataInfoList, bindMountAppStorageDirs);
if (pid == 0) {
// Note that this event ends at the end of handleChildProc,
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
@@ -312,7 +343,8 @@
private static native int nativeForkAndSpecialize(int uid, int gid, int[] gids,
int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
int[] fdsToClose, int[] fdsToIgnore, boolean startChildZygote, String instructionSet,
- String appDataDir, boolean isTopApp, String[] pkgDataInfoList);
+ String appDataDir, boolean isTopApp, String[] pkgDataInfoList,
+ boolean bindMountAppStorageDirs);
/**
* Specialize an unspecialized app process. The current VM must have been started
@@ -339,14 +371,15 @@
* volume uuid and CE dir inode. For example, pkgDataInfoList = [app_a_pkg_name,
* app_a_data_volume_uuid, app_a_ce_inode, app_b_pkg_name, app_b_data_volume_uuid,
* app_b_ce_inode, ...];
+ * @param bindMountAppStorageDirs True if the zygote needs to mount storage dirs.
*/
private static void specializeAppProcess(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, int mountExternal, String seInfo, String niceName,
boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp,
- String[] pkgDataInfoList) {
+ String[] pkgDataInfoList, boolean bindMountAppStorageDirs) {
nativeSpecializeAppProcess(uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo,
niceName, startChildZygote, instructionSet, appDataDir, isTopApp,
- pkgDataInfoList);
+ pkgDataInfoList, bindMountAppStorageDirs);
// Note that this event ends at the end of handleChildProc.
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
@@ -366,7 +399,7 @@
private static native void nativeSpecializeAppProcess(int uid, int gid, int[] gids,
int runtimeFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName,
boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp,
- String[] pkgDataInfoList);
+ String[] pkgDataInfoList, boolean bindMountAppStorageDirs);
/**
* Called to do any initialization before starting an application.
@@ -691,7 +724,7 @@
args.mRuntimeFlags, rlimits, args.mMountExternal,
args.mSeInfo, args.mNiceName, args.mStartChildZygote,
args.mInstructionSet, args.mAppDataDir, args.mIsTopApp,
- args.mPkgDataInfoList);
+ args.mPkgDataInfoList, args.mBindMountAppStorageDirs);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
diff --git a/core/java/com/android/internal/os/ZygoteArguments.java b/core/java/com/android/internal/os/ZygoteArguments.java
index 37f570b..1a63765 100644
--- a/core/java/com/android/internal/os/ZygoteArguments.java
+++ b/core/java/com/android/internal/os/ZygoteArguments.java
@@ -227,6 +227,11 @@
String[] mPkgDataInfoList;
/**
+ * @see Zygote#BIND_MOUNT_APP_STORAGE_DIRS
+ */
+ boolean mBindMountAppStorageDirs;
+
+ /**
* Constructs instance and parses args
*
* @param args zygote command-line args
@@ -447,6 +452,8 @@
}
} else if (arg.startsWith(Zygote.PKG_DATA_INFO_MAP)) {
mPkgDataInfoList = getAssignmentList(arg);
+ } else if (arg.equals(Zygote.BIND_MOUNT_APP_STORAGE_DIRS)) {
+ mBindMountAppStorageDirs = true;
} else {
break;
}
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index 4949811..bc8dfd4 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -258,7 +258,7 @@
parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mIsTopApp,
- parsedArgs.mPkgDataInfoList);
+ parsedArgs.mPkgDataInfoList, parsedArgs.mBindMountAppStorageDirs);
try {
if (pid == 0) {
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index 54cf693..ec1f516 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -125,12 +125,6 @@
private static boolean sPreloadComplete;
- /**
- * Cached classloader to use for the system server. Will only be populated in the system
- * server process.
- */
- private static ClassLoader sCachedSystemServerClassLoader = null;
-
static void preload(TimingsTraceLog bootTimingsTraceLog) {
Log.d(TAG, "begin preload");
bootTimingsTraceLog.traceBegin("BeginPreload");
@@ -508,13 +502,7 @@
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
- if (performSystemServerDexOpt(systemServerClasspath)) {
- // Throw away the cached classloader. If we compiled here, the classloader would
- // not have had AoT-ed artifacts.
- // Note: This only works in a very special environment where selinux enforcement is
- // disabled, e.g., Mac builds.
- sCachedSystemServerClassLoader = null;
- }
+ performSystemServerDexOpt(systemServerClasspath);
// Capturing profiles is only supported for debug or eng builds since selinux normally
// prevents it.
if (shouldProfileSystemServer() && (Build.IS_USERDEBUG || Build.IS_ENG)) {
@@ -546,9 +534,10 @@
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
- createSystemServerClassLoader();
- ClassLoader cl = sCachedSystemServerClassLoader;
- if (cl != null) {
+ ClassLoader cl = null;
+ if (systemServerClasspath != null) {
+ cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);
+
Thread.currentThread().setContextClassLoader(cl);
}
@@ -564,24 +553,6 @@
}
/**
- * Create the classloader for the system server and store it in
- * {@link sCachedSystemServerClassLoader}. This function may be called through JNI in
- * system server startup, when the runtime is in a critically low state. Do not do
- * extended computation etc here.
- */
- private static void createSystemServerClassLoader() {
- if (sCachedSystemServerClassLoader != null) {
- return;
- }
- final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
- // TODO: Should we run optimization here?
- if (systemServerClasspath != null) {
- sCachedSystemServerClassLoader = createPathClassLoader(systemServerClasspath,
- VMRuntime.SDK_VERSION_CUR_DEVELOPMENT);
- }
- }
-
- /**
* Note that preparing the profiles for system server does not require special selinux
* permissions. From the installer perspective the system server is a regular package which can
* capture profile information.
@@ -645,16 +616,15 @@
/**
* Performs dex-opt on the elements of {@code classPath}, if needed. We choose the instruction
- * set of the current runtime. If something was compiled, return true.
+ * set of the current runtime.
*/
- private static boolean performSystemServerDexOpt(String classPath) {
+ private static void performSystemServerDexOpt(String classPath) {
final String[] classPathElements = classPath.split(":");
final IInstalld installd = IInstalld.Stub
.asInterface(ServiceManager.getService("installd"));
final String instructionSet = VMRuntime.getRuntime().vmInstructionSet();
String classPathForElement = "";
- boolean compiledSomething = false;
for (String classPathElement : classPathElements) {
// We default to the verify filter because the compilation will happen on /data and
// system server cannot load executable code outside /system.
@@ -695,7 +665,6 @@
uuid, classLoaderContext, seInfo, false /* downgrade */,
targetSdkVersion, /*profileName*/ null, /*dexMetadataPath*/ null,
"server-dexopt");
- compiledSomething = true;
} catch (RemoteException | ServiceSpecificException e) {
// Ignore (but log), we need this on the classpath for fallback mode.
Log.w(TAG, "Failed compiling classpath element for system server: "
@@ -706,8 +675,6 @@
classPathForElement = encodeSystemServerClassPath(
classPathForElement, classPathElement);
}
-
- return compiledSomething;
}
/**
@@ -794,6 +761,10 @@
* this is present in all ARMv8 CPUs; this flag has no effect on other platforms. */
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
+ /* Enable gwp-asan on the system server with a small probability. This is the same
+ * policy as applied to native processes and system apps. */
+ parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY;
+
if (shouldProfileSystemServer()) {
parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
diff --git a/core/java/com/android/internal/policy/GestureNavigationSettingsObserver.java b/core/java/com/android/internal/policy/GestureNavigationSettingsObserver.java
new file mode 100644
index 0000000..ebfea450
--- /dev/null
+++ b/core/java/com/android/internal/policy/GestureNavigationSettingsObserver.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2020 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.internal.policy;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.res.Resources;
+import android.database.ContentObserver;
+import android.os.Handler;
+import android.os.UserHandle;
+import android.provider.Settings;
+
+/**
+ * @hide
+ */
+public class GestureNavigationSettingsObserver extends ContentObserver {
+ private Context mContext;
+ private Runnable mOnChangeRunnable;
+
+ public GestureNavigationSettingsObserver(Handler handler, Context context,
+ Runnable onChangeRunnable) {
+ super(handler);
+ mContext = context;
+ mOnChangeRunnable = onChangeRunnable;
+ }
+
+ public void register() {
+ ContentResolver r = mContext.getContentResolver();
+ r.registerContentObserver(
+ Settings.Secure.getUriFor(Settings.Secure.BACK_GESTURE_INSET_SCALE_LEFT),
+ false, this, UserHandle.USER_ALL);
+ r.registerContentObserver(
+ Settings.Secure.getUriFor(Settings.Secure.BACK_GESTURE_INSET_SCALE_RIGHT),
+ false, this, UserHandle.USER_ALL);
+ }
+
+ public void unregister() {
+ mContext.getContentResolver().unregisterContentObserver(this);
+ }
+
+ @Override
+ public void onChange(boolean selfChange) {
+ super.onChange(selfChange);
+ if (mOnChangeRunnable != null) {
+ mOnChangeRunnable.run();
+ }
+ }
+
+ public int getLeftSensitivity(Resources userRes) {
+ return getSensitivity(userRes, Settings.Secure.BACK_GESTURE_INSET_SCALE_LEFT);
+ }
+
+ public int getRightSensitivity(Resources userRes) {
+ return getSensitivity(userRes, Settings.Secure.BACK_GESTURE_INSET_SCALE_RIGHT);
+ }
+
+ private int getSensitivity(Resources userRes, String side) {
+ final int inset = userRes.getDimensionPixelSize(
+ com.android.internal.R.dimen.config_backGestureInset);
+ final float scale = Settings.Secure.getFloatForUser(
+ mContext.getContentResolver(), side, 1.0f, UserHandle.USER_CURRENT);
+ return (int) (inset * scale);
+ }
+}
diff --git a/core/java/com/android/internal/statusbar/IStatusBar.aidl b/core/java/com/android/internal/statusbar/IStatusBar.aidl
index 380a20c..5b79b18 100644
--- a/core/java/com/android/internal/statusbar/IStatusBar.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBar.aidl
@@ -136,7 +136,8 @@
// Used to show the authentication dialog (Biometrics, Device Credential)
void showAuthenticationDialog(in Bundle bundle, IBiometricServiceReceiverInternal receiver,
- int biometricModality, boolean requireConfirmation, int userId, String opPackageName);
+ int biometricModality, boolean requireConfirmation, int userId, String opPackageName,
+ long operationId);
// Used to notify the authentication dialog that a biometric has been authenticated
void onBiometricAuthenticated();
// Used to set a temporary message, e.g. fingerprint not recognized, finger moved too fast, etc
diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
index 9907b99..1dbd69c 100644
--- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl
+++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl
@@ -105,7 +105,8 @@
// Used to show the authentication dialog (Biometrics, Device Credential)
void showAuthenticationDialog(in Bundle bundle, IBiometricServiceReceiverInternal receiver,
- int biometricModality, boolean requireConfirmation, int userId, String opPackageName);
+ int biometricModality, boolean requireConfirmation, int userId, String opPackageName,
+ long operationId);
// Used to notify the authentication dialog that a biometric has been authenticated
void onBiometricAuthenticated();
// Used to set a temporary message, e.g. fingerprint not recognized, finger moved too fast, etc
diff --git a/core/java/com/android/internal/util/CollectionUtils.java b/core/java/com/android/internal/util/CollectionUtils.java
index 9b2bcfb..488b18d 100644
--- a/core/java/com/android/internal/util/CollectionUtils.java
+++ b/core/java/com/android/internal/util/CollectionUtils.java
@@ -16,6 +16,8 @@
package com.android.internal.util;
+import static java.util.Collections.emptySet;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.util.ArrayMap;
@@ -67,7 +69,7 @@
*/
public static @NonNull <T> Set<T> filter(@Nullable Set<T> set,
java.util.function.Predicate<? super T> predicate) {
- if (set == null || set.size() == 0) return Collections.emptySet();
+ if (set == null || set.size() == 0) return emptySet();
ArraySet<T> result = null;
if (set instanceof ArraySet) {
ArraySet<T> arraySet = (ArraySet<T>) set;
@@ -123,7 +125,7 @@
*/
public static @NonNull <I, O> Set<O> map(@Nullable Set<I> cur,
Function<? super I, ? extends O> f) {
- if (isEmpty(cur)) return Collections.emptySet();
+ if (isEmpty(cur)) return emptySet();
ArraySet<O> result = new ArraySet<>();
if (cur instanceof ArraySet) {
ArraySet<I> arraySet = (ArraySet<I>) cur;
@@ -182,7 +184,7 @@
* @see Collections#emptySet
*/
public static @NonNull <T> Set<T> emptyIfNull(@Nullable Set<T> cur) {
- return cur == null ? Collections.emptySet() : cur;
+ return cur == null ? emptySet() : cur;
}
/**
@@ -325,9 +327,9 @@
*/
public static @NonNull <T> Set<T> addAll(@Nullable Set<T> cur, @Nullable Collection<T> val) {
if (isEmpty(val)) {
- return cur != null ? cur : Collections.emptySet();
+ return cur != null ? cur : emptySet();
}
- if (cur == null || cur == Collections.emptySet()) {
+ if (cur == null || cur == emptySet()) {
cur = new ArraySet<>();
}
cur.addAll(val);
@@ -338,7 +340,7 @@
* @see #add(List, Object)
*/
public static @NonNull <T> Set<T> add(@Nullable Set<T> cur, T val) {
- if (cur == null || cur == Collections.emptySet()) {
+ if (cur == null || cur == emptySet()) {
cur = new ArraySet<>();
}
cur.add(val);
@@ -390,7 +392,14 @@
* @return a list that will not be affected by mutations to the given original list.
*/
public static @NonNull <T> Set<T> copyOf(@Nullable Set<T> cur) {
- return isEmpty(cur) ? Collections.emptySet() : new ArraySet<>(cur);
+ return isEmpty(cur) ? emptySet() : new ArraySet<>(cur);
+ }
+
+ /**
+ * @return a {@link Set} representing the given collection.
+ */
+ public static @NonNull <T> Set<T> toSet(@Nullable Collection<T> cur) {
+ return isEmpty(cur) ? emptySet() : new ArraySet<>(cur);
}
/**
diff --git a/core/java/com/android/internal/util/DataClass.java b/core/java/com/android/internal/util/DataClass.java
index 43539c7..ee139d9 100644
--- a/core/java/com/android/internal/util/DataClass.java
+++ b/core/java/com/android/internal/util/DataClass.java
@@ -15,7 +15,13 @@
*/
package com.android.internal.util;
-import static java.lang.annotation.ElementType.*;
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.CONSTRUCTOR;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.ElementType.TYPE;
import android.annotation.IntDef;
import android.annotation.Nullable;
@@ -243,6 +249,13 @@
}
/**
+ * Mark that the field should have a {@link Nullable} argument for its setter.
+ */
+ @Retention(RetentionPolicy.SOURCE)
+ @Target({FIELD})
+ @interface MaySetToNull {}
+
+ /**
* Callback used by {@link #genForEachField}.
*
* @param <THIS> The enclosing data class instance.
diff --git a/core/java/com/android/internal/util/NotificationMessagingUtil.java b/core/java/com/android/internal/util/NotificationMessagingUtil.java
index bf796cd..28994fd 100644
--- a/core/java/com/android/internal/util/NotificationMessagingUtil.java
+++ b/core/java/com/android/internal/util/NotificationMessagingUtil.java
@@ -28,6 +28,7 @@
import android.service.notification.StatusBarNotification;
import android.util.ArrayMap;
+import java.util.Collection;
import java.util.Objects;
/**
@@ -77,8 +78,8 @@
private final ContentObserver mSmsContentObserver = new ContentObserver(
new Handler(Looper.getMainLooper())) {
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
- if (Settings.Secure.getUriFor(DEFAULT_SMS_APP_SETTING).equals(uri)) {
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags, int userId) {
+ if (uris.contains(Settings.Secure.getUriFor(DEFAULT_SMS_APP_SETTING))) {
cacheDefaultSmsApp(userId);
}
}
diff --git a/core/java/com/android/internal/util/Parcelling.java b/core/java/com/android/internal/util/Parcelling.java
index 7f567b9..dd64c40 100644
--- a/core/java/com/android/internal/util/Parcelling.java
+++ b/core/java/com/android/internal/util/Parcelling.java
@@ -221,6 +221,33 @@
}
}
+ class ForInternedStringArraySet implements Parcelling<ArraySet<String>> {
+ @Override
+ public void parcel(ArraySet<String> item, Parcel dest, int parcelFlags) {
+ if (item == null) {
+ dest.writeInt(-1);
+ } else {
+ dest.writeInt(item.size());
+ for (String string : item) {
+ dest.writeString(string);
+ }
+ }
+ }
+
+ @Override
+ public ArraySet<String> unparcel(Parcel source) {
+ final int size = source.readInt();
+ if (size < 0) {
+ return null;
+ }
+ ArraySet<String> set = new ArraySet<>();
+ for (int count = 0; count < size; count++) {
+ set.add(TextUtils.safeIntern(source.readString()));
+ }
+ return set;
+ }
+ }
+
class ForBoolean implements Parcelling<Boolean> {
@Override
public void parcel(@Nullable Boolean item, Parcel dest, int parcelFlags) {
diff --git a/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java b/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
index 8446bbd..e4a4408 100755
--- a/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
+++ b/core/java/com/android/internal/util/function/pooled/PooledLambdaImpl.java
@@ -200,8 +200,9 @@
try {
return doInvoke();
} finally {
- if (isRecycleOnUse()) doRecycle();
- if (!isRecycled()) {
+ if (isRecycleOnUse()) {
+ doRecycle();
+ } else if (!isRecycled()) {
int argsSize = ArrayUtils.size(mArgs);
for (int i = 0; i < argsSize; i++) {
popArg(i);
diff --git a/core/java/com/android/internal/view/BaseIWindow.java b/core/java/com/android/internal/view/BaseIWindow.java
index 5dd3389b..47f094f 100644
--- a/core/java/com/android/internal/view/BaseIWindow.java
+++ b/core/java/com/android/internal/view/BaseIWindow.java
@@ -116,7 +116,8 @@
}
@Override
- public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, boolean sync) {
+ public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, float zoom,
+ boolean sync) {
if (sync) {
try {
mSession.wallpaperOffsetsComplete(asBinder());
diff --git a/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl b/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl
index 29bdf56..feb3f02 100644
--- a/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl
+++ b/core/java/com/android/internal/view/inline/IInlineContentCallback.aidl
@@ -24,4 +24,6 @@
*/
oneway interface IInlineContentCallback {
void onContent(in SurfaceControlViewHost.SurfacePackage content);
+ void onClick();
+ void onLongClick();
}
diff --git a/core/java/com/android/internal/widget/CachingIconView.java b/core/java/com/android/internal/widget/CachingIconView.java
index 74ad815..bd0623e 100644
--- a/core/java/com/android/internal/widget/CachingIconView.java
+++ b/core/java/com/android/internal/widget/CachingIconView.java
@@ -32,6 +32,7 @@
import android.widget.RemoteViews;
import java.util.Objects;
+import java.util.function.Consumer;
/**
* An ImageView for displaying an Icon. Avoids reloading the Icon when possible.
@@ -44,6 +45,7 @@
private boolean mInternalSetDrawable;
private boolean mForceHidden;
private int mDesiredVisibility;
+ private Consumer<Integer> mOnVisibilityChangedListener;
@UnsupportedAppUsage
public CachingIconView(Context context, @Nullable AttributeSet attrs) {
@@ -198,6 +200,13 @@
private void updateVisibility() {
int visibility = mDesiredVisibility == VISIBLE && mForceHidden ? INVISIBLE
: mDesiredVisibility;
+ if (mOnVisibilityChangedListener != null) {
+ mOnVisibilityChangedListener.accept(visibility);
+ }
super.setVisibility(visibility);
}
+
+ public void setOnVisibilityChangedListener(Consumer<Integer> listener) {
+ mOnVisibilityChangedListener = listener;
+ }
}
diff --git a/core/java/com/android/internal/widget/ConversationLayout.java b/core/java/com/android/internal/widget/ConversationLayout.java
new file mode 100644
index 0000000..73da600
--- /dev/null
+++ b/core/java/com/android/internal/widget/ConversationLayout.java
@@ -0,0 +1,909 @@
+/*
+ * Copyright (C) 2020 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.internal.widget;
+
+import android.annotation.AttrRes;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.StyleRes;
+import android.app.Notification;
+import android.app.Person;
+import android.app.RemoteInputHistoryItem;
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.drawable.Icon;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.text.TextUtils;
+import android.util.ArrayMap;
+import android.util.AttributeSet;
+import android.util.DisplayMetrics;
+import android.view.Gravity;
+import android.view.RemotableViewMethod;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewTreeObserver;
+import android.view.animation.Interpolator;
+import android.view.animation.PathInterpolator;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.RemoteViews;
+import android.widget.TextView;
+
+import com.android.internal.R;
+import com.android.internal.graphics.ColorUtils;
+import com.android.internal.util.ContrastColorUtil;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.regex.Pattern;
+
+/**
+ * A custom-built layout for the Notification.MessagingStyle allows dynamic addition and removal
+ * messages and adapts the layout accordingly.
+ */
+@RemoteViews.RemoteView
+public class ConversationLayout extends FrameLayout
+ implements ImageMessageConsumer, IMessagingLayout {
+
+ public static final boolean CONVERSATION_LAYOUT_ENABLED = true;
+ private static final float COLOR_SHIFT_AMOUNT = 60;
+ /**
+ * Pattren for filter some ingonable characters.
+ * p{Z} for any kind of whitespace or invisible separator.
+ * p{C} for any kind of punctuation character.
+ */
+ private static final Pattern IGNORABLE_CHAR_PATTERN
+ = Pattern.compile("[\\p{C}\\p{Z}]");
+ private static final Pattern SPECIAL_CHAR_PATTERN
+ = Pattern.compile ("[!@#$%&*()_+=|<>?{}\\[\\]~-]");
+ private static final Consumer<MessagingMessage> REMOVE_MESSAGE
+ = MessagingMessage::removeMessage;
+ public static final Interpolator LINEAR_OUT_SLOW_IN = new PathInterpolator(0f, 0f, 0.2f, 1f);
+ public static final Interpolator FAST_OUT_LINEAR_IN = new PathInterpolator(0.4f, 0f, 1f, 1f);
+ public static final Interpolator FAST_OUT_SLOW_IN = new PathInterpolator(0.4f, 0f, 0.2f, 1f);
+ public static final OnLayoutChangeListener MESSAGING_PROPERTY_ANIMATOR
+ = new MessagingPropertyAnimator();
+ private List<MessagingMessage> mMessages = new ArrayList<>();
+ private List<MessagingMessage> mHistoricMessages = new ArrayList<>();
+ private MessagingLinearLayout mMessagingLinearLayout;
+ private boolean mShowHistoricMessages;
+ private ArrayList<MessagingGroup> mGroups = new ArrayList<>();
+ private TextView mTitleView;
+ private int mLayoutColor;
+ private int mSenderTextColor;
+ private int mMessageTextColor;
+ private int mAvatarSize;
+ private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private Paint mTextPaint = new Paint();
+ private Icon mAvatarReplacement;
+ private boolean mIsOneToOne;
+ private ArrayList<MessagingGroup> mAddedGroups = new ArrayList<>();
+ private Person mUser;
+ private CharSequence mNameReplacement;
+ private boolean mIsCollapsed;
+ private ImageResolver mImageResolver;
+ private ImageView mConversationIcon;
+ private TextView mConversationText;
+ private View mConversationIconBadge;
+ private Icon mLargeIcon;
+ private View mExpandButtonContainer;
+ private ViewGroup mExpandButtonAndContentContainer;
+ private NotificationExpandButton mExpandButton;
+ private int mExpandButtonExpandedTopMargin;
+ private int mBadgedSideMargins;
+ private int mIconSizeBadged;
+ private int mIconSizeCentered;
+ private CachingIconView mIcon;
+ private int mExpandedGroupTopMargin;
+ private int mExpandButtonExpandedSize;
+ private View mConversationFacePile;
+ private int mNotificationBackgroundColor;
+ private CharSequence mFallbackChatName;
+ private CharSequence mFallbackGroupChatName;
+ private CharSequence mConversationTitle;
+ private int mNotificationHeaderExpandedPadding;
+ private View mConversationHeader;
+ private View mContentContainer;
+ private boolean mExpandable = true;
+ private int mContentMarginEnd;
+
+ public ConversationLayout(@NonNull Context context) {
+ super(context);
+ }
+
+ public ConversationLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public ConversationLayout(@NonNull Context context, @Nullable AttributeSet attrs,
+ @AttrRes int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ }
+
+ public ConversationLayout(@NonNull Context context, @Nullable AttributeSet attrs,
+ @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
+ super(context, attrs, defStyleAttr, defStyleRes);
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+ mMessagingLinearLayout = findViewById(R.id.notification_messaging);
+ mMessagingLinearLayout.setMessagingLayout(this);
+ // We still want to clip, but only on the top, since views can temporarily out of bounds
+ // during transitions.
+ DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
+ int size = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels);
+ Rect rect = new Rect(0, 0, size, size);
+ mMessagingLinearLayout.setClipBounds(rect);
+ mTitleView = findViewById(R.id.title);
+ mAvatarSize = getResources().getDimensionPixelSize(R.dimen.messaging_avatar_size);
+ mTextPaint.setTextAlign(Paint.Align.CENTER);
+ mTextPaint.setAntiAlias(true);
+ mConversationIcon = findViewById(R.id.conversation_icon);
+ mIcon = findViewById(R.id.icon);
+ mConversationIconBadge = findViewById(R.id.conversation_icon_badge);
+ mIcon.setOnVisibilityChangedListener((visibility) -> {
+ // Always keep the badge visibility in sync with the icon. This is necessary in cases
+ // Where the icon is being hidden externally like in group children.
+ mConversationIconBadge.setVisibility(visibility);
+ });
+ mConversationText = findViewById(R.id.conversation_text);
+ mExpandButtonContainer = findViewById(R.id.expand_button_container);
+ mConversationHeader = findViewById(R.id.conversation_header);
+ mContentContainer = findViewById(R.id.notification_action_list_margin_target);
+ mExpandButtonAndContentContainer = findViewById(R.id.expand_button_and_content_container);
+ mExpandButton = findViewById(R.id.expand_button);
+ mExpandButtonExpandedTopMargin = getResources().getDimensionPixelSize(
+ R.dimen.conversation_expand_button_top_margin_expanded);
+ mExpandButtonExpandedSize = getResources().getDimensionPixelSize(
+ R.dimen.conversation_expand_button_expanded_size);
+ mNotificationHeaderExpandedPadding = getResources().getDimensionPixelSize(
+ R.dimen.conversation_header_expanded_padding_end);
+ mContentMarginEnd = getResources().getDimensionPixelSize(
+ R.dimen.notification_content_margin_end);
+ mBadgedSideMargins = getResources().getDimensionPixelSize(
+ R.dimen.conversation_badge_side_margin);
+ mIconSizeBadged = getResources().getDimensionPixelSize(
+ R.dimen.conversation_icon_size_badged);
+ mIconSizeCentered = getResources().getDimensionPixelSize(
+ R.dimen.conversation_icon_size_centered);
+ mExpandedGroupTopMargin = getResources().getDimensionPixelSize(
+ R.dimen.conversation_icon_margin_top_centered);
+ mConversationFacePile = findViewById(R.id.conversation_face_pile);
+ mFallbackChatName = getResources().getString(
+ R.string.conversation_title_fallback_one_to_one);
+ mFallbackGroupChatName = getResources().getString(
+ R.string.conversation_title_fallback_group_chat);
+ }
+
+ @RemotableViewMethod
+ public void setAvatarReplacement(Icon icon) {
+ mAvatarReplacement = icon;
+ }
+
+ @RemotableViewMethod
+ public void setNameReplacement(CharSequence nameReplacement) {
+ mNameReplacement = nameReplacement;
+ }
+
+ /**
+ * Set this layout to show the collapsed representation.
+ *
+ * @param isCollapsed is it collapsed
+ */
+ @RemotableViewMethod
+ public void setIsCollapsed(boolean isCollapsed) {
+ mIsCollapsed = isCollapsed;
+ mMessagingLinearLayout.setMaxDisplayedLines(isCollapsed ? 1 : Integer.MAX_VALUE);
+ updateExpandButton();
+ updateContentPaddings();
+ }
+
+ @RemotableViewMethod
+ public void setData(Bundle extras) {
+ Parcelable[] messages = extras.getParcelableArray(Notification.EXTRA_MESSAGES);
+ List<Notification.MessagingStyle.Message> newMessages
+ = Notification.MessagingStyle.Message.getMessagesFromBundleArray(messages);
+ Parcelable[] histMessages = extras.getParcelableArray(Notification.EXTRA_HISTORIC_MESSAGES);
+ List<Notification.MessagingStyle.Message> newHistoricMessages
+ = Notification.MessagingStyle.Message.getMessagesFromBundleArray(histMessages);
+
+ // mUser now set (would be nice to avoid the side effect but WHATEVER)
+ setUser(extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON));
+
+
+ // Append remote input history to newMessages (again, side effect is lame but WHATEVS)
+ RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
+ extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS);
+ addRemoteInputHistoryToMessages(newMessages, history);
+
+ boolean showSpinner =
+ extras.getBoolean(Notification.EXTRA_SHOW_REMOTE_INPUT_SPINNER, false);
+
+ // bind it, baby
+ bind(newMessages, newHistoricMessages, showSpinner);
+ }
+
+ @Override
+ public void setImageResolver(ImageResolver resolver) {
+ mImageResolver = resolver;
+ }
+
+ private void addRemoteInputHistoryToMessages(
+ List<Notification.MessagingStyle.Message> newMessages,
+ RemoteInputHistoryItem[] remoteInputHistory) {
+ if (remoteInputHistory == null || remoteInputHistory.length == 0) {
+ return;
+ }
+ for (int i = remoteInputHistory.length - 1; i >= 0; i--) {
+ RemoteInputHistoryItem historyMessage = remoteInputHistory[i];
+ Notification.MessagingStyle.Message message = new Notification.MessagingStyle.Message(
+ historyMessage.getText(), 0, (Person) null, true /* remoteHistory */);
+ if (historyMessage.getUri() != null) {
+ message.setData(historyMessage.getMimeType(), historyMessage.getUri());
+ }
+ newMessages.add(message);
+ }
+ }
+
+ private void bind(List<Notification.MessagingStyle.Message> newMessages,
+ List<Notification.MessagingStyle.Message> newHistoricMessages,
+ boolean showSpinner) {
+ // convert MessagingStyle.Message to MessagingMessage, re-using ones from a previous binding
+ // if they exist
+ List<MessagingMessage> historicMessages = createMessages(newHistoricMessages,
+ true /* isHistoric */);
+ List<MessagingMessage> messages = createMessages(newMessages, false /* isHistoric */);
+
+ // Copy our groups, before they get clobbered
+ ArrayList<MessagingGroup> oldGroups = new ArrayList<>(mGroups);
+
+ // Add our new MessagingMessages to groups
+ List<List<MessagingMessage>> groups = new ArrayList<>();
+ List<Person> senders = new ArrayList<>();
+
+ // Lets first find the groups (populate `groups` and `senders`)
+ findGroups(historicMessages, messages, groups, senders);
+
+ // Let's now create the views and reorder them accordingly
+ // side-effect: updates mGroups, mAddedGroups
+ createGroupViews(groups, senders, showSpinner);
+
+ // Let's first check which groups were removed altogether and remove them in one animation
+ removeGroups(oldGroups);
+
+ // Let's remove the remaining messages
+ mMessages.forEach(REMOVE_MESSAGE);
+ mHistoricMessages.forEach(REMOVE_MESSAGE);
+
+ mMessages = messages;
+ mHistoricMessages = historicMessages;
+
+ updateHistoricMessageVisibility();
+ updateTitleAndNamesDisplay();
+
+ updateConversationLayout();
+
+ }
+
+ /**
+ * Update the layout according to the data provided (i.e mIsOneToOne, expanded etc);
+ */
+ private void updateConversationLayout() {
+ // TODO: resolve this from shortcuts
+ // Set avatar and name
+ CharSequence conversationText = mConversationTitle;
+ // TODO: display the secondary text somewhere
+ if (mIsOneToOne) {
+ // Let's resolve the icon / text from the last sender
+ mConversationIcon.setVisibility(VISIBLE);
+ mConversationFacePile.setVisibility(GONE);
+ CharSequence userKey = getKey(mUser);
+ for (int i = mGroups.size() - 1; i >= 0; i--) {
+ MessagingGroup messagingGroup = mGroups.get(i);
+ Person messageSender = messagingGroup.getSender();
+ if ((messageSender != null && !TextUtils.equals(userKey, getKey(messageSender)))
+ || i == 0) {
+ if (TextUtils.isEmpty(conversationText)) {
+ // We use the sendername as header text if no conversation title is provided
+ // (This usually happens for most 1:1 conversations)
+ conversationText = messagingGroup.getSenderName();
+ }
+ Icon avatarIcon = messagingGroup.getAvatarIcon();
+ if (avatarIcon == null) {
+ avatarIcon = createAvatarSymbol(conversationText, "", mLayoutColor);
+ }
+ mConversationIcon.setImageIcon(avatarIcon);
+ break;
+ }
+ }
+ } else {
+ if (mIsCollapsed) {
+ if (mLargeIcon != null) {
+ mConversationIcon.setVisibility(VISIBLE);
+ mConversationFacePile.setVisibility(GONE);
+ mConversationIcon.setImageIcon(mLargeIcon);
+ } else {
+ mConversationIcon.setVisibility(GONE);
+ // This will also inflate it!
+ mConversationFacePile.setVisibility(VISIBLE);
+ mConversationFacePile = findViewById(R.id.conversation_face_pile);
+ bindFacePile();
+ }
+ } else {
+ mConversationFacePile.setVisibility(GONE);
+ mConversationIcon.setVisibility(GONE);
+ }
+ }
+ if (TextUtils.isEmpty(conversationText)) {
+ conversationText = mIsOneToOne ? mFallbackChatName : mFallbackGroupChatName;
+ }
+ mConversationText.setText(conversationText);
+ // Update if the groups can hide the sender if they are first (applies to 1:1 conversations)
+ // This needs to happen after all of the above o update all of the groups
+ for (int i = mGroups.size() - 1; i >= 0; i--) {
+ MessagingGroup messagingGroup = mGroups.get(i);
+ CharSequence messageSender = messagingGroup.getSenderName();
+ boolean canHide = mIsOneToOne
+ && TextUtils.equals(conversationText, messageSender);
+ messagingGroup.setCanHideSenderIfFirst(canHide);
+ }
+ updateIconPositionAndSize();
+ }
+
+ private void bindFacePile() {
+ // Let's bind the face pile
+ View bottomBackground = mConversationFacePile.findViewById(
+ R.id.conversation_face_pile_bottom_background);
+ applyNotificationBackgroundColor(bottomBackground);
+ ImageView bottomView = mConversationFacePile.findViewById(
+ R.id.conversation_face_pile_bottom);
+ ImageView topView = mConversationFacePile.findViewById(
+ R.id.conversation_face_pile_top);
+ // Let's find the two last conversations:
+ Icon secondLastIcon = null;
+ CharSequence lastKey = null;
+ Icon lastIcon = null;
+ CharSequence userKey = getKey(mUser);
+ for (int i = mGroups.size() - 1; i >= 0; i--) {
+ MessagingGroup messagingGroup = mGroups.get(i);
+ Person messageSender = messagingGroup.getSender();
+ boolean notUser = messageSender != null
+ && !TextUtils.equals(userKey, getKey(messageSender));
+ boolean notIncluded = messageSender != null
+ && !TextUtils.equals(lastKey, getKey(messageSender));
+ if ((notUser && notIncluded)
+ || (i == 0 && lastKey == null)) {
+ if (lastIcon == null) {
+ lastIcon = messagingGroup.getAvatarIcon();
+ lastKey = getKey(messageSender);
+ } else {
+ secondLastIcon = messagingGroup.getAvatarIcon();
+ break;
+ }
+ }
+ }
+ if (lastIcon == null) {
+ lastIcon = createAvatarSymbol(" ", "", mLayoutColor);
+ }
+ bottomView.setImageIcon(lastIcon);
+ if (secondLastIcon == null) {
+ secondLastIcon = createAvatarSymbol("", "", mLayoutColor);
+ }
+ topView.setImageIcon(secondLastIcon);
+ }
+
+ /**
+ * update the icon position and sizing
+ */
+ private void updateIconPositionAndSize() {
+ int gravity;
+ int marginStart;
+ int marginTop;
+ int iconSize;
+ if (mIsOneToOne || mIsCollapsed) {
+ // Baded format
+ gravity = Gravity.LEFT;
+ marginStart = mBadgedSideMargins;
+ marginTop = mBadgedSideMargins;
+ iconSize = mIconSizeBadged;
+ } else {
+ gravity = Gravity.CENTER_HORIZONTAL;
+ marginStart = 0;
+ marginTop = mExpandedGroupTopMargin;
+ iconSize = mIconSizeCentered;
+ }
+ LayoutParams layoutParams =
+ (LayoutParams) mConversationIconBadge.getLayoutParams();
+ layoutParams.gravity = gravity;
+ layoutParams.topMargin = marginTop;
+ layoutParams.setMarginStart(marginStart);
+ mConversationIconBadge.setLayoutParams(layoutParams);
+ ViewGroup.LayoutParams iconParams = mIcon.getLayoutParams();
+ iconParams.width = iconSize;
+ iconParams.height = iconSize;
+ mIcon.setLayoutParams(iconParams);
+ }
+
+ @RemotableViewMethod
+ public void setLargeIcon(Icon largeIcon) {
+ mLargeIcon = largeIcon;
+ }
+
+ /**
+ * Sets the conversation title of this conversation.
+ *
+ * @param conversationTitle the conversation title
+ */
+ @RemotableViewMethod
+ public void setConversationTitle(CharSequence conversationTitle) {
+ mConversationTitle = conversationTitle;
+ }
+
+ private void removeGroups(ArrayList<MessagingGroup> oldGroups) {
+ int size = oldGroups.size();
+ for (int i = 0; i < size; i++) {
+ MessagingGroup group = oldGroups.get(i);
+ if (!mGroups.contains(group)) {
+ List<MessagingMessage> messages = group.getMessages();
+ Runnable endRunnable = () -> {
+ mMessagingLinearLayout.removeTransientView(group);
+ group.recycle();
+ };
+
+ boolean wasShown = group.isShown();
+ mMessagingLinearLayout.removeView(group);
+ if (wasShown && !MessagingLinearLayout.isGone(group)) {
+ mMessagingLinearLayout.addTransientView(group, 0);
+ group.removeGroupAnimated(endRunnable);
+ } else {
+ endRunnable.run();
+ }
+ mMessages.removeAll(messages);
+ mHistoricMessages.removeAll(messages);
+ }
+ }
+ }
+
+ private void updateTitleAndNamesDisplay() {
+ ArrayMap<CharSequence, String> uniqueNames = new ArrayMap<>();
+ ArrayMap<Character, CharSequence> uniqueCharacters = new ArrayMap<>();
+ for (int i = 0; i < mGroups.size(); i++) {
+ MessagingGroup group = mGroups.get(i);
+ CharSequence senderName = group.getSenderName();
+ if (!group.needsGeneratedAvatar() || TextUtils.isEmpty(senderName)) {
+ continue;
+ }
+ if (!uniqueNames.containsKey(senderName)) {
+ // Only use visible characters to get uniqueNames
+ String pureSenderName = IGNORABLE_CHAR_PATTERN
+ .matcher(senderName).replaceAll("" /* replacement */);
+ char c = pureSenderName.charAt(0);
+ if (uniqueCharacters.containsKey(c)) {
+ // this character was already used, lets make it more unique. We first need to
+ // resolve the existing character if it exists
+ CharSequence existingName = uniqueCharacters.get(c);
+ if (existingName != null) {
+ uniqueNames.put(existingName, findNameSplit((String) existingName));
+ uniqueCharacters.put(c, null);
+ }
+ uniqueNames.put(senderName, findNameSplit((String) senderName));
+ } else {
+ uniqueNames.put(senderName, Character.toString(c));
+ uniqueCharacters.put(c, pureSenderName);
+ }
+ }
+ }
+
+ // Now that we have the correct symbols, let's look what we have cached
+ ArrayMap<CharSequence, Icon> cachedAvatars = new ArrayMap<>();
+ for (int i = 0; i < mGroups.size(); i++) {
+ // Let's now set the avatars
+ MessagingGroup group = mGroups.get(i);
+ boolean isOwnMessage = group.getSender() == mUser;
+ CharSequence senderName = group.getSenderName();
+ if (!group.needsGeneratedAvatar() || TextUtils.isEmpty(senderName)
+ || (mIsOneToOne && mAvatarReplacement != null && !isOwnMessage)) {
+ continue;
+ }
+ String symbol = uniqueNames.get(senderName);
+ Icon cachedIcon = group.getAvatarSymbolIfMatching(senderName,
+ symbol, mLayoutColor);
+ if (cachedIcon != null) {
+ cachedAvatars.put(senderName, cachedIcon);
+ }
+ }
+
+ for (int i = 0; i < mGroups.size(); i++) {
+ // Let's now set the avatars
+ MessagingGroup group = mGroups.get(i);
+ CharSequence senderName = group.getSenderName();
+ if (!group.needsGeneratedAvatar() || TextUtils.isEmpty(senderName)) {
+ continue;
+ }
+ if (mIsOneToOne && mAvatarReplacement != null && group.getSender() != mUser) {
+ group.setAvatar(mAvatarReplacement);
+ } else {
+ Icon cachedIcon = cachedAvatars.get(senderName);
+ if (cachedIcon == null) {
+ cachedIcon = createAvatarSymbol(senderName, uniqueNames.get(senderName),
+ mLayoutColor);
+ cachedAvatars.put(senderName, cachedIcon);
+ }
+ group.setCreatedAvatar(cachedIcon, senderName, uniqueNames.get(senderName),
+ mLayoutColor);
+ }
+ }
+ }
+
+ private Icon createAvatarSymbol(CharSequence senderName, String symbol, int layoutColor) {
+ if (symbol.isEmpty() || TextUtils.isDigitsOnly(symbol) ||
+ SPECIAL_CHAR_PATTERN.matcher(symbol).find()) {
+ Icon avatarIcon = Icon.createWithResource(getContext(),
+ R.drawable.messaging_user);
+ avatarIcon.setTint(findColor(senderName, layoutColor));
+ return avatarIcon;
+ } else {
+ Bitmap bitmap = Bitmap.createBitmap(mAvatarSize, mAvatarSize, Bitmap.Config.ARGB_8888);
+ Canvas canvas = new Canvas(bitmap);
+ float radius = mAvatarSize / 2.0f;
+ int color = findColor(senderName, layoutColor);
+ mPaint.setColor(color);
+ canvas.drawCircle(radius, radius, radius, mPaint);
+ boolean needDarkText = ColorUtils.calculateLuminance(color) > 0.5f;
+ mTextPaint.setColor(needDarkText ? Color.BLACK : Color.WHITE);
+ mTextPaint.setTextSize(symbol.length() == 1 ? mAvatarSize * 0.5f : mAvatarSize * 0.3f);
+ int yPos = (int) (radius - ((mTextPaint.descent() + mTextPaint.ascent()) / 2));
+ canvas.drawText(symbol, radius, yPos, mTextPaint);
+ return Icon.createWithBitmap(bitmap);
+ }
+ }
+
+ private int findColor(CharSequence senderName, int layoutColor) {
+ double luminance = ContrastColorUtil.calculateLuminance(layoutColor);
+ float shift = Math.abs(senderName.hashCode()) % 5 / 4.0f - 0.5f;
+
+ // we need to offset the range if the luminance is too close to the borders
+ shift += Math.max(COLOR_SHIFT_AMOUNT / 2.0f / 100 - luminance, 0);
+ shift -= Math.max(COLOR_SHIFT_AMOUNT / 2.0f / 100 - (1.0f - luminance), 0);
+ return ContrastColorUtil.getShiftedColor(layoutColor,
+ (int) (shift * COLOR_SHIFT_AMOUNT));
+ }
+
+ private String findNameSplit(String existingName) {
+ String[] split = existingName.split(" ");
+ if (split.length > 1) {
+ return Character.toString(split[0].charAt(0))
+ + Character.toString(split[1].charAt(0));
+ }
+ return existingName.substring(0, 1);
+ }
+
+ @RemotableViewMethod
+ public void setLayoutColor(int color) {
+ mLayoutColor = color;
+ }
+
+ @RemotableViewMethod
+ public void setIsOneToOne(boolean oneToOne) {
+ mIsOneToOne = oneToOne;
+ }
+
+ @RemotableViewMethod
+ public void setSenderTextColor(int color) {
+ mSenderTextColor = color;
+ }
+
+ /**
+ * @param color the color of the notification background
+ */
+ @RemotableViewMethod
+ public void setNotificationBackgroundColor(int color) {
+ mNotificationBackgroundColor = color;
+ applyNotificationBackgroundColor(mConversationIconBadge);
+ }
+
+ private void applyNotificationBackgroundColor(View view) {
+ view.setBackgroundTintList(ColorStateList.valueOf(mNotificationBackgroundColor));
+ }
+
+ @RemotableViewMethod
+ public void setMessageTextColor(int color) {
+ mMessageTextColor = color;
+ }
+
+ private void setUser(Person user) {
+ mUser = user;
+ if (mUser.getIcon() == null) {
+ Icon userIcon = Icon.createWithResource(getContext(),
+ R.drawable.messaging_user);
+ userIcon.setTint(mLayoutColor);
+ mUser = mUser.toBuilder().setIcon(userIcon).build();
+ }
+ }
+
+ private void createGroupViews(List<List<MessagingMessage>> groups,
+ List<Person> senders, boolean showSpinner) {
+ mGroups.clear();
+ for (int groupIndex = 0; groupIndex < groups.size(); groupIndex++) {
+ List<MessagingMessage> group = groups.get(groupIndex);
+ MessagingGroup newGroup = null;
+ // we'll just take the first group that exists or create one there is none
+ for (int messageIndex = group.size() - 1; messageIndex >= 0; messageIndex--) {
+ MessagingMessage message = group.get(messageIndex);
+ newGroup = message.getGroup();
+ if (newGroup != null) {
+ break;
+ }
+ }
+ // Create a new group, adding it to the linear layout as well
+ if (newGroup == null) {
+ newGroup = MessagingGroup.createGroup(mMessagingLinearLayout);
+ mAddedGroups.add(newGroup);
+ }
+ newGroup.setDisplayImagesAtEnd(mIsCollapsed);
+ newGroup.setIsInConversation(true);
+ newGroup.setLayoutColor(mLayoutColor);
+ newGroup.setTextColors(mSenderTextColor, mMessageTextColor);
+ Person sender = senders.get(groupIndex);
+ CharSequence nameOverride = null;
+ if (sender != mUser && mNameReplacement != null) {
+ nameOverride = mNameReplacement;
+ }
+ newGroup.setShowingAvatar(!mIsOneToOne && !mIsCollapsed);
+ newGroup.setSingleLine(mIsCollapsed);
+ newGroup.setSender(sender, nameOverride);
+ newGroup.setSending(groupIndex == (groups.size() - 1) && showSpinner);
+ mGroups.add(newGroup);
+
+ // Reposition to the correct place (if we're re-using a group)
+ if (mMessagingLinearLayout.indexOfChild(newGroup) != groupIndex) {
+ mMessagingLinearLayout.removeView(newGroup);
+ mMessagingLinearLayout.addView(newGroup, groupIndex);
+ }
+ newGroup.setMessages(group);
+ }
+ }
+
+ private void findGroups(List<MessagingMessage> historicMessages,
+ List<MessagingMessage> messages, List<List<MessagingMessage>> groups,
+ List<Person> senders) {
+ CharSequence currentSenderKey = null;
+ List<MessagingMessage> currentGroup = null;
+ int histSize = historicMessages.size();
+ for (int i = 0; i < histSize + messages.size(); i++) {
+ MessagingMessage message;
+ if (i < histSize) {
+ message = historicMessages.get(i);
+ } else {
+ message = messages.get(i - histSize);
+ }
+ boolean isNewGroup = currentGroup == null;
+ Person sender = message.getMessage().getSenderPerson();
+ CharSequence key = getKey(sender);
+ isNewGroup |= !TextUtils.equals(key, currentSenderKey);
+ if (isNewGroup) {
+ currentGroup = new ArrayList<>();
+ groups.add(currentGroup);
+ if (sender == null) {
+ sender = mUser;
+ }
+ senders.add(sender);
+ currentSenderKey = key;
+ }
+ currentGroup.add(message);
+ }
+ }
+
+ private CharSequence getKey(Person person) {
+ return person == null ? null : person.getKey() == null ? person.getName() : person.getKey();
+ }
+
+ /**
+ * Creates new messages, reusing existing ones if they are available.
+ *
+ * @param newMessages the messages to parse.
+ */
+ private List<MessagingMessage> createMessages(
+ List<Notification.MessagingStyle.Message> newMessages, boolean historic) {
+ List<MessagingMessage> result = new ArrayList<>();
+ for (int i = 0; i < newMessages.size(); i++) {
+ Notification.MessagingStyle.Message m = newMessages.get(i);
+ MessagingMessage message = findAndRemoveMatchingMessage(m);
+ if (message == null) {
+ message = MessagingMessage.createMessage(this, m, mImageResolver);
+ }
+ message.setIsHistoric(historic);
+ result.add(message);
+ }
+ return result;
+ }
+
+ private MessagingMessage findAndRemoveMatchingMessage(Notification.MessagingStyle.Message m) {
+ for (int i = 0; i < mMessages.size(); i++) {
+ MessagingMessage existing = mMessages.get(i);
+ if (existing.sameAs(m)) {
+ mMessages.remove(i);
+ return existing;
+ }
+ }
+ for (int i = 0; i < mHistoricMessages.size(); i++) {
+ MessagingMessage existing = mHistoricMessages.get(i);
+ if (existing.sameAs(m)) {
+ mHistoricMessages.remove(i);
+ return existing;
+ }
+ }
+ return null;
+ }
+
+ public void showHistoricMessages(boolean show) {
+ mShowHistoricMessages = show;
+ updateHistoricMessageVisibility();
+ }
+
+ private void updateHistoricMessageVisibility() {
+ int numHistoric = mHistoricMessages.size();
+ for (int i = 0; i < numHistoric; i++) {
+ MessagingMessage existing = mHistoricMessages.get(i);
+ existing.setVisibility(mShowHistoricMessages ? VISIBLE : GONE);
+ }
+ int numGroups = mGroups.size();
+ for (int i = 0; i < numGroups; i++) {
+ MessagingGroup group = mGroups.get(i);
+ int visibleChildren = 0;
+ List<MessagingMessage> messages = group.getMessages();
+ int numGroupMessages = messages.size();
+ for (int j = 0; j < numGroupMessages; j++) {
+ MessagingMessage message = messages.get(j);
+ if (message.getVisibility() != GONE) {
+ visibleChildren++;
+ }
+ }
+ if (visibleChildren > 0 && group.getVisibility() == GONE) {
+ group.setVisibility(VISIBLE);
+ } else if (visibleChildren == 0 && group.getVisibility() != GONE) {
+ group.setVisibility(GONE);
+ }
+ }
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+ super.onLayout(changed, left, top, right, bottom);
+ if (!mAddedGroups.isEmpty()) {
+ getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
+ @Override
+ public boolean onPreDraw() {
+ for (MessagingGroup group : mAddedGroups) {
+ if (!group.isShown()) {
+ continue;
+ }
+ MessagingPropertyAnimator.fadeIn(group.getAvatar());
+ MessagingPropertyAnimator.fadeIn(group.getSenderView());
+ MessagingPropertyAnimator.startLocalTranslationFrom(group,
+ group.getHeight(), LINEAR_OUT_SLOW_IN);
+ }
+ mAddedGroups.clear();
+ getViewTreeObserver().removeOnPreDrawListener(this);
+ return true;
+ }
+ });
+ }
+ }
+
+ public MessagingLinearLayout getMessagingLinearLayout() {
+ return mMessagingLinearLayout;
+ }
+
+ public ArrayList<MessagingGroup> getMessagingGroups() {
+ return mGroups;
+ }
+
+ private void updateExpandButton() {
+ int drawableId;
+ int contentDescriptionId;
+ int gravity;
+ int topMargin = 0;
+ ViewGroup newContainer;
+ int newContainerHeight;
+ if (mIsCollapsed) {
+ drawableId = R.drawable.ic_expand_notification;
+ contentDescriptionId = R.string.expand_button_content_description_collapsed;
+ gravity = Gravity.CENTER;
+ newContainer = mExpandButtonAndContentContainer;
+ newContainerHeight = LayoutParams.MATCH_PARENT;
+ } else {
+ drawableId = R.drawable.ic_collapse_notification;
+ contentDescriptionId = R.string.expand_button_content_description_expanded;
+ gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
+ topMargin = mExpandButtonExpandedTopMargin;
+ newContainer = this;
+ newContainerHeight = mExpandButtonExpandedSize;
+ }
+ mExpandButton.setImageDrawable(getContext().getDrawable(drawableId));
+ mExpandButton.setColorFilter(mExpandButton.getOriginalNotificationColor());
+
+ // We need to make sure that the expand button is in the linearlayout pushing over the
+ // content when collapsed, but allows the content to flow under it when expanded.
+ if (newContainer != mExpandButtonContainer.getParent()) {
+ ((ViewGroup) mExpandButtonContainer.getParent()).removeView(mExpandButtonContainer);
+ newContainer.addView(mExpandButtonContainer);
+ MarginLayoutParams layoutParams =
+ (MarginLayoutParams) mExpandButtonContainer.getLayoutParams();
+ layoutParams.height = newContainerHeight;
+ mExpandButtonContainer.setLayoutParams(layoutParams);
+ }
+
+ // update if the expand button is centered
+ FrameLayout.LayoutParams layoutParams = (LayoutParams) mExpandButton.getLayoutParams();
+ layoutParams.gravity = gravity;
+ layoutParams.topMargin = topMargin;
+ mExpandButton.setLayoutParams(layoutParams);
+
+ mExpandButtonContainer.setContentDescription(mContext.getText(contentDescriptionId));
+ }
+
+ private void updateContentPaddings() {
+
+ // Let's make sure the conversation header can't run into the expand button when we're
+ // collapsed and update the paddings of the content
+ int headerPaddingEnd;
+ int contentPaddingEnd;
+ if (!mExpandable) {
+ headerPaddingEnd = 0;
+ contentPaddingEnd = mContentMarginEnd;
+ } else if (mIsCollapsed) {
+ headerPaddingEnd = 0;
+ contentPaddingEnd = 0;
+ } else {
+ headerPaddingEnd = mNotificationHeaderExpandedPadding;
+ contentPaddingEnd = mContentMarginEnd;
+ }
+ mConversationHeader.setPaddingRelative(
+ mConversationHeader.getPaddingStart(),
+ mConversationHeader.getPaddingTop(),
+ headerPaddingEnd,
+ mConversationHeader.getPaddingBottom());
+
+ mContentContainer.setPaddingRelative(
+ mContentContainer.getPaddingStart(),
+ mContentContainer.getPaddingTop(),
+ contentPaddingEnd,
+ mContentContainer.getPaddingBottom());
+ }
+
+ public void updateExpandability(boolean expandable, @Nullable OnClickListener onClickListener) {
+ mExpandable = expandable;
+ if (expandable) {
+ mExpandButtonContainer.setVisibility(VISIBLE);
+ mExpandButtonContainer.setOnClickListener(onClickListener);
+ } else {
+ // TODO: handle content paddings to end of layout
+ mExpandButtonContainer.setVisibility(GONE);
+ }
+ updateContentPaddings();
+ }
+}
diff --git a/core/java/com/android/internal/widget/IMessagingLayout.java b/core/java/com/android/internal/widget/IMessagingLayout.java
new file mode 100644
index 0000000..149d056
--- /dev/null
+++ b/core/java/com/android/internal/widget/IMessagingLayout.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2020 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.internal.widget;
+
+import android.content.Context;
+
+import java.util.ArrayList;
+
+/**
+ * An interface for a MessagingLayout
+ */
+public interface IMessagingLayout {
+
+ /**
+ * @return the layout containing the messages
+ */
+ MessagingLinearLayout getMessagingLinearLayout();
+
+ /**
+ * @return the context of this view
+ */
+ Context getContext();
+
+ /**
+ * @return the list of messaging groups
+ */
+ ArrayList<MessagingGroup> getMessagingGroups();
+}
diff --git a/core/java/com/android/internal/widget/MessagingGroup.java b/core/java/com/android/internal/widget/MessagingGroup.java
index c9a9161..c68da97 100644
--- a/core/java/com/android/internal/widget/MessagingGroup.java
+++ b/core/java/com/android/internal/widget/MessagingGroup.java
@@ -55,8 +55,9 @@
private static Pools.SimplePool<MessagingGroup> sInstancePool
= new Pools.SynchronizedPool<>(10);
private MessagingLinearLayout mMessageContainer;
- private ImageFloatingTextView mSenderName;
+ ImageFloatingTextView mSenderView;
private ImageView mAvatarView;
+ private View mAvatarContainer;
private String mAvatarSymbol = "";
private int mLayoutColor;
private CharSequence mAvatarName = "";
@@ -72,10 +73,22 @@
private boolean mImagesAtEnd;
private ViewGroup mImageContainer;
private MessagingImageMessage mIsolatedMessage;
- private boolean mTransformingImages;
+ private boolean mClippingDisabled;
private Point mDisplaySize = new Point();
private ProgressBar mSendingSpinner;
private View mSendingSpinnerContainer;
+ private boolean mShowingAvatar = true;
+ private CharSequence mSenderName;
+ private boolean mSingleLine = false;
+ private LinearLayout mContentContainer;
+ private int mRequestedMaxDisplayedLines = Integer.MAX_VALUE;
+ private int mSenderTextPaddingSingleLine;
+ private boolean mIsFirstGroupInLayout = true;
+ private boolean mCanHideSenderIfFirst;
+ private boolean mIsInConversation = true;
+ private ViewGroup mMessagingIconContainer;
+ private int mConversationContentStart;
+ private int mNonConversationMarginEnd;
public MessagingGroup(@NonNull Context context) {
super(context);
@@ -99,26 +112,39 @@
protected void onFinishInflate() {
super.onFinishInflate();
mMessageContainer = findViewById(R.id.group_message_container);
- mSenderName = findViewById(R.id.message_name);
+ mSenderView = findViewById(R.id.message_name);
mAvatarView = findViewById(R.id.message_icon);
mImageContainer = findViewById(R.id.messaging_group_icon_container);
mSendingSpinner = findViewById(R.id.messaging_group_sending_progress);
+ mMessagingIconContainer = findViewById(R.id.message_icon_container);
+ mContentContainer = findViewById(R.id.messaging_group_content_container);
mSendingSpinnerContainer = findViewById(R.id.messaging_group_sending_progress_container);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
mDisplaySize.x = displayMetrics.widthPixels;
mDisplaySize.y = displayMetrics.heightPixels;
+ mSenderTextPaddingSingleLine = getResources().getDimensionPixelSize(
+ R.dimen.messaging_group_singleline_sender_padding_end);
+ mConversationContentStart = getResources().getDimensionPixelSize(
+ R.dimen.conversation_content_start);
+ mNonConversationMarginEnd = getResources().getDimensionPixelSize(
+ R.dimen.messaging_layout_margin_end);
}
public void updateClipRect() {
// We want to clip to the senderName if it's available, otherwise our images will come
// from a weird position
Rect clipRect;
- if (mSenderName.getVisibility() != View.GONE && !mTransformingImages) {
- ViewGroup parent = (ViewGroup) mSenderName.getParent();
- int top = getDistanceFromParent(mSenderName, parent) - getDistanceFromParent(
- mMessageContainer, parent) + mSenderName.getHeight();
+ if (mSenderView.getVisibility() != View.GONE && !mClippingDisabled) {
+ int top;
+ if (mSingleLine) {
+ top = 0;
+ } else {
+ top = getDistanceFromParent(mSenderView, mContentContainer)
+ - getDistanceFromParent(mMessageContainer, mContentContainer)
+ + mSenderView.getHeight();
+ }
int size = Math.max(mDisplaySize.x, mDisplaySize.y);
- clipRect = new Rect(0, top, size, size);
+ clipRect = new Rect(-size, top, size, size);
} else {
clipRect = null;
}
@@ -140,17 +166,31 @@
if (nameOverride == null) {
nameOverride = sender.getName();
}
- mSenderName.setText(nameOverride);
+ mSenderName = nameOverride;
+ if (mSingleLine && !TextUtils.isEmpty(nameOverride)) {
+ nameOverride = mContext.getResources().getString(
+ R.string.conversation_single_line_name_display, nameOverride);
+ }
+ mSenderView.setText(nameOverride);
mNeedsGeneratedAvatar = sender.getIcon() == null;
if (!mNeedsGeneratedAvatar) {
setAvatar(sender.getIcon());
}
- mAvatarView.setVisibility(VISIBLE);
- mSenderName.setVisibility(TextUtils.isEmpty(nameOverride) ? GONE : VISIBLE);
+ updateSenderVisibility();
+ }
+
+ /**
+ * Should the avatar be shown for this view.
+ *
+ * @param showingAvatar should it be shown
+ */
+ public void setShowingAvatar(boolean showingAvatar) {
+ mAvatarView.setVisibility(showingAvatar ? VISIBLE : GONE);
+ mShowingAvatar = showingAvatar;
}
public void setSending(boolean sending) {
- int visibility = sending ? View.VISIBLE : View.GONE;
+ int visibility = sending ? VISIBLE : GONE;
if (mSendingSpinnerContainer.getVisibility() != visibility) {
mSendingSpinnerContainer.setVisibility(visibility);
updateMessageColor();
@@ -171,7 +211,9 @@
public void setAvatar(Icon icon) {
mAvatarIcon = icon;
- mAvatarView.setImageIcon(icon);
+ if (mShowingAvatar || icon == null) {
+ mAvatarView.setImageIcon(icon);
+ }
mAvatarSymbol = "";
mAvatarName = "";
}
@@ -220,13 +262,20 @@
setAvatar(null);
mAvatarView.setAlpha(1.0f);
mAvatarView.setTranslationY(0.0f);
- mSenderName.setAlpha(1.0f);
- mSenderName.setTranslationY(0.0f);
+ mSenderView.setAlpha(1.0f);
+ mSenderView.setTranslationY(0.0f);
setAlpha(1.0f);
mIsolatedMessage = null;
mMessages = null;
+ mSenderName = null;
mAddedMessages.clear();
mFirstLayout = true;
+ setCanHideSenderIfFirst(false);
+ setIsFirstInLayout(true);
+
+ setMaxDisplayedLines(Integer.MAX_VALUE);
+ setSingleLine(false);
+ setShowingAvatar(true);
MessagingPropertyAnimator.recycle(this);
sInstancePool.release(MessagingGroup.this);
}
@@ -252,7 +301,7 @@
}
public CharSequence getSenderName() {
- return mSenderName.getText();
+ return mSenderName;
}
public static void dropCache() {
@@ -310,7 +359,12 @@
@Override
public void setMaxDisplayedLines(int lines) {
- mMessageContainer.setMaxDisplayedLines(lines);
+ mRequestedMaxDisplayedLines = lines;
+ updateMaxDisplayedLines();
+ }
+
+ private void updateMaxDisplayedLines() {
+ mMessageContainer.setMaxDisplayedLines(mSingleLine ? 1 : mRequestedMaxDisplayedLines);
}
@Override
@@ -324,6 +378,35 @@
return mIsHidingAnimated;
}
+ @Override
+ public void setIsFirstInLayout(boolean first) {
+ if (first != mIsFirstGroupInLayout) {
+ mIsFirstGroupInLayout = first;
+ updateSenderVisibility();
+ }
+ }
+
+ /**
+ * @param canHide true if the sender can be hidden if it is first
+ */
+ public void setCanHideSenderIfFirst(boolean canHide) {
+ if (mCanHideSenderIfFirst != canHide) {
+ mCanHideSenderIfFirst = canHide;
+ updateSenderVisibility();
+ }
+ }
+
+ private void updateSenderVisibility() {
+ boolean hidden = (mIsFirstGroupInLayout || mSingleLine) && mCanHideSenderIfFirst
+ || TextUtils.isEmpty(mSenderName);
+ mSenderView.setVisibility(hidden ? GONE : VISIBLE);
+ }
+
+ @Override
+ public boolean hasDifferentHeightWhenFirst() {
+ return mCanHideSenderIfFirst && !mSingleLine && !TextUtils.isEmpty(mSenderName);
+ }
+
private void setIsHidingAnimated(boolean isHiding) {
ViewParent parent = getParent();
mIsHidingAnimated = isHiding;
@@ -362,7 +445,7 @@
mTextColor = messageTextColor;
mSendingTextColor = calculateSendingTextColor();
updateMessageColor();
- mSenderName.setTextColor(senderTextColor);
+ mSenderView.setTextColor(senderTextColor);
}
public void setLayoutColor(int layoutColor) {
@@ -506,13 +589,17 @@
}
public View getSenderView() {
- return mSenderName;
+ return mSenderView;
}
public View getAvatar() {
return mAvatarView;
}
+ public Icon getAvatarIcon() {
+ return mAvatarIcon;
+ }
+
public MessagingLinearLayout getMessageContainer() {
return mMessageContainer;
}
@@ -529,8 +616,8 @@
return mSender;
}
- public void setTransformingImages(boolean transformingImages) {
- mTransformingImages = transformingImages;
+ public void setClippingDisabled(boolean disabled) {
+ mClippingDisabled = disabled;
}
public void setDisplayImagesAtEnd(boolean atEnd) {
@@ -543,4 +630,44 @@
public List<MessagingMessage> getMessages() {
return mMessages;
}
+
+ /**
+ * Set this layout to be single line and therefore displaying both the sender and the text on
+ * the same line.
+ *
+ * @param singleLine should be layout be single line
+ */
+ public void setSingleLine(boolean singleLine) {
+ if (singleLine != mSingleLine) {
+ mSingleLine = singleLine;
+ mContentContainer.setOrientation(
+ singleLine ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
+ MarginLayoutParams layoutParams = (MarginLayoutParams) mSenderView.getLayoutParams();
+ layoutParams.setMarginEnd(singleLine ? mSenderTextPaddingSingleLine : 0);
+ updateMaxDisplayedLines();
+ updateClipRect();
+ updateSenderVisibility();
+ }
+ }
+
+ public boolean isSingleLine() {
+ return mSingleLine;
+ }
+
+ /**
+ * Set this group to be displayed in a conversation and adjust the visual appearance
+ *
+ * @param isInConversation is this in a conversation
+ */
+ public void setIsInConversation(boolean isInConversation) {
+ if (mIsInConversation != isInConversation) {
+ mIsInConversation = isInConversation;
+ MarginLayoutParams layoutParams =
+ (MarginLayoutParams) mMessagingIconContainer.getLayoutParams();
+ layoutParams.width = mIsInConversation ? mConversationContentStart
+ : ViewPager.LayoutParams.WRAP_CONTENT;
+ layoutParams.setMarginEnd(mIsInConversation ? 0 : mNonConversationMarginEnd);
+ mMessagingIconContainer.setLayoutParams(layoutParams);
+ }
+ }
}
diff --git a/core/java/com/android/internal/widget/MessagingImageMessage.java b/core/java/com/android/internal/widget/MessagingImageMessage.java
index 64650a7..c243f3b 100644
--- a/core/java/com/android/internal/widget/MessagingImageMessage.java
+++ b/core/java/com/android/internal/widget/MessagingImageMessage.java
@@ -120,7 +120,7 @@
return true;
}
- static MessagingMessage createMessage(MessagingLayout layout,
+ static MessagingMessage createMessage(IMessagingLayout layout,
Notification.MessagingStyle.Message m, ImageResolver resolver) {
MessagingLinearLayout messagingLinearLayout = layout.getMessagingLinearLayout();
MessagingImageMessage createdMessage = sInstancePool.acquire();
diff --git a/core/java/com/android/internal/widget/MessagingLayout.java b/core/java/com/android/internal/widget/MessagingLayout.java
index f608958..3fb5d43 100644
--- a/core/java/com/android/internal/widget/MessagingLayout.java
+++ b/core/java/com/android/internal/widget/MessagingLayout.java
@@ -58,7 +58,8 @@
* messages and adapts the layout accordingly.
*/
@RemoteViews.RemoteView
-public class MessagingLayout extends FrameLayout implements ImageMessageConsumer {
+public class MessagingLayout extends FrameLayout
+ implements ImageMessageConsumer, IMessagingLayout {
private static final float COLOR_SHIFT_AMOUNT = 60;
/**
@@ -143,9 +144,29 @@
mNameReplacement = nameReplacement;
}
+ /**
+ * Set this layout to show the collapsed representation.
+ *
+ * @param isCollapsed is it collapsed
+ */
@RemotableViewMethod
- public void setDisplayImagesAtEnd(boolean atEnd) {
- mDisplayImagesAtEnd = atEnd;
+ public void setIsCollapsed(boolean isCollapsed) {
+ mDisplayImagesAtEnd = isCollapsed;
+ }
+
+ @RemotableViewMethod
+ public void setLargeIcon(Icon largeIcon) {
+ // Unused
+ }
+
+ /**
+ * Sets the conversation title of this conversation.
+ *
+ * @param conversationTitle the conversation title
+ */
+ @RemotableViewMethod
+ public void setConversationTitle(CharSequence conversationTitle) {
+ // Unused
}
@RemotableViewMethod
@@ -371,6 +392,15 @@
mSenderTextColor = color;
}
+
+ /**
+ * @param color the color of the notification background
+ */
+ @RemotableViewMethod
+ public void setNotificationBackgroundColor(int color) {
+ // Nothing to do with this
+ }
+
@RemotableViewMethod
public void setMessageTextColor(int color) {
mMessageTextColor = color;
@@ -418,6 +448,7 @@
mAddedGroups.add(newGroup);
}
newGroup.setDisplayImagesAtEnd(mDisplayImagesAtEnd);
+ newGroup.setIsInConversation(false);
newGroup.setLayoutColor(mLayoutColor);
newGroup.setTextColors(mSenderTextColor, mMessageTextColor);
Person sender = senders.get(groupIndex);
diff --git a/core/java/com/android/internal/widget/MessagingLinearLayout.java b/core/java/com/android/internal/widget/MessagingLinearLayout.java
index 0c8613b..ac04862 100644
--- a/core/java/com/android/internal/widget/MessagingLinearLayout.java
+++ b/core/java/com/android/internal/widget/MessagingLinearLayout.java
@@ -43,7 +43,7 @@
private int mMaxDisplayedLines = Integer.MAX_VALUE;
- private MessagingLayout mMessagingLayout;
+ private IMessagingLayout mMessagingLayout;
public MessagingLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
@@ -84,6 +84,11 @@
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.hide = true;
+ if (child instanceof MessagingChild) {
+ MessagingChild messagingChild = (MessagingChild) child;
+ // Whenever we encounter the message first, it's always first in the layout
+ messagingChild.setIsFirstInLayout(true);
+ }
}
totalHeight = mPaddingTop + mPaddingBottom;
@@ -91,6 +96,11 @@
int linesRemaining = mMaxDisplayedLines;
// Starting from the bottom: we measure every view as if it were the only one. If it still
// fits, we take it, otherwise we stop there.
+ MessagingChild previousChild = null;
+ View previousView = null;
+ int previousChildHeight = 0;
+ int previousTotalHeight = 0;
+ int previousLinesConsumed = 0;
for (int i = count - 1; i >= 0 && totalHeight < targetHeight; i--) {
if (getChildAt(i).getVisibility() == GONE) {
continue;
@@ -99,7 +109,16 @@
LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams();
MessagingChild messagingChild = null;
int spacing = mSpacing;
+ int previousChildIncrease = 0;
if (child instanceof MessagingChild) {
+ // We need to remeasure the previous child again if it's not the first anymore
+ if (previousChild != null && previousChild.hasDifferentHeightWhenFirst()) {
+ previousChild.setIsFirstInLayout(false);
+ measureChildWithMargins(previousView, widthMeasureSpec, 0, heightMeasureSpec,
+ previousTotalHeight - previousChildHeight);
+ previousChildIncrease = previousView.getMeasuredHeight() - previousChildHeight;
+ linesRemaining -= previousChild.getConsumedLines() - previousLinesConsumed;
+ }
messagingChild = (MessagingChild) child;
messagingChild.setMaxDisplayedLines(linesRemaining);
spacing += messagingChild.getExtraSpacing();
@@ -110,18 +129,26 @@
final int childHeight = child.getMeasuredHeight();
int newHeight = Math.max(totalHeight, totalHeight + childHeight + lp.topMargin +
- lp.bottomMargin + spacing);
+ lp.bottomMargin + spacing + previousChildIncrease);
int measureType = MessagingChild.MEASURED_NORMAL;
if (messagingChild != null) {
measureType = messagingChild.getMeasuredType();
- linesRemaining -= messagingChild.getConsumedLines();
}
// We never measure the first item as too small, we want to at least show something.
boolean isTooSmall = measureType == MessagingChild.MEASURED_TOO_SMALL && !first;
boolean isShortened = measureType == MessagingChild.MEASURED_SHORTENED
|| measureType == MessagingChild.MEASURED_TOO_SMALL && first;
- if (newHeight <= targetHeight && !isTooSmall) {
+ boolean showView = newHeight <= targetHeight && !isTooSmall;
+ if (showView) {
+ if (messagingChild != null) {
+ previousLinesConsumed = messagingChild.getConsumedLines();
+ linesRemaining -= previousLinesConsumed;
+ previousChild = messagingChild;
+ previousView = child;
+ previousChildHeight = childHeight;
+ previousTotalHeight = totalHeight;
+ }
totalHeight = newHeight;
measuredWidth = Math.max(measuredWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin
@@ -131,6 +158,16 @@
break;
}
} else {
+ // We now became too short, let's make sure to reset any previous views to be first
+ // and remeasure it.
+ if (previousChild != null && previousChild.hasDifferentHeightWhenFirst()) {
+ previousChild.setIsFirstInLayout(true);
+ // We need to remeasure the previous child again since it became first
+ measureChildWithMargins(previousView, widthMeasureSpec, 0, heightMeasureSpec,
+ previousTotalHeight - previousChildHeight);
+ // The totalHeight is already correct here since we only set it during the
+ // first pass
+ }
break;
}
first = false;
@@ -255,11 +292,11 @@
mMaxDisplayedLines = numberLines;
}
- public void setMessagingLayout(MessagingLayout layout) {
+ public void setMessagingLayout(IMessagingLayout layout) {
mMessagingLayout = layout;
}
- public MessagingLayout getMessagingLayout() {
+ public IMessagingLayout getMessagingLayout() {
return mMessagingLayout;
}
@@ -273,6 +310,20 @@
void setMaxDisplayedLines(int lines);
void hideAnimated();
boolean isHidingAnimated();
+
+ /**
+ * Set that this view is first in layout. Relevant and only set if
+ * {@link #hasDifferentHeightWhenFirst()}.
+ * @param first is this first?
+ */
+ default void setIsFirstInLayout(boolean first) {}
+
+ /**
+ * @return if this layout has different height it is first in the layout
+ */
+ default boolean hasDifferentHeightWhenFirst() {
+ return false;
+ }
default int getExtraSpacing() {
return 0;
}
diff --git a/core/java/com/android/internal/widget/MessagingMessage.java b/core/java/com/android/internal/widget/MessagingMessage.java
index c32d370..8c84379 100644
--- a/core/java/com/android/internal/widget/MessagingMessage.java
+++ b/core/java/com/android/internal/widget/MessagingMessage.java
@@ -32,7 +32,7 @@
**/
String IMAGE_MIME_TYPE_PREFIX = "image/";
- static MessagingMessage createMessage(MessagingLayout layout,
+ static MessagingMessage createMessage(IMessagingLayout layout,
Notification.MessagingStyle.Message m, ImageResolver resolver) {
if (hasImage(m) && !ActivityManager.isLowRamDeviceStatic()) {
return MessagingImageMessage.createMessage(layout, m, resolver);
diff --git a/core/java/com/android/internal/widget/MessagingTextMessage.java b/core/java/com/android/internal/widget/MessagingTextMessage.java
index 4081a86..d778c59 100644
--- a/core/java/com/android/internal/widget/MessagingTextMessage.java
+++ b/core/java/com/android/internal/widget/MessagingTextMessage.java
@@ -26,14 +26,10 @@
import android.util.AttributeSet;
import android.util.Pools;
import android.view.LayoutInflater;
-import android.view.ViewGroup;
-import android.view.ViewParent;
import android.widget.RemoteViews;
import com.android.internal.R;
-import java.util.Objects;
-
/**
* A message of a {@link MessagingLayout}.
*/
@@ -74,7 +70,7 @@
return true;
}
- static MessagingMessage createMessage(MessagingLayout layout,
+ static MessagingMessage createMessage(IMessagingLayout layout,
Notification.MessagingStyle.Message m) {
MessagingLinearLayout messagingLinearLayout = layout.getMessagingLinearLayout();
MessagingTextMessage createdMessage = sInstancePool.acquire();
diff --git a/core/java/com/android/internal/widget/NotificationExpandButton.java b/core/java/com/android/internal/widget/NotificationExpandButton.java
index 39f82a5..a499806 100644
--- a/core/java/com/android/internal/widget/NotificationExpandButton.java
+++ b/core/java/com/android/internal/widget/NotificationExpandButton.java
@@ -20,7 +20,7 @@
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
-import android.view.View;
+import android.view.RemotableViewMethod;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.ImageView;
@@ -32,6 +32,8 @@
@RemoteViews.RemoteView
public class NotificationExpandButton extends ImageView {
+ private int mOriginalNotificationColor;
+
public NotificationExpandButton(Context context) {
super(context);
}
@@ -56,6 +58,15 @@
extendRectToMinTouchSize(outRect);
}
+ @RemotableViewMethod
+ public void setOriginalNotificationColor(int color) {
+ mOriginalNotificationColor = color;
+ }
+
+ public int getOriginalNotificationColor() {
+ return mOriginalNotificationColor;
+ }
+
private void extendRectToMinTouchSize(Rect rect) {
int touchTargetSize = (int) (getResources().getDisplayMetrics().density * 48);
rect.left = rect.centerX() - touchTargetSize / 2;
diff --git a/core/java/com/android/internal/widget/RemeasuringLinearLayout.java b/core/java/com/android/internal/widget/RemeasuringLinearLayout.java
index e352b45..7b154a5 100644
--- a/core/java/com/android/internal/widget/RemeasuringLinearLayout.java
+++ b/core/java/com/android/internal/widget/RemeasuringLinearLayout.java
@@ -23,6 +23,8 @@
import android.widget.LinearLayout;
import android.widget.RemoteViews;
+import java.util.ArrayList;
+
/**
* A LinearLayout that sets it's height again after the last measure pass. This is needed for
* MessagingLayouts where groups need to be able to snap it's height to.
@@ -30,6 +32,8 @@
@RemoteViews.RemoteView
public class RemeasuringLinearLayout extends LinearLayout {
+ private ArrayList<View> mMatchParentViews = new ArrayList<>();
+
public RemeasuringLinearLayout(Context context) {
super(context);
}
@@ -53,6 +57,8 @@
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int count = getChildCount();
int height = 0;
+ boolean isVertical = getOrientation() == LinearLayout.VERTICAL;
+ boolean isWrapContent = getLayoutParams().height == LayoutParams.WRAP_CONTENT;
for (int i = 0; i < count; ++i) {
final View child = getChildAt(i);
if (child == null || child.getVisibility() == View.GONE) {
@@ -60,9 +66,25 @@
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
- height = Math.max(height, height + child.getMeasuredHeight() + lp.topMargin +
- lp.bottomMargin);
+ if (!isWrapContent || lp.height != LayoutParams.MATCH_PARENT || isVertical) {
+ int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
+ height = Math.max(height, isVertical ? height + childHeight : childHeight);
+ } else {
+ // We have match parent children in a wrap content view, let's measure the
+ // view properly
+ mMatchParentViews.add(child);
+ }
}
+ if (mMatchParentViews.size() > 0) {
+ int exactHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
+ for (View child : mMatchParentViews) {
+ child.measure(getChildMeasureSpec(
+ widthMeasureSpec, getPaddingStart() + getPaddingEnd(),
+ child.getLayoutParams().width),
+ exactHeightSpec);
+ }
+ }
+ mMatchParentViews.clear();
setMeasuredDimension(getMeasuredWidth(), height);
}
}
diff --git a/core/java/com/android/internal/widget/ResolverDrawerLayout.java b/core/java/com/android/internal/widget/ResolverDrawerLayout.java
index b117e40..c83cab7 100644
--- a/core/java/com/android/internal/widget/ResolverDrawerLayout.java
+++ b/core/java/com/android/internal/widget/ResolverDrawerLayout.java
@@ -121,7 +121,8 @@
private final Rect mTempRect = new Rect();
- private AbsListView mNestedScrollingChild;
+ private AbsListView mNestedListChild;
+ private RecyclerView mNestedRecyclerChild;
private final ViewTreeObserver.OnTouchModeChangeListener mTouchModeChangeListener =
new ViewTreeObserver.OnTouchModeChangeListener() {
@@ -347,11 +348,20 @@
return mIsDragging || mOpenOnClick;
}
- private boolean isNestedChildScrolled() {
- return mNestedScrollingChild != null
- && mNestedScrollingChild.getChildCount() > 0
- && (mNestedScrollingChild.getFirstVisiblePosition() > 0
- || mNestedScrollingChild.getChildAt(0).getTop() < 0);
+ private boolean isNestedListChildScrolled() {
+ return mNestedListChild != null
+ && mNestedListChild.getChildCount() > 0
+ && (mNestedListChild.getFirstVisiblePosition() > 0
+ || mNestedListChild.getChildAt(0).getTop() < 0);
+ }
+
+ private boolean isNestedRecyclerChildScrolled() {
+ if (mNestedRecyclerChild != null && mNestedRecyclerChild.getChildCount() > 0) {
+ final RecyclerView.ViewHolder vh =
+ mNestedRecyclerChild.findViewHolderForAdapterPosition(0);
+ return vh == null || vh.itemView.getTop() < 0;
+ }
+ return false;
}
@Override
@@ -396,8 +406,10 @@
}
if (mIsDragging) {
final float dy = y - mLastTouchY;
- if (dy > 0 && isNestedChildScrolled()) {
- mNestedScrollingChild.smoothScrollBy((int) -dy, 0);
+ if (dy > 0 && isNestedListChildScrolled()) {
+ mNestedListChild.smoothScrollBy((int) -dy, 0);
+ } else if (dy > 0 && isNestedRecyclerChildScrolled()) {
+ mNestedRecyclerChild.scrollBy(0, (int) -dy);
} else {
performDrag(dy);
}
@@ -452,8 +464,10 @@
smoothScrollTo(mCollapsibleHeight + mUncollapsibleHeight, yvel);
mDismissOnScrollerFinished = true;
} else {
- if (isNestedChildScrolled()) {
- mNestedScrollingChild.smoothScrollToPosition(0);
+ if (isNestedListChildScrolled()) {
+ mNestedListChild.smoothScrollToPosition(0);
+ } else if (isNestedRecyclerChildScrolled()) {
+ mNestedRecyclerChild.smoothScrollToPosition(0);
}
smoothScrollTo(yvel < 0 ? 0 : mCollapsibleHeight, yvel);
}
@@ -729,8 +743,11 @@
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
if ((nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0) {
- if (child instanceof AbsListView) {
- mNestedScrollingChild = (AbsListView) child;
+ if (target instanceof AbsListView) {
+ mNestedListChild = (AbsListView) target;
+ }
+ if (target instanceof RecyclerView) {
+ mNestedRecyclerChild = (RecyclerView) target;
}
return true;
}
diff --git a/core/java/com/android/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java
index 3378c07..d40924b 100644
--- a/core/java/com/android/server/SystemConfig.java
+++ b/core/java/com/android/server/SystemConfig.java
@@ -82,6 +82,9 @@
// property for runtime configuration differentiation
private static final String SKU_PROPERTY = "ro.boot.product.hardware.sku";
+ // property for runtime configuration differentiation in vendor
+ private static final String VENDOR_SKU_PROPERTY = "ro.boot.product.vendor.sku";
+
// Group-ids that are given to all packages as read from etc/permissions/*.xml.
int[] mGlobalGids;
@@ -468,6 +471,17 @@
readPermissions(Environment.buildPath(
Environment.getVendorDirectory(), "etc", "permissions"), vendorPermissionFlag);
+ String vendorSkuProperty = SystemProperties.get(VENDOR_SKU_PROPERTY, "");
+ if (!vendorSkuProperty.isEmpty()) {
+ String vendorSkuDir = "sku_" + vendorSkuProperty;
+ readPermissions(Environment.buildPath(
+ Environment.getVendorDirectory(), "etc", "sysconfig", vendorSkuDir),
+ vendorPermissionFlag);
+ readPermissions(Environment.buildPath(
+ Environment.getVendorDirectory(), "etc", "permissions", vendorSkuDir),
+ vendorPermissionFlag);
+ }
+
// Allow ODM to customize system configs as much as Vendor, because /odm is another
// vendor partition other than /vendor.
int odmPermissionFlag = vendorPermissionFlag;
diff --git a/core/jni/android_os_Debug.cpp b/core/jni/android_os_Debug.cpp
index 0d0dc3e..f7c6dbd 100644
--- a/core/jni/android_os_Debug.cpp
+++ b/core/jni/android_os_Debug.cpp
@@ -853,8 +853,11 @@
} cfg_state = CONFIG_UNKNOWN;
if (cfg_state == CONFIG_UNKNOWN) {
- const std::map<std::string, std::string> configs =
- vintf::VintfObject::GetInstance()->getRuntimeInfo()->kernelConfigs();
+ auto runtime_info = vintf::VintfObject::GetInstance()
+ ->getRuntimeInfo(false /* skip cache */,
+ vintf::RuntimeInfo::FetchFlag::CONFIG_GZ);
+ CHECK(runtime_info != nullptr) << "Kernel configs cannot be fetched. b/151092221";
+ const std::map<std::string, std::string>& configs = runtime_info->kernelConfigs();
std::map<std::string, std::string>::const_iterator it = configs.find("CONFIG_VMAP_STACK");
cfg_state = (it != configs.end() && it->second == "y") ? CONFIG_SET : CONFIG_UNSET;
}
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index 4e139a3..ea3c0fa 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -121,19 +121,19 @@
static pid_t gSystemServerPid = 0;
static constexpr const char* kPropFuse = "persist.sys.fuse";
-static constexpr const char* kZygoteClassName = "com/android/internal/os/Zygote";
-
+static const char kZygoteClassName[] = "com/android/internal/os/Zygote";
static jclass gZygoteClass;
static jmethodID gCallPostForkSystemServerHooks;
static jmethodID gCallPostForkChildHooks;
-static constexpr const char* kZygoteInitClassName = "com/android/internal/os/ZygoteInit";
-static jclass gZygoteInitClass;
-static jmethodID gCreateSystemServerClassLoader;
-
static bool gIsSecurityEnforced = true;
/**
+ * True if the app process is running in its mount namespace.
+ */
+static bool gInAppMountNamespace = false;
+
+/**
* The maximum number of characters (not including a null terminator) that a
* process name may contain.
*/
@@ -351,10 +351,14 @@
// Must match values in com.android.internal.os.Zygote.
enum RuntimeFlags : uint32_t {
- DEBUG_ENABLE_JDWP = 1,
- PROFILE_FROM_SHELL = 1 << 15,
- MEMORY_TAG_LEVEL_MASK = (1 << 19) | (1 << 20),
- MEMORY_TAG_LEVEL_TBI = 1 << 19,
+ DEBUG_ENABLE_JDWP = 1,
+ PROFILE_FROM_SHELL = 1 << 15,
+ MEMORY_TAG_LEVEL_MASK = (1 << 19) | (1 << 20),
+ MEMORY_TAG_LEVEL_TBI = 1 << 19,
+ GWP_ASAN_LEVEL_MASK = (1 << 21) | (1 << 22),
+ GWP_ASAN_LEVEL_NEVER = 0 << 21,
+ GWP_ASAN_LEVEL_LOTTERY = 1 << 21,
+ GWP_ASAN_LEVEL_ALWAYS = 2 << 21,
};
enum UnsolicitedZygoteMessageTypes : uint32_t {
@@ -548,6 +552,17 @@
}
}
+static void ensureInAppMountNamespace(fail_fn_t fail_fn) {
+ if (gInAppMountNamespace) {
+ // In app mount namespace already
+ return;
+ }
+ if (unshare(CLONE_NEWNS) == -1) {
+ fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
+ }
+ gInAppMountNamespace = true;
+}
+
// Sets the resource limits via setrlimit(2) for the values in the
// two-dimensional array of integers that's passed in. The second dimension
// contains a tuple of length 3: (resource, rlim_cur, rlim_max). nullptr is
@@ -811,9 +826,7 @@
}
// Create a second private mount namespace for our process
- if (unshare(CLONE_NEWNS) == -1) {
- fail_fn(CREATE_ERROR("Failed to unshare(): %s", strerror(errno)));
- }
+ ensureInAppMountNamespace(fail_fn);
// Handle force_mount_namespace with MOUNT_EXTERNAL_NONE.
if (mount_mode == MOUNT_EXTERNAL_NONE) {
@@ -1319,6 +1332,7 @@
if ((size % 3) != 0) {
fail_fn(CREATE_ERROR("Wrong pkg_inode_list size %d", size));
}
+ ensureInAppMountNamespace(fail_fn);
// Mount tmpfs on all possible data directories, so app no longer see the original apps data.
char internalCePath[PATH_MAX];
@@ -1553,23 +1567,6 @@
auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
const userid_t user_id = multiuser_get_user_id(uid);
- // If FUSE is not ready for this user, skip it
- // TODO(148772775): Pass primary volume name from zygote argument to here
- std::string tmp = GetProperty("vold.fuse_running_users", "");
- std::istringstream fuse_running_users(tmp);
- bool user_found = false;
- std::string s;
- std::string user_id_str = std::to_string(user_id);
- while (!user_found && std::getline(fuse_running_users, s, ',')) {
- if (user_id_str == s) {
- user_found = true;
- }
- }
- if (!user_found) {
- ALOGI("User %d is not running fuse yet, fuse_running_users=%s", user_id, tmp.c_str());
- return;
- }
-
// Fuse is ready, so we can start using fuse path.
int size = (pkg_data_info_list != nullptr) ? env->GetArrayLength(pkg_data_info_list) : 0;
@@ -1597,7 +1594,7 @@
jstring managed_nice_name, bool is_system_server,
bool is_child_zygote, jstring managed_instruction_set,
jstring managed_app_data_dir, bool is_top_app,
- jobjectArray pkg_data_info_list) {
+ jobjectArray pkg_data_info_list, bool mount_storage_dirs) {
const char* process_name = is_system_server ? "system_server" : "zygote";
auto fail_fn = std::bind(ZygoteFailure, env, process_name, managed_nice_name, _1);
auto extract_fn = std::bind(ExtractJString, env, process_name, managed_nice_name, _1);
@@ -1636,10 +1633,7 @@
isolateAppData(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
isolateJitProfile(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
}
-
- if ((mount_external != MOUNT_EXTERNAL_INSTALLER) &&
- GetBoolProperty(kPropFuse, false) &&
- GetBoolProperty(ANDROID_VOLD_APP_DATA_ISOLATION_ENABLED_PROPERTY, false)) {
+ if ((mount_external != MOUNT_EXTERNAL_INSTALLER) && mount_storage_dirs) {
BindMountStorageDirs(env, pkg_data_info_list, uid, process_name, managed_nice_name, fail_fn);
}
@@ -1726,6 +1720,18 @@
}
android_mallopt(M_SET_HEAP_TAGGING_LEVEL, &heap_tagging_level, sizeof(heap_tagging_level));
+ bool forceEnableGwpAsan = false;
+ switch (runtime_flags & RuntimeFlags::GWP_ASAN_LEVEL_MASK) {
+ default:
+ case RuntimeFlags::GWP_ASAN_LEVEL_NEVER:
+ break;
+ case RuntimeFlags::GWP_ASAN_LEVEL_ALWAYS:
+ forceEnableGwpAsan = true;
+ [[fallthrough]];
+ case RuntimeFlags::GWP_ASAN_LEVEL_LOTTERY:
+ android_mallopt(M_INITIALIZE_GWP_ASAN, &forceEnableGwpAsan, sizeof(forceEnableGwpAsan));
+ }
+
if (NeedsNoRandomizeWorkaround()) {
// Work around ARM kernel ASLR lossage (http://b/5817320).
int old_personality = personality(0xffffffff);
@@ -1765,15 +1771,6 @@
fail_fn("Error calling post fork system server hooks.");
}
- // Prefetch the classloader for the system server. This is done early to
- // allow a tie-down of the proper system server selinux domain.
- env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
- if (env->ExceptionCheck()) {
- // Be robust here. The Java code will attempt to create the classloader
- // at a later point (but may not have rights to use AoT artifacts).
- env->ExceptionClear();
- }
-
// TODO(oth): Remove hardcoded label here (b/117874058).
static const char* kSystemServerLabel = "u:r:system_server:s0";
if (selinux_android_setcon(kSystemServerLabel) != 0) {
@@ -2006,7 +2003,7 @@
jint mount_external, jstring se_info, jstring nice_name,
jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
- jobjectArray pkg_data_info_list) {
+ jobjectArray pkg_data_info_list, jboolean mount_storage_dirs) {
jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
if (UNLIKELY(managed_fds_to_close == nullptr)) {
@@ -2043,7 +2040,8 @@
capabilities, capabilities,
mount_external, se_info, nice_name, false,
is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
- is_top_app == JNI_TRUE, pkg_data_info_list);
+ is_top_app == JNI_TRUE, pkg_data_info_list,
+ mount_storage_dirs == JNI_TRUE);
}
return pid;
}
@@ -2078,7 +2076,7 @@
permitted_capabilities, effective_capabilities,
MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
false, nullptr, nullptr, /* is_top_app= */ false,
- /* pkg_data_info_list */ nullptr);
+ /* pkg_data_info_list */ nullptr, false);
} else if (pid > 0) {
// The zygote process checks whether the child process has died or not.
ALOGI("System server process %d has been created", pid);
@@ -2208,14 +2206,15 @@
jint runtime_flags, jobjectArray rlimits,
jint mount_external, jstring se_info, jstring nice_name,
jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app,
- jobjectArray pkg_data_info_list) {
+ jobjectArray pkg_data_info_list, jboolean mount_storage_dirs) {
jlong capabilities = CalculateCapabilities(env, uid, gid, gids, is_child_zygote);
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
capabilities, capabilities,
mount_external, se_info, nice_name, false,
is_child_zygote == JNI_TRUE, instruction_set, app_data_dir,
- is_top_app == JNI_TRUE, pkg_data_info_list);
+ is_top_app == JNI_TRUE, pkg_data_info_list,
+ mount_storage_dirs == JNI_TRUE);
}
/**
@@ -2409,7 +2408,7 @@
static const JNINativeMethod gMethods[] = {
{"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/"
- "String;Z[Ljava/lang/String;)I",
+ "String;Z[Ljava/lang/String;Z)I",
(void*)com_android_internal_os_Zygote_nativeForkAndSpecialize},
{"nativeForkSystemServer", "(II[II[[IJJ)I",
(void*)com_android_internal_os_Zygote_nativeForkSystemServer},
@@ -2422,7 +2421,7 @@
{"nativeForkUsap", "(II[IZ)I", (void*)com_android_internal_os_Zygote_nativeForkUsap},
{"nativeSpecializeAppProcess",
"(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/"
- "String;Z[Ljava/lang/String;)V",
+ "String;Z[Ljava/lang/String;Z)V",
(void*)com_android_internal_os_Zygote_nativeSpecializeAppProcess},
{"nativeInitNativeState", "(Z)V",
(void*)com_android_internal_os_Zygote_nativeInitNativeState},
@@ -2451,13 +2450,6 @@
gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks",
"(IZZLjava/lang/String;)V");
- gZygoteInitClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteInitClassName));
- gCreateSystemServerClassLoader = GetStaticMethodIDOrDie(env, gZygoteInitClass,
- "createSystemServerClassLoader",
- "()V");
-
- RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
-
- return JNI_OK;
+ return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods));
}
} // namespace android
diff --git a/core/proto/android/app/enums.proto b/core/proto/android/app/enums.proto
index 9abe923..42437d5 100644
--- a/core/proto/android/app/enums.proto
+++ b/core/proto/android/app/enums.proto
@@ -104,3 +104,108 @@
PROCESS_STATE_NONEXISTENT = 1019;
}
+// AppOpsManager.java - operation ids for logging
+enum AppOpEnum {
+ APP_OP_NONE = -1;
+ APP_OP_COARSE_LOCATION = 0;
+ APP_OP_FINE_LOCATION = 1;
+ APP_OP_GPS = 2;
+ APP_OP_VIBRATE = 3;
+ APP_OP_READ_CONTACTS = 4;
+ APP_OP_WRITE_CONTACTS = 5;
+ APP_OP_READ_CALL_LOG = 6;
+ APP_OP_WRITE_CALL_LOG = 7;
+ APP_OP_READ_CALENDAR = 8;
+ APP_OP_WRITE_CALENDAR = 9;
+ APP_OP_WIFI_SCAN = 10;
+ APP_OP_POST_NOTIFICATION = 11;
+ APP_OP_NEIGHBORING_CELLS = 12;
+ APP_OP_CALL_PHONE = 13;
+ APP_OP_READ_SMS = 14;
+ APP_OP_WRITE_SMS = 15;
+ APP_OP_RECEIVE_SMS = 16;
+ APP_OP_RECEIVE_EMERGENCY_SMS = 17;
+ APP_OP_RECEIVE_MMS = 18;
+ APP_OP_RECEIVE_WAP_PUSH = 19;
+ APP_OP_SEND_SMS = 20;
+ APP_OP_READ_ICC_SMS = 21;
+ APP_OP_WRITE_ICC_SMS = 22;
+ APP_OP_WRITE_SETTINGS = 23;
+ APP_OP_SYSTEM_ALERT_WINDOW = 24;
+ APP_OP_ACCESS_NOTIFICATIONS = 25;
+ APP_OP_CAMERA = 26;
+ APP_OP_RECORD_AUDIO = 27;
+ APP_OP_PLAY_AUDIO = 28;
+ APP_OP_READ_CLIPBOARD = 29;
+ APP_OP_WRITE_CLIPBOARD = 30;
+ APP_OP_TAKE_MEDIA_BUTTONS = 31;
+ APP_OP_TAKE_AUDIO_FOCUS = 32;
+ APP_OP_AUDIO_MASTER_VOLUME = 33;
+ APP_OP_AUDIO_VOICE_VOLUME = 34;
+ APP_OP_AUDIO_RING_VOLUME = 35;
+ APP_OP_AUDIO_MEDIA_VOLUME = 36;
+ APP_OP_AUDIO_ALARM_VOLUME = 37;
+ APP_OP_AUDIO_NOTIFICATION_VOLUME = 38;
+ APP_OP_AUDIO_BLUETOOTH_VOLUME = 39;
+ APP_OP_WAKE_LOCK = 40;
+ APP_OP_MONITOR_LOCATION = 41;
+ APP_OP_MONITOR_HIGH_POWER_LOCATION = 42;
+ APP_OP_GET_USAGE_STATS = 43;
+ APP_OP_MUTE_MICROPHONE = 44;
+ APP_OP_TOAST_WINDOW = 45;
+ APP_OP_PROJECT_MEDIA = 46;
+ APP_OP_ACTIVATE_VPN = 47;
+ APP_OP_WRITE_WALLPAPER = 48;
+ APP_OP_ASSIST_STRUCTURE = 49;
+ APP_OP_ASSIST_SCREENSHOT = 50;
+ APP_OP_READ_PHONE_STATE = 51;
+ APP_OP_ADD_VOICEMAIL = 52;
+ APP_OP_USE_SIP = 53;
+ APP_OP_PROCESS_OUTGOING_CALLS = 54;
+ APP_OP_USE_FINGERPRINT = 55;
+ APP_OP_BODY_SENSORS = 56;
+ APP_OP_READ_CELL_BROADCASTS = 57;
+ APP_OP_MOCK_LOCATION = 58;
+ APP_OP_READ_EXTERNAL_STORAGE = 59;
+ APP_OP_WRITE_EXTERNAL_STORAGE = 60;
+ APP_OP_TURN_SCREEN_ON = 61;
+ APP_OP_GET_ACCOUNTS = 62;
+ APP_OP_RUN_IN_BACKGROUND = 63;
+ APP_OP_AUDIO_ACCESSIBILITY_VOLUME = 64;
+ APP_OP_READ_PHONE_NUMBERS = 65;
+ APP_OP_REQUEST_INSTALL_PACKAGES = 66;
+ APP_OP_PICTURE_IN_PICTURE = 67;
+ APP_OP_INSTANT_APP_START_FOREGROUND = 68;
+ APP_OP_ANSWER_PHONE_CALLS = 69;
+ APP_OP_RUN_ANY_IN_BACKGROUND = 70;
+ APP_OP_CHANGE_WIFI_STATE = 71;
+ APP_OP_REQUEST_DELETE_PACKAGES = 72;
+ APP_OP_BIND_ACCESSIBILITY_SERVICE = 73;
+ APP_OP_ACCEPT_HANDOVER = 74;
+ APP_OP_MANAGE_IPSEC_TUNNELS = 75;
+ APP_OP_START_FOREGROUND = 76;
+ APP_OP_BLUETOOTH_SCAN = 77;
+ APP_OP_USE_BIOMETRIC = 78;
+ APP_OP_ACTIVITY_RECOGNITION = 79;
+ APP_OP_SMS_FINANCIAL_TRANSACTIONS = 80;
+ APP_OP_READ_MEDIA_AUDIO = 81;
+ APP_OP_WRITE_MEDIA_AUDIO = 82;
+ APP_OP_READ_MEDIA_VIDEO = 83;
+ APP_OP_WRITE_MEDIA_VIDEO = 84;
+ APP_OP_READ_MEDIA_IMAGES = 85;
+ APP_OP_WRITE_MEDIA_IMAGES = 86;
+ APP_OP_LEGACY_STORAGE = 87;
+ APP_OP_ACCESS_ACCESSIBILITY = 88;
+ APP_OP_READ_DEVICE_IDENTIFIERS = 89;
+ APP_OP_ACCESS_MEDIA_LOCATION = 90;
+ APP_OP_QUERY_ALL_PACKAGES = 91;
+ APP_OP_MANAGE_EXTERNAL_STORAGE = 92;
+ APP_OP_INTERACT_ACROSS_PROFILES = 93;
+ APP_OP_ACTIVATE_PLATFORM_VPN = 94;
+ APP_OP_LOADER_USAGE_STATS = 95;
+ APP_OP_ACCESS_CALL_AUDIO = 96;
+ APP_OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED = 97;
+ APP_OP_AUTO_REVOKE_MANAGED_BY_INSTALLER = 98;
+}
+
+
diff --git a/core/proto/android/app/settings_enums.proto b/core/proto/android/app/settings_enums.proto
index 030483b..ef6eb38 100644
--- a/core/proto/android/app/settings_enums.proto
+++ b/core/proto/android/app/settings_enums.proto
@@ -724,6 +724,16 @@
// CATEGORY: SETTINGS
// OS: R
ACTION_ADB_WIRELESS_OFF = 1735;
+
+ // ACTION: Change Wi-Fi hotspot name
+ // CATEGORY: SETTINGS
+ // OS: R
+ ACTION_SETTINGS_CHANGE_WIFI_HOTSPOT_NAME = 1736;
+
+ // ACTION: Change Wi-Fi hotspot password
+ // CATEGORY: SETTINGS
+ // OS: R
+ ACTION_SETTINGS_CHANGE_WIFI_HOTSPOT_PASSWORD = 1737;
}
/**
diff --git a/core/proto/android/bluetooth/enums.proto b/core/proto/android/bluetooth/enums.proto
index b4f3d1e..22f2498 100644
--- a/core/proto/android/bluetooth/enums.proto
+++ b/core/proto/android/bluetooth/enums.proto
@@ -40,6 +40,7 @@
ENABLE_DISABLE_REASON_CRASH = 7;
ENABLE_DISABLE_REASON_USER_SWITCH = 8;
ENABLE_DISABLE_REASON_RESTORE_USER_SETTING = 9;
+ ENABLE_DISABLE_REASON_FACTORY_RESET = 10;
}
enum DirectionEnum {
diff --git a/core/proto/android/content/package_item_info.proto b/core/proto/android/content/package_item_info.proto
index 4a7d043..e8ae1b3 100644
--- a/core/proto/android/content/package_item_info.proto
+++ b/core/proto/android/content/package_item_info.proto
@@ -109,6 +109,7 @@
}
optional int32 network_security_config_res = 17;
optional int32 category = 18;
+ optional bool enable_gwp_asan = 19;
}
optional Detail detail = 17;
}
diff --git a/core/proto/android/providers/settings/config.proto b/core/proto/android/providers/settings/config.proto
index cc24196..b0a70ef 100644
--- a/core/proto/android/providers/settings/config.proto
+++ b/core/proto/android/providers/settings/config.proto
@@ -47,6 +47,7 @@
repeated SettingProto systemui_settings = 20;
repeated SettingProto telephony_settings = 21;
repeated SettingProto textclassifier_settings = 22;
+ repeated SettingProto blobstore_settings = 23;
message NamespaceProto {
optional string namespace = 1;
diff --git a/core/proto/android/server/windowmanagerservice.proto b/core/proto/android/server/windowmanagerservice.proto
index e8a0b46..608925578 100644
--- a/core/proto/android/server/windowmanagerservice.proto
+++ b/core/proto/android/server/windowmanagerservice.proto
@@ -53,10 +53,10 @@
option (.android.msg_privacy).dest = DEST_AUTOMATIC;
optional WindowContainerProto window_container = 1;
- repeated DisplayContentProto displays = 2;
+ repeated DisplayContentProto displays = 2 [deprecated=true];
reserved 3; // IdentifierProto windows
/* window references in top down z order */
- repeated WindowStateProto windows = 4;
+ repeated WindowStateProto windows = 4 [deprecated=true];
optional KeyguardControllerProto keyguard_controller = 5;
// Whether or not the home activity is the recents activity. This is needed for the CTS tests to
// know what activity types to check for when invoking splitscreen multi-window.
@@ -192,7 +192,8 @@
optional bool single_task_instance = 22;
optional int32 focused_root_task_id = 23;
optional .com.android.server.wm.IdentifierProto resumed_activity = 24;
- repeated TaskProto tasks = 25;
+ repeated TaskProto tasks = 25 [deprecated=true];
+ optional bool display_ready = 26;
}
/* represents DisplayArea object */
@@ -201,7 +202,7 @@
optional WindowContainerProto window_container = 1;
optional string name = 2 [ (.android.privacy).dest = DEST_EXPLICIT ];
- repeated DisplayAreaChildProto children = 3;
+ repeated DisplayAreaChildProto children = 3 [deprecated=true];
}
/* represents a generic child of a DisplayArea */
@@ -254,8 +255,8 @@
optional int32 surface_width = 8;
optional int32 surface_height = 9;
- repeated TaskProto tasks = 10;
- repeated ActivityRecordProto activities = 11;
+ repeated TaskProto tasks = 10 [deprecated=true];
+ repeated ActivityRecordProto activities = 11 [deprecated=true];
optional .com.android.server.wm.IdentifierProto resumed_activity = 12;
optional string real_activity = 13;
@@ -321,7 +322,7 @@
optional WindowContainerProto window_container = 1;
optional int32 hash_code = 2;
- repeated WindowStateProto windows = 3;
+ repeated WindowStateProto windows = 3 [deprecated=true];
optional bool waiting_to_show = 5;
optional bool paused = 6;
}
@@ -346,7 +347,7 @@
optional .android.graphics.RectProto surface_insets = 12;
optional WindowStateAnimatorProto animator = 13;
optional bool animating_exit = 14;
- repeated WindowStateProto child_windows = 15;
+ repeated WindowStateProto child_windows = 15 [deprecated=true];
optional .android.graphics.RectProto surface_position = 16;
optional int32 requested_width = 18;
optional int32 requested_height = 19;
@@ -426,6 +427,32 @@
optional int32 orientation = 2;
optional bool visible = 3;
optional SurfaceAnimatorProto surface_animator = 4;
+ repeated WindowContainerChildProto children = 5;
+}
+
+/* represents a generic child of a WindowContainer */
+message WindowContainerChildProto {
+ option (.android.msg_privacy).dest = DEST_AUTOMATIC;
+
+ /* A window container can have multiple children of different types stored as
+ * a WindowContainerChildProto but each instance of WindowContainerChildProto
+ * can only contain a single type.
+ */
+ /* We do not know the derived typ and the class is dumped
+ * as a WindowContainer */
+ optional WindowContainerProto window_container = 2;
+ /* represents a DisplayContent child */
+ optional DisplayContentProto display_content = 3;
+ /* represents a DisplayArea child */
+ optional DisplayAreaProto display_area = 4;
+ /* represents a Task child */
+ optional TaskProto task = 5;
+ /* represents an ActivityRecord child */
+ optional ActivityRecordProto activity = 6;
+ /* represents a WindowToken child */
+ optional WindowTokenProto window_token = 7;
+ /* represents a WindowState child */
+ optional WindowStateProto window = 8;
}
/* represents ConfigurationContainer */
diff --git a/core/proto/android/stats/devicepolicy/device_policy_enums.proto b/core/proto/android/stats/devicepolicy/device_policy_enums.proto
index 3d8108d..684a292 100644
--- a/core/proto/android/stats/devicepolicy/device_policy_enums.proto
+++ b/core/proto/android/stats/devicepolicy/device_policy_enums.proto
@@ -153,7 +153,7 @@
CROSS_PROFILE_APPS_START_ACTIVITY_AS_USER = 126;
SET_AUTO_TIME = 127;
SET_AUTO_TIME_ZONE = 128;
- SET_PACKAGES_PROTECTED = 129;
+ SET_USER_CONTROL_DISABLED_PACKAGES = 129;
SET_FACTORY_RESET_PROTECTION = 130;
SET_COMMON_CRITERIA_MODE = 131;
ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS = 132;
diff --git a/core/proto/android/telephony/enums.proto b/core/proto/android/telephony/enums.proto
index 4777169..f14e3ed 100644
--- a/core/proto/android/telephony/enums.proto
+++ b/core/proto/android/telephony/enums.proto
@@ -20,6 +20,43 @@
option java_outer_classname = "TelephonyProtoEnums";
option java_multiple_files = true;
+enum CallBearerEnum {
+ /** Call bearer is unknown or invalid */
+ CALL_BEARER_UNKNOWN = 0;
+
+ /** Call bearer is legacy CS */
+ CALL_BEARER_CS = 1;
+
+ /** Call bearer is IMS */
+ CALL_BEARER_IMS = 2;
+}
+
+enum CallDirectionEnum {
+ /** Call direction: unknown or invalid */
+ CALL_DIRECTION_UNKNOWN = 0;
+
+ /** Call direction: mobile originated (outgoing for this device) */
+ CALL_DIRECTION_MO = 1;
+
+ /** Call direction: mobile terminated (incoming for this device) */
+ CALL_DIRECTION_MT = 2;
+}
+
+// Call setup duration buckets.
+// See com.android.internal.telephony.metrics.VoiceCallSessionStats for definition.
+enum CallSetupDurationEnum {
+ CALL_SETUP_DURATION_UNKNOWN = 0;
+ CALL_SETUP_DURATION_EXTREMELY_FAST = 1;
+ CALL_SETUP_DURATION_ULTRA_FAST = 2;
+ CALL_SETUP_DURATION_VERY_FAST = 3;
+ CALL_SETUP_DURATION_FAST = 4;
+ CALL_SETUP_DURATION_NORMAL = 5;
+ CALL_SETUP_DURATION_SLOW = 6;
+ CALL_SETUP_DURATION_VERY_SLOW = 7;
+ CALL_SETUP_DURATION_ULTRA_SLOW = 8;
+ CALL_SETUP_DURATION_EXTREMELY_SLOW = 9;
+}
+
// Data conn. power states, primarily used by android/telephony/DataConnectionRealTimeInfo.java.
enum DataConnectionPowerStateEnum {
DATA_CONNECTION_POWER_STATE_LOW = 1;
@@ -63,7 +100,6 @@
SIGNAL_STRENGTH_GREAT = 4;
}
-
enum ServiceStateEnum {
/**
* Normal operation condition, the phone is registered
diff --git a/core/proto/android/view/remote_animation_target.proto b/core/proto/android/view/remote_animation_target.proto
index 24d2785..150493d 100644
--- a/core/proto/android/view/remote_animation_target.proto
+++ b/core/proto/android/view/remote_animation_target.proto
@@ -44,4 +44,6 @@
optional .android.app.WindowConfigurationProto window_configuration = 10;
optional .android.view.SurfaceControlProto start_leash = 11;
optional .android.graphics.RectProto start_bounds = 12;
+ optional .android.graphics.RectProto local_bounds = 13;
+ optional .android.graphics.RectProto screen_space_bounds = 14;
}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 8851170..7a3ec95 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1187,6 +1187,16 @@
android:description="@string/permdesc_callCompanionApp"
android:protectionLevel="normal" />
+ <!-- Exempt this uid from restrictions to background audio recoding
+ <p>Protection level: signature|privileged
+ @hide
+ @SystemApi
+ -->
+ <permission android:name="android.permission.EXEMPT_FROM_AUDIO_RECORD_RESTRICTIONS"
+ android:label="@string/permlab_exemptFromAudioRecordRestrictions"
+ android:description="@string/permdesc_exemptFromAudioRecordRestrictions"
+ android:protectionLevel="signature|privileged" />
+
<!-- Allows a calling app to continue a call which was started in another app. An example is a
video calling app that wants to continue a voice call on the user's mobile network.<p>
When the handover of a call from one app to another takes place, there are two devices
@@ -1305,7 +1315,7 @@
android:description="@string/permdesc_camera"
android:protectionLevel="dangerous|instant" />
- <!-- @SystemApi Required in addition to android.permission.CAMERA to be able to access
+ <!-- @SystemApi Required in addition to android.permission.CAMERA to be able to access
system only camera devices.
<p>Protection level: system|signature
@hide -->
@@ -1315,6 +1325,15 @@
android:description="@string/permdesc_systemCamera"
android:protectionLevel="system|signature" />
+ <!-- Allows receiving the camera service notifications when a camera is opened
+ (by a certain application package) or closed.
+ @hide -->
+ <permission android:name="android.permission.CAMERA_OPEN_CLOSE_LISTENER"
+ android:permissionGroup="android.permission-group.UNDEFINED"
+ android:label="@string/permlab_cameraOpenCloseListener"
+ android:description="@string/permdesc_cameraOpenCloseListener"
+ android:protectionLevel="signature" />
+
<!-- ====================================================================== -->
<!-- Permissions for accessing the device sensors -->
<!-- ====================================================================== -->
@@ -3726,7 +3745,8 @@
<permission android:name="android.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY"
android:protectionLevel="signature|installer" />
- <!-- @hide Allows an application to upgrade runtime permissions. -->
+ <!-- @SystemApi @TestApi Allows an application to upgrade runtime permissions.
+ @hide -->
<permission android:name="android.permission.UPGRADE_RUNTIME_PERMISSIONS"
android:protectionLevel="signature" />
@@ -3736,6 +3756,12 @@
<permission android:name="android.permission.WHITELIST_RESTRICTED_PERMISSIONS"
android:protectionLevel="signature|installer" />
+ <!-- @SystemApi Allows an application to an exempt an app from having its permission be
+ auto-revoked when unused for an extended period of time.
+ @hide -->
+ <permission android:name="android.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS"
+ android:protectionLevel="signature|installer" />
+
<!-- @hide Allows an application to observe permission changes. -->
<permission android:name="android.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS"
android:protectionLevel="signature|privileged" />
@@ -4983,15 +5009,15 @@
<permission android:name="android.permission.ACCESS_LOCUS_ID_USAGE_STATS"
android:protectionLevel="signature|appPredictor" />
- <!-- Feature Id for Country Detector. -->
- <feature android:featureId="CountryDetector" android:label="@string/country_detector"/>
- <!-- Feature Id for Location service. -->
- <feature android:featureId="LocationService" android:label="@string/location_service"/>
- <!-- Feature Id for Sensor Notification service. -->
- <feature android:featureId="SensorNotificationService"
+ <!-- Attribution for Country Detector. -->
+ <attribution android:tag="CountryDetector" android:label="@string/country_detector"/>
+ <!-- Attribution for Location service. -->
+ <attribution android:tag="LocationService" android:label="@string/location_service"/>
+ <!-- Attribution for Sensor Notification service. -->
+ <attribution android:tag="SensorNotificationService"
android:label="@string/sensor_notification_service"/>
<!-- Feature Id for Twilight service. -->
- <feature android:featureId="TwilightService" android:label="@string/twilight_service"/>
+ <attribution android:tag="TwilightService" android:label="@string/twilight_service"/>
<application android:process="system"
android:persistent="true"
@@ -5180,6 +5206,7 @@
<activity android:name="com.android.internal.app.BlockedAppActivity"
android:theme="@style/Theme.Dialog.Confirmation"
android:excludeFromRecents="true"
+ android:lockTaskMode="always"
android:process=":ui">
</activity>
diff --git a/core/res/res/drawable/conversation_badge_background.xml b/core/res/res/drawable/conversation_badge_background.xml
new file mode 100644
index 0000000..0dd0dcd
--- /dev/null
+++ b/core/res/res/drawable/conversation_badge_background.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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
+ -->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="oval">
+
+ <solid
+ android:color="#ffffff"/>
+
+ <size
+ android:width="26dp"
+ android:height="26dp"/>
+</shape>
+
diff --git a/core/res/res/drawable/ic_collapse_notification.xml b/core/res/res/drawable/ic_collapse_notification.xml
index 124e99e..ca4f0ed 100644
--- a/core/res/res/drawable/ic_collapse_notification.xml
+++ b/core/res/res/drawable/ic_collapse_notification.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
-Copyright (C) 2015 The Android Open Source Project
+Copyright (C) 2020 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.
@@ -15,11 +15,14 @@
limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="14.0dp"
- android:height="14.0dp"
- android:viewportWidth="24.0"
- android:viewportHeight="24.0">
+ android:width="22.0dp"
+ android:height="22.0dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
- android:pathData="M12.0,8.0l-6.0,6.0l1.4,1.4l4.6,-4.6l4.6,4.6L18.0,14.0L12.0,8.0z"/>
-</vector>
+ android:pathData="M18.59,16.41L20.0,15.0l-8.0,-8.0 -8.0,8.0 1.41,1.41L12.0,9.83"/>
+ <path
+ android:pathData="M0 0h24v24H0V0z"
+ android:fillColor="#00000000"/>
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/ic_expand_notification.xml b/core/res/res/drawable/ic_expand_notification.xml
index 847e326..a080ce4 100644
--- a/core/res/res/drawable/ic_expand_notification.xml
+++ b/core/res/res/drawable/ic_expand_notification.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
-Copyright (C) 2015 The Android Open Source Project
+Copyright (C) 2014 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.
@@ -15,11 +15,14 @@
limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="14.0dp"
- android:height="14.0dp"
- android:viewportWidth="24.0"
- android:viewportHeight="24.0">
+ android:width="22.0dp"
+ android:height="22.0dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
- android:pathData="M16.6,8.6L12.0,13.2L7.4,8.6L6.0,10.0l6.0,6.0l6.0,-6.0L16.6,8.6z"/>
-</vector>
+ android:pathData="M5.41,7.59L4.0,9.0l8.0,8.0 8.0,-8.0 -1.41,-1.41L12.0,14.17"/>
+ <path
+ android:pathData="M24 24H0V0h24v24z"
+ android:fillColor="#00000000"/>
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/ic_delete_item.xml b/core/res/res/drawable/ic_pan_tool.xml
similarity index 69%
copy from core/res/res/drawable/ic_delete_item.xml
copy to core/res/res/drawable/ic_pan_tool.xml
index 8a398a4..c1a8549 100644
--- a/core/res/res/drawable/ic_delete_item.xml
+++ b/core/res/res/drawable/ic_pan_tool.xml
@@ -12,7 +12,7 @@
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.
- -->
+-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
@@ -21,6 +21,6 @@
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
- android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z"
+ android:pathData="M23,5.5V20c0,2.2 -1.8,4 -4,4h-7.3c-1.08,0 -2.1,-0.43 -2.85,-1.19L1,14.83c0,0 1.26,-1.23 1.3,-1.25c0.22,-0.19 0.49,-0.29 0.79,-0.29c0.22,0 0.42,0.06 0.6,0.16C3.73,13.46 8,15.91 8,15.91V4c0,-0.83 0.67,-1.5 1.5,-1.5S11,3.17 11,4v7h1V1.5C12,0.67 12.67,0 13.5,0S15,0.67 15,1.5V11h1V2.5C16,1.67 16.67,1 17.5,1S19,1.67 19,2.5V11h1V5.5C20,4.67 20.67,4 21.5,4S23,4.67 23,5.5z"
android:fillColor="#FFFFFF"/>
</vector>
diff --git a/core/res/res/drawable/ic_delete_item.xml b/core/res/res/drawable/ic_visibility.xml
similarity index 77%
rename from core/res/res/drawable/ic_delete_item.xml
rename to core/res/res/drawable/ic_visibility.xml
index 8a398a4..1956241 100644
--- a/core/res/res/drawable/ic_delete_item.xml
+++ b/core/res/res/drawable/ic_visibility.xml
@@ -12,7 +12,7 @@
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.
- -->
+-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
@@ -21,6 +21,6 @@
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
- android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z"
+ android:pathData="M12,4.5C7,4.5 2.73,7.61 1,12c1.73,4.39 6,7.5 11,7.5s9.27,-3.11 11,-7.5c-1.73,-4.39 -6,-7.5 -11,-7.5zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5zM12,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3 -1.34,-3 -3,-3z"
android:fillColor="#FFFFFF"/>
</vector>
diff --git a/core/res/res/layout-car/car_resolver_different_item_header.xml b/core/res/res/layout-car/car_resolver_different_item_header.xml
deleted file mode 100644
index 222ecc6..0000000
--- a/core/res/res/layout-car/car_resolver_different_item_header.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
- * Copyright 2019, 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.
- */
--->
-<TextView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alwaysShow="true"
- android:text="@*android:string/use_a_different_app"
- android:minHeight="56dp"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:gravity="start|center_vertical"
- android:paddingStart="16dp"
- android:paddingEnd="16dp"
- android:paddingTop="8dp"
- android:paddingBottom="8dp"
- android:elevation="8dp"
-/>
\ No newline at end of file
diff --git a/core/res/res/layout-car/car_resolver_list.xml b/core/res/res/layout-car/car_resolver_list.xml
index 15a8645..755cbfe 100644
--- a/core/res/res/layout-car/car_resolver_list.xml
+++ b/core/res/res/layout-car/car_resolver_list.xml
@@ -23,90 +23,142 @@
android:id="@id/contentPanel">
<LinearLayout
- android:id="@+id/button_bar"
- android:visibility="gone"
- style="?attr/buttonBarStyle"
android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_ignoreOffset="true"
- android:layout_alwaysShow="true"
- android:layout_hasNestedScrollIndicator="true"
- android:background="?attr/colorBackgroundFloating"
- android:orientation="horizontal"
- android:paddingTop="8dp"
- android:paddingBottom="8dp"
- android:paddingStart="12dp"
+ android:layout_height="match_parent"
android:weightSum="5"
- android:paddingEnd="12dp"
+ android:layout_alwaysShow="true"
+ android:orientation="vertical"
+ android:background="?attr/colorBackgroundFloating"
android:elevation="8dp">
- <TextView
- android:id="@+id/profile_button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginEnd="8dp"
- android:paddingStart="8dp"
- android:paddingEnd="8dp"
- android:textSize="40sp"
- android:layout_weight="5"
- android:layout_gravity = "left"
+ <LinearLayout
+ android:id="@+id/button_bar"
android:visibility="gone"
- android:textColor="?attr/colorAccent"
- android:singleLine="true"/>
-
- <TextView
- android:id="@+id/title"
- android:layout_width="wrap_content"
+ style="?attr/buttonBarStyle"
+ android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:minHeight="56dp"
- android:layout_gravity = "left"
- android:layout_weight="3"
+ android:layout_ignoreOffset="true"
+ android:layout_alwaysShow="true"
+ android:layout_hasNestedScrollIndicator="true"
+ android:background="?attr/colorBackgroundFloating"
+ android:orientation="horizontal"
android:paddingTop="8dp"
- android:layout_below="@id/profile_button"
- android:paddingBottom="8dp"/>
+ android:paddingStart="12dp"
+ android:weightSum="4"
+ android:paddingEnd="12dp"
+ android:elevation="8dp">
- <Button
- android:id="@+id/button_once"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:enabled="false"
- android:layout_gravity = "right"
- android:text="@string/activity_resolver_use_once"
- android:layout_weight="1"
- android:onClick="onButtonClick"/>
+ <TextView
+ android:id="@+id/profile_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginEnd="8dp"
+ android:paddingStart="8dp"
+ android:paddingEnd="8dp"
+ android:textSize="40sp"
+ android:layout_weight="4"
+ android:layout_gravity="left"
+ android:visibility="gone"
+ android:textColor="?attr/colorAccent"
+ android:singleLine="true"/>
- <Button
- android:id="@+id/button_always"
- android:layout_marginLeft="10dp"
- android:layout_width="wrap_content"
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="left"
+ android:layout_weight="3"
+ android:paddingTop="8dp"
+ android:layout_below="@id/profile_button"
+ android:textAppearance="?android:attr/textAppearanceLarge"
+ android:paddingBottom="8dp"/>
+
+ <Button
+ android:id="@+id/button_once"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:enabled="false"
+ android:layout_gravity="right"
+ style="?attr/buttonBarButtonStyle"
+ android:text="@string/activity_resolver_use_once"
+ android:layout_weight="0.5"
+ android:onClick="onButtonClick"/>
+
+ <Button
+ android:id="@+id/button_always"
+ android:layout_marginLeft="2dp"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:enabled="false"
+ android:layout_gravity="right"
+ style="?attr/buttonBarButtonStyle"
+ android:text="@string/activity_resolver_use_always"
+ android:layout_weight="0.5"
+ android:onClick="onButtonClick"/>
+ </LinearLayout>
+
+ <FrameLayout
+ android:id="@+id/stub"
+ android:visibility="gone"
+ android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:enabled="false"
- android:layout_gravity = "right"
- android:text="@string/activity_resolver_use_always"
- android:layout_weight="1"
- android:onClick="onButtonClick"/>
+ android:background="?attr/colorBackgroundFloating"/>
+
+ <TabHost
+ android:id="@+id/profile_tabhost"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:layout_centerHorizontal="true"
+ android:background="?attr/colorBackgroundFloating">
+ <LinearLayout
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+ <TabWidget
+ android:id="@android:id/tabs"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone">
+ </TabWidget>
+ <View
+ android:id="@+id/resolver_tab_divider"
+ android:visibility="gone"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="?attr/colorBackgroundFloating"
+ android:foreground="?attr/dividerVertical"
+ android:layout_marginBottom="8dp"/>
+ <FrameLayout
+ android:id="@android:id/tabcontent"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+ <com.android.internal.app.ResolverViewPager
+ android:id="@+id/profile_pager"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"/>
+ </FrameLayout>
+ </LinearLayout>
+ </TabHost>
+
+ <View
+ android:layout_alwaysShow="true"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="?attr/colorBackgroundFloating"
+ android:foreground="?attr/dividerVertical"/>
+
+ <TextView android:id="@+id/empty"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:background="?attr/colorBackgroundFloating"
+ android:elevation="8dp"
+ android:layout_alwaysShow="true"
+ android:text="@string/noApplications"
+ android:padding="32dp"
+ android:gravity="center"
+ android:visibility="gone"/>
+
</LinearLayout>
- <ListView
- android:layout_width="match_parent"
- android:layout_height="500dp"
- android:id="@+id/resolver_list"
- android:clipToPadding="false"
- android:scrollbarStyle="outsideOverlay"
- android:background="?attr/colorBackgroundFloating"
- android:elevation="8dp"
- android:nestedScrollingEnabled="true"
- android:scrollIndicators="top|bottom"/>
-
- <TextView android:id="@+id/empty"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="?attr/colorBackgroundFloating"
- android:elevation="8dp"
- android:layout_alwaysShow="true"
- android:text="@string/noApplications"
- android:padding="32dp"
- android:gravity="center"
- android:visibility="gone"/>
-
</com.android.internal.widget.ResolverDrawerLayout>
diff --git a/core/res/res/layout-car/car_resolver_list_with_default.xml b/core/res/res/layout-car/car_resolver_list_with_default.xml
index 2aed00b..5e450b2 100644
--- a/core/res/res/layout-car/car_resolver_list_with_default.xml
+++ b/core/res/res/layout-car/car_resolver_list_with_default.xml
@@ -40,12 +40,12 @@
<ImageView
android:id="@+id/icon"
- android:layout_width="24dp"
- android:layout_height="24dp"
+ android:layout_width="60dp"
+ android:layout_height="60dp"
android:layout_gravity="start|top"
- android:layout_marginStart="16dp"
- android:layout_marginEnd="16dp"
- android:layout_marginTop="20dp"
+ android:layout_marginStart="10dp"
+ android:layout_marginEnd="5dp"
+ android:layout_marginTop="10dp"
android:src="@drawable/resolver_icon_placeholder"
android:scaleType="fitCenter"/>
@@ -55,7 +55,7 @@
android:layout_weight="1"
android:layout_height="?attr/listPreferredItemHeight"
android:layout_marginStart="16dp"
- android:textAppearance="?attr/textAppearanceMedium"
+ android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="start|center_vertical"
android:paddingEnd="16dp"/>
@@ -120,7 +120,7 @@
android:layout_width="wrap_content"
android:layout_gravity="start"
android:maxLines="2"
- style="?attr/buttonBarNegativeButtonStyle"
+ style="?attr/buttonBarButtonStyle"
android:minHeight="@dimen/alert_dialog_button_bar_height"
android:layout_height="wrap_content"
android:enabled="false"
@@ -133,29 +133,64 @@
android:layout_gravity="end"
android:maxLines="2"
android:minHeight="@dimen/alert_dialog_button_bar_height"
- style="?attr/buttonBarPositiveButtonStyle"
+ style="?attr/buttonBarButtonStyle"
android:layout_height="wrap_content"
android:enabled="false"
android:text="@string/activity_resolver_use_always"
android:onClick="onButtonClick"/>
</LinearLayout>
+ <FrameLayout
+ android:id="@+id/stub"
+ android:layout_alwaysShow="true"
+ android:visibility="gone"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:background="?attr/colorBackgroundFloating"/>
+
+ <TabHost
+ android:layout_alwaysShow="true"
+ android:id="@+id/profile_tabhost"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:layout_centerHorizontal="true"
+ android:background="?attr/colorBackgroundFloating">
+ <LinearLayout
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+ <TabWidget
+ android:id="@android:id/tabs"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone">
+ </TabWidget>
+ <View
+ android:id="@+id/resolver_tab_divider"
+ android:visibility="gone"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="?attr/colorBackgroundFloating"
+ android:foreground="?attr/dividerVertical"
+ android:layout_marginBottom="8dp"/>
+ <FrameLayout
+ android:id="@android:id/tabcontent"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+ <com.android.internal.app.ResolverViewPager
+ android:id="@+id/profile_pager"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+ </com.android.internal.app.ResolverViewPager>
+ </FrameLayout>
+ </LinearLayout>
+ </TabHost>
+
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/dividerVertical"/>
-
- <ListView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/resolver_list"
- android:layout_weight="4"
- android:clipToPadding="false"
- android:scrollbarStyle="outsideOverlay"
- android:background="?attr/colorBackgroundFloating"
- android:elevation="8dp"
- android:nestedScrollingEnabled="true"
- android:divider="@null"/>
</LinearLayout>
</com.android.internal.widget.ResolverDrawerLayout>
diff --git a/core/res/res/layout/accessibility_button_chooser_item.xml b/core/res/res/layout/accessibility_button_chooser_item.xml
index c01766b..b7dd892 100644
--- a/core/res/res/layout/accessibility_button_chooser_item.xml
+++ b/core/res/res/layout/accessibility_button_chooser_item.xml
@@ -21,10 +21,17 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
- android:paddingStart="16dp"
- android:paddingEnd="16dp"
- android:paddingTop="12dp"
- android:paddingBottom="12dp">
+ android:padding="16dp">
+
+ <CheckBox
+ android:id="@+id/accessibility_button_target_checkbox"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingStart="16dp"
+ android:background="@null"
+ android:clickable="false"
+ android:focusable="false"
+ android:visibility="gone"/>
<ImageView
android:id="@+id/accessibility_button_target_icon"
@@ -36,31 +43,18 @@
android:id="@+id/accessibility_button_target_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
- android:layout_marginStart="14dp"
+ android:layout_marginStart="16dp"
android:layout_weight="1"
android:textSize="20sp"
android:textColor="?attr/textColorPrimary"
android:fontFamily="sans-serif-medium"/>
- <FrameLayout
- android:id="@+id/accessibility_button_target_item_container"
+ <Switch
+ android:id="@+id/accessibility_button_target_switch_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:minWidth="56dp">
-
- <ImageView
- android:id="@+id/accessibility_button_target_view_item"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"/>
-
- <Switch android:id="@+id/accessibility_button_target_switch_item"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:background="@null"
- android:clickable="false"
- android:focusable="false"/>
- </FrameLayout>
+ android:background="@null"
+ android:clickable="false"
+ android:focusable="false"/>
</LinearLayout>
diff --git a/core/res/res/layout/accessibility_enable_service_encryption_warning.xml b/core/res/res/layout/accessibility_enable_service_encryption_warning.xml
new file mode 100644
index 0000000..4000516
--- /dev/null
+++ b/core/res/res/layout/accessibility_enable_service_encryption_warning.xml
@@ -0,0 +1,175 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2020 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.
+-->
+
+<ScrollView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:textDirection="locale"
+ android:scrollbarStyle="outsideOverlay">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center"
+ android:orientation="vertical">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:paddingStart="24dp"
+ android:paddingEnd="24dp"
+ android:gravity="center"
+ android:orientation="vertical">
+
+ <ImageView
+ android:id="@+id/accessibility_permissionDialog_icon"
+ android:layout_width="36dp"
+ android:layout_height="36dp"
+ android:layout_marginTop="16dp"
+ android:layout_marginBottom="16dp"
+ android:scaleType="fitCenter"/>
+
+ <TextView
+ android:id="@+id/accessibility_permissionDialog_title"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center"
+ android:textSize="20sp"
+ android:textColor="?android:attr/textColorPrimary"
+ android:fontFamily="google-sans-medium"/>
+
+ <TextView
+ android:id="@+id/accessibility_encryption_warning"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:padding="10dip"
+ android:textAlignment="viewStart"
+ android:textAppearance="?android:attr/textAppearanceMedium"/>
+
+ <TextView
+ android:id="@+id/accessibility_permissionDialog_description"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="16dp"
+ android:layout_marginBottom="32dp"
+ android:text="@string/accessibility_service_warning_description"
+ android:textSize="16sp"
+ android:textColor="?android:attr/textColorPrimary"
+ android:fontFamily="sans-serif"/>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center"
+ android:orientation="horizontal">
+
+ <ImageView
+ android:id="@+id/accessibility_controlScreen_icon"
+ android:layout_width="18dp"
+ android:layout_height="18dp"
+ android:layout_marginRight="12dp"
+ android:src="@android:drawable/ic_visibility"
+ android:scaleType="fitCenter"/>
+
+ <TextView
+ android:id="@+id/accessibility_controlScreen_title"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="@string/accessibility_service_screen_control_title"
+ android:textSize="16sp"
+ android:textColor="?android:attr/textColorPrimary"
+ android:fontFamily="sans-serif"/>
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/accessibility_controlScreen_description"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="24dp"
+ android:paddingStart="30dp"
+ android:text="@string/accessibility_service_screen_control_description"
+ android:textSize="14sp"
+ android:textColor="?android:attr/textColorSecondary"
+ android:fontFamily="sans-serif"/>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center"
+ android:orientation="horizontal">
+
+ <ImageView
+ android:id="@+id/accessibility_performAction_icon"
+ android:layout_width="18dp"
+ android:layout_height="18dp"
+ android:layout_marginEnd="12dp"
+ android:src="@android:drawable/ic_pan_tool"
+ android:scaleType="fitCenter"/>
+
+ <TextView
+ android:id="@+id/accessibility_performAction_title"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="@string/accessibility_service_action_perform_title"
+ android:textSize="16sp"
+ android:textColor="?android:attr/textColorPrimary"
+ android:fontFamily="sans-serif"/>
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/accessibility_performAction_description"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="24dp"
+ android:paddingStart="30dp"
+ android:text="@string/accessibility_service_action_perform_description"
+ android:textSize="14sp"
+ android:textColor="?android:attr/textColorSecondary"
+ android:fontFamily="sans-serif" />
+ </LinearLayout>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="@color/chooser_row_divider"/>
+
+ <Button
+ android:id="@+id/accessibility_permission_enable_allow_button"
+ android:layout_width="match_parent"
+ android:layout_height="56dp"
+ android:background="?android:attr/selectableItemBackground"
+ android:text="@string/accessibility_dialog_button_allow"
+ style="?attr/buttonBarPositiveButtonStyle"/>
+
+ <View
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:background="@color/chooser_row_divider"/>
+
+ <Button
+ android:id="@+id/accessibility_permission_enable_deny_button"
+ android:layout_width="match_parent"
+ android:layout_height="56dp"
+ android:background="?android:attr/selectableItemBackground"
+ android:text="@string/accessibility_dialog_button_deny"
+ style="?attr/buttonBarPositiveButtonStyle"/>
+ </LinearLayout>
+
+</ScrollView>
\ No newline at end of file
diff --git a/core/res/res/layout/conversation_face_pile_layout.xml b/core/res/res/layout/conversation_face_pile_layout.xml
new file mode 100644
index 0000000..1db3870
--- /dev/null
+++ b/core/res/res/layout/conversation_face_pile_layout.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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
+ -->
+<FrameLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/conversation_face_pile"
+ android:layout_width="@dimen/conversation_avatar_size"
+ android:layout_height="@dimen/conversation_avatar_size"
+ android:forceHasOverlappingRendering="false"
+ >
+ <ImageView
+ android:id="@+id/conversation_face_pile_top"
+ android:layout_width="36dp"
+ android:layout_height="36dp"
+ android:scaleType="centerCrop"
+ android:layout_gravity="end|top"
+ />
+ <FrameLayout
+ android:id="@+id/conversation_face_pile_bottom_background"
+ android:layout_width="40dp"
+ android:layout_height="40dp"
+ android:layout_gravity="start|bottom"
+ android:background="@drawable/conversation_badge_background">
+ <ImageView
+ android:id="@+id/conversation_face_pile_bottom"
+ android:layout_width="36dp"
+ android:layout_height="36dp"
+ android:scaleType="centerCrop"
+ android:layout_gravity="center"
+ />
+ </FrameLayout>
+</FrameLayout>
diff --git a/core/res/res/layout/notification_template_header.xml b/core/res/res/layout/notification_template_header.xml
index f5fa1b6a..6f36aae 100644
--- a/core/res/res/layout/notification_template_header.xml
+++ b/core/res/res/layout/notification_template_header.xml
@@ -91,7 +91,6 @@
android:textAppearance="@style/TextAppearance.Material.Notification.Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_gravity="center"
android:layout_marginStart="@dimen/notification_header_separating_margin"
android:layout_marginEnd="@dimen/notification_header_separating_margin"
android:showRelative="true"
diff --git a/core/res/res/layout/notification_template_material_conversation.xml b/core/res/res/layout/notification_template_material_conversation.xml
new file mode 100644
index 0000000..2348dee
--- /dev/null
+++ b/core/res/res/layout/notification_template_material_conversation.xml
@@ -0,0 +1,206 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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
+ -->
+<com.android.internal.widget.ConversationLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/status_bar_latest_event_content"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:clipChildren="false"
+ android:tag="conversation"
+ android:theme="@style/Theme.DeviceDefault.Notification"
+ >
+
+ <FrameLayout
+ android:layout_width="@dimen/conversation_content_start"
+ android:layout_height="wrap_content"
+ android:gravity="start|top"
+ android:clipChildren="false"
+ android:clipToPadding="false"
+ android:paddingTop="12dp"
+ >
+
+ <FrameLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="top|center_horizontal"
+ >
+
+ <!-- Big icon: 52x52, 12dp padding left + top, 16dp padding right -->
+ <ImageView
+ android:id="@+id/conversation_icon"
+ android:layout_width="@dimen/conversation_avatar_size"
+ android:layout_height="@dimen/conversation_avatar_size"
+ android:scaleType="centerCrop"
+ android:importantForAccessibility="no"
+ />
+
+ <ViewStub
+ android:layout="@layout/conversation_face_pile_layout"
+ android:layout_width="@dimen/conversation_avatar_size"
+ android:layout_height="@dimen/conversation_avatar_size"
+ android:id="@+id/conversation_face_pile"
+ />
+
+ <FrameLayout
+ android:id="@+id/conversation_icon_badge"
+ android:layout_width="20dp"
+ android:layout_height="20dp"
+ android:layout_marginLeft="@dimen/conversation_badge_side_margin"
+ android:layout_marginTop="@dimen/conversation_badge_side_margin"
+ android:background="@drawable/conversation_badge_background" >
+ <!-- Badge: 20x20, 48dp padding left + top -->
+ <com.android.internal.widget.CachingIconView
+ android:id="@+id/icon"
+ android:layout_width="@dimen/conversation_icon_size_badged"
+ android:layout_height="@dimen/conversation_icon_size_badged"
+ android:layout_gravity="center"
+ />
+ </FrameLayout>
+ </FrameLayout>
+ </FrameLayout>
+
+ <!-- Wraps entire "expandable" notification -->
+ <com.android.internal.widget.RemeasuringLinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="top"
+ android:clipToPadding="false"
+ android:clipChildren="false"
+ android:orientation="vertical"
+ >
+ <!-- LinearLayout for Expand Button-->
+ <com.android.internal.widget.RemeasuringLinearLayout
+ android:id="@+id/expand_button_and_content_container"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:gravity="start|top"
+ android:orientation="horizontal"
+ android:clipChildren="false"
+ android:clipToPadding="false">
+ <!--TODO: move this into a separate layout and share logic with the header to bring back app opps etc-->
+ <com.android.internal.widget.RemeasuringLinearLayout
+ android:id="@+id/notification_action_list_margin_target"
+ android:layout_width="0dp"
+ android:orientation="vertical"
+ android:layout_height="wrap_content"
+ android:layout_weight="1">
+
+ <!-- Header -->
+ <LinearLayout
+ android:id="@+id/conversation_header"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:paddingTop="16dp"
+ android:paddingStart="@dimen/conversation_content_start"
+ >
+ <TextView
+ android:id="@+id/conversation_text"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginEnd="@dimen/notification_header_separating_margin"
+ android:textAppearance="@style/TextAppearance.DeviceDefault.Notification.Title"
+ android:textSize="16sp"
+ android:singleLine="true"
+ />
+
+ <TextView
+ android:id="@+id/time_divider"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?attr/notificationHeaderTextAppearance"
+ android:layout_marginStart="@dimen/notification_header_separating_margin"
+ android:layout_marginEnd="@dimen/notification_header_separating_margin"
+ android:text="@string/notification_header_divider_symbol"
+ android:layout_gravity="center"
+ android:paddingTop="1sp"
+ android:singleLine="true"
+ android:visibility="gone"
+ />
+
+ <DateTimeView
+ android:id="@+id/time"
+ android:textAppearance="@style/TextAppearance.Material.Notification.Time"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center"
+ android:layout_marginStart="@dimen/notification_header_separating_margin"
+ android:paddingTop="1sp"
+ android:showRelative="true"
+ android:singleLine="true"
+ android:visibility="gone"
+ />
+
+ <ImageView
+ android:id="@+id/profile_badge"
+ android:layout_width="@dimen/notification_badge_size"
+ android:layout_height="@dimen/notification_badge_size"
+ android:layout_gravity="center"
+ android:layout_marginStart="4dp"
+ android:paddingTop="2dp"
+ android:scaleType="fitCenter"
+ android:visibility="gone"
+ android:contentDescription="@string/notification_work_profile_content_description"
+ />
+ </LinearLayout>
+
+ <!-- Messages -->
+ <com.android.internal.widget.MessagingLinearLayout
+ android:id="@+id/notification_messaging"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="2dp"
+ android:spacing="@dimen/notification_messaging_spacing"
+ android:clipToPadding="false"
+ android:clipChildren="false"
+ />
+ </com.android.internal.widget.RemeasuringLinearLayout>
+ <!-- Unread Count -->
+ <!-- <TextView /> -->
+
+ <!-- This is where the expand button will be placed when collapsed-->
+ </com.android.internal.widget.RemeasuringLinearLayout>
+
+ <include layout="@layout/notification_template_smart_reply_container"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="@dimen/notification_content_margin"
+ android:layout_marginStart="@dimen/conversation_content_start"
+ android:layout_marginEnd="@dimen/notification_content_margin_end" />
+ <include layout="@layout/notification_material_action_list" />
+ </com.android.internal.widget.RemeasuringLinearLayout>
+
+ <!--This is dynamically placed between here and at the end of the layout-->
+ <FrameLayout
+ android:id="@+id/expand_button_container"
+ android:layout_width="wrap_content"
+ android:layout_height="@dimen/conversation_expand_button_expanded_size"
+ android:layout_gravity="end|top"
+ android:paddingStart="16dp"
+ android:paddingEnd="@dimen/notification_content_margin_end">
+ <com.android.internal.widget.NotificationExpandButton
+ android:id="@+id/expand_button"
+ android:layout_width="@dimen/notification_header_expand_icon_size"
+ android:layout_height="@dimen/notification_header_expand_icon_size"
+ android:layout_gravity="center"
+ android:drawable="@drawable/ic_expand_notification"
+ android:clickable="false"
+ android:importantForAccessibility="no"
+ />
+ </FrameLayout>
+</com.android.internal.widget.ConversationLayout>
diff --git a/core/res/res/layout/notification_template_messaging_group.xml b/core/res/res/layout/notification_template_messaging_group.xml
index 483b479..3188861 100644
--- a/core/res/res/layout/notification_template_messaging_group.xml
+++ b/core/res/res/layout/notification_template_messaging_group.xml
@@ -20,14 +20,20 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
- <ImageView
- android:id="@+id/message_icon"
- android:layout_width="@dimen/messaging_avatar_size"
- android:layout_height="@dimen/messaging_avatar_size"
- android:layout_marginEnd="12dp"
- android:scaleType="centerCrop"
- android:importantForAccessibility="no" />
+ <FrameLayout
+ android:id="@+id/message_icon_container"
+ android:layout_width="@dimen/conversation_content_start"
+ android:layout_height="wrap_content">
+ <ImageView
+ android:layout_gravity="top|center_horizontal"
+ android:id="@+id/message_icon"
+ android:layout_width="@dimen/messaging_avatar_size"
+ android:layout_height="@dimen/messaging_avatar_size"
+ android:scaleType="centerCrop"
+ android:importantForAccessibility="no" />
+ </FrameLayout>
<com.android.internal.widget.RemeasuringLinearLayout
+ android:id="@+id/messaging_group_content_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
@@ -43,7 +49,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/notification_text_margin_top"
- android:spacing="2dp"/>
+ android:spacing="2dp" />
</com.android.internal.widget.RemeasuringLinearLayout>
<FrameLayout
android:id="@+id/messaging_group_icon_container"
diff --git a/core/res/res/layout/resolver_empty_states.xml b/core/res/res/layout/resolver_empty_states.xml
index 619b392..176f289 100644
--- a/core/res/res/layout/resolver_empty_states.xml
+++ b/core/res/res/layout/resolver_empty_states.xml
@@ -38,7 +38,7 @@
android:layout_height="wrap_content"
android:fontFamily="@string/config_headlineFontFamilyMedium"
android:textColor="@color/resolver_empty_state_text"
- android:textSize="18sp"
+ android:textSize="14sp"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/resolver_empty_state_subtitle"
@@ -47,7 +47,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/resolver_empty_state_text"
- android:textSize="14sp"
+ android:textSize="12sp"
android:gravity="center_horizontal"
android:layout_centerHorizontal="true" />
<Button
diff --git a/core/res/res/layout/resolver_list.xml b/core/res/res/layout/resolver_list.xml
index e17fc8a..b754e0c 100644
--- a/core/res/res/layout/resolver_list.xml
+++ b/core/res/res/layout/resolver_list.xml
@@ -100,8 +100,7 @@
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/colorBackgroundFloating"
- android:foreground="?attr/dividerVertical"
- android:layout_marginBottom="@dimen/resolver_tab_divider_bottom_padding"/>
+ android:foreground="?attr/dividerVertical"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
diff --git a/core/res/res/layout/resolver_list_with_default.xml b/core/res/res/layout/resolver_list_with_default.xml
index 0d4523a..06a7633 100644
--- a/core/res/res/layout/resolver_list_with_default.xml
+++ b/core/res/res/layout/resolver_list_with_default.xml
@@ -183,8 +183,7 @@
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/colorBackgroundFloating"
- android:foreground="?attr/dividerVertical"
- android:layout_marginBottom="@dimen/resolver_tab_divider_bottom_padding"/>
+ android:foreground="?attr/dividerVertical"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
diff --git a/core/res/res/values-af/strings.xml b/core/res/res/values-af/strings.xml
index af56edd..632c400 100644
--- a/core/res/res/values-af/strings.xml
+++ b/core/res/res/values-af/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Neem skermkiekie vir foutverslag oor <xliff:g id="NUMBER_1">%d</xliff:g> sekondes.</item>
<item quantity="one">Neem skermkiekie vir foutverslag oor <xliff:g id="NUMBER_0">%d</xliff:g> sekonde.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Skermkiekie met foutverslag geneem"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Kon nie skermkiekie met foutverslag neem nie"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Stilmodus"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Klank is AF"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Klank is AAN"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Laat die program toe om \'n oproep voort te sit wat in \'n ander program begin is."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lees foonnommers"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Laat die program toe om toegang tot die toestel se foonnommers te kry."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"hou motorskerm aan"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"verhoed dat tablet slaap"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"keer dat jou Android TV-toestel slaap"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"verhoed foon om te slaap"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Laat die program toe om die motorskerm aan te hou."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Laat die program toe om die tablet te keer om te slaap."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Laat die program toe om te keer dat jou Android TV-toestel slaap."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Laat die program toe om die foon te keer om te slaap."</string>
@@ -1631,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Verhoog volume bo aanbevole vlak?\n\nOm lang tydperke teen hoë volume te luister, kan jou gehoor beskadig."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Gebruik toeganklikheidkortpad?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Wanneer die kortpad aan is, sal \'n toeganklikheidkenmerk begin word as albei volumeknoppies 3 sekondes lank gedruk word."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Tik op die toeganklikheidprogram wat jy wil gebruik"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Kies programme wat jy met toeganklikheidknoppie wil gebruik"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Kies programme wat jy met die volumesleutelkortpad wil gebruik"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Wysig kortpaaie"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Kanselleer"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Skakel kortpad af"</string>
@@ -1853,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Ongekategoriseer"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Jy stel die belangrikheid van hierdie kennisgewings."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Dit is belangrik as gevolg van die mense wat betrokke is."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Gepasmaakte programkennisgewing"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Laat <xliff:g id="APP">%1$s</xliff:g> toe om \'n nuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> te skep (\'n gebruiker met hierdie rekening bestaan reeds)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Laat <xliff:g id="APP">%1$s</xliff:g> toe om \'n nuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> te skep?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Voeg \'n taal by"</string>
@@ -2028,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> is in die BEPERK-groep geplaas"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Persoonlik"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Werk"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Persoonlike aansig"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Werkaansig"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Kan nie met werkprogramme deel nie"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Kan nie met persoonlike programme deel nie"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Jou IT-admin het deling tussen persoonlike en werkprogramme geblokkeer"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Skakel werkprogramme aan"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Skakel werkprogramme aan om toegang tot werkprogramme en -kontakte te kry"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Jou IT-admin het deling tussen persoonlike en werkprofiele geblokkeer"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Kan nie toegang tot werkprogramme kry nie"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Jou IT-admin laat jou nie toe om persoonlike inhoud in werkprogramme te bekyk nie"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Kan nie toegang tot persoonlike programme kry nie"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Jou IT-admin laat jou nie toe om werkinhoud in persoonlike programme te bekyk nie"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Skakel werkprofiel aan om inhoud te deel"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Skakel werkprofiel aan om inhoud te bekyk"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Geen programme beskikbaar nie"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Ons kon geen programme kry nie"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Skakel werk aan"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Skakel aan"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Neem oudio in telefonie-oproepe op of speel dit"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Laat hierdie program, indien dit as die verstekbellerprogram aangewys is, toe om oudio in telefonie-oproepe op te neem of te speel."</string>
</resources>
diff --git a/core/res/res/values-am/strings.xml b/core/res/res/values-am/strings.xml
index 9a0ed24..898a56a 100644
--- a/core/res/res/values-am/strings.xml
+++ b/core/res/res/values-am/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">በ<xliff:g id="NUMBER_1">%d</xliff:g> ሰከንዶች ውስጥ ለሳንካ ሪፖርት ቅጽበታዊ ገጽ ዕይታን በማንሳት ላይ።</item>
<item quantity="other">በ<xliff:g id="NUMBER_1">%d</xliff:g> ሰከንዶች ውስጥ ለሳንካ ሪፖርት ቅጽበታዊ ገጽ ዕይታን በማንሳት ላይ።</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ቅጽበታዊ ገጽ እይታ ከሳንካ ሪፖርት ጋር ተነስቷል"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ቅጽበታዊ ገጽ እይታን ከሳንካ ሪፖርት ጋር ማንሳት አልተሳካም"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"የፀጥታ ሁነታ"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ድምፅ ጠፍቷል"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ድምፅ በርቷል"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"መተግበሪያው በሌላ መተግበሪያ ውስጥ የተጀመረ ጥሪ እንዲቀጥል ያስችለዋል።"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ስልክ ቁጥሮች ያንብቡ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"መተግበሪያው የመሣሪያውን የስልክ ቁጥሮች እንዲደርስባቸው ይፈቅድለታል።"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"የመኪና ማያ ገጽ እንደበራ አቆይ"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ጡባዊ ከማንቀላፋት ተከላከል"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"የእርስዎ Android TV መሣሪያ እንዳይተኛ ይከላከሉ"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ስልክ ከማንቀላፋት ተከላከል"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"መተግበሪያው የመኪናው ማያ ገጽ እንደበራ እንዲያቆየው ያስችለዋል።"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ጡባዊውን ከመተኛት መከልከል ለመተግበሪያው ይፈቅዳሉ።"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"የእርስዎን Android TV ከመተኛት እንዲከላከል ለመተግበሪያው ይፈቅድለታል።"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ስልኩን ከመተኛት መከልከል ለመተግበሪያው ይፈቅዳሉ።"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"ድምጹ ከሚመከረው መጠን በላይ ከፍ ይበል?\n\nበከፍተኛ ድምጽ ለረጅም ጊዜ ማዳመጥ ጆሮዎን ሊጎዳው ይችላል።"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"የተደራሽነት አቋራጭ ጥቅም ላይ ይዋል?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"አቋራጩ ሲበራ ሁለቱንም የድምጽ አዝራሮች ለ3 ሰከንዶች ተጭኖ መቆየት የተደራሽነት ባህሪን ያስጀምረዋል።"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"አቋራጮችን አርትዕ ያድርጉ"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ይቅር"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"አቋራጩን አጥፋ"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"ያልተመደቡ"</string>
<string name="importance_from_user" msgid="2782756722448800447">"የእነዚህን ማሳወቂያዎች አስፈላጊነት አዘጋጅተዋል።"</string>
<string name="importance_from_person" msgid="4235804979664465383">"ይሄ በሚሳተፉ ሰዎች ምክንያት አስፈላጊ ነው።"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"ብጁ የመተግበሪያ ማሳወቂያ"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> በ<xliff:g id="ACCOUNT">%2$s</xliff:g> አዲስ ተጠቃሚ እንዲፈጥር ይፈቀድለት (ይህ መለያ ያለው ተጠቃሚ አስቀድሞ አለ)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> አዲስ ተጠቃሚ ከ <xliff:g id="ACCOUNT">%2$s</xliff:g> ጋር መፍጠር እንዲችል ይፍቀዱ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"ቋንቋ ያክሉ"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ወደ የRESTRICTED ባልዲ ተከትቷል"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"የግል"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ሥራ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"በሥራ መተግበሪያዎች ማጋራት አይቻልም"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"በግል መተግበሪያዎች ማጋራት አይቻልም"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"የእርስዎ አይቲ አስተዳዳሪ በግል እና በሥራ መተግበሪያዎች መካከል ማጋራትን አግደዋል"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"የሥራ መተግበሪያዎች ያብሩ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"የሥራ መተግበሪያዎች እና እውቂያዎችን ለመድረስ የሥራ መተግበሪያዎችን ያብሩ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ምንም መተግበሪያዎች አይገኙም"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ምንም መተግበሪያዎች ልናገኝ አልቻልንም"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ሥራን ያብሩ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"በስልክ ጥሪዎች ላይ ኦዲዮን መቅዳት ወይም ማጫወት"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ይህ መተግበሪያ እንደ ነባሪ የመደወያ መተግበሪያ ሲመደብ በስልክ ጥሪዎች ላይ ኦዲዮን እንዲቀዳ ወይም እንዲያጫውት ያስችለዋል።"</string>
</resources>
diff --git a/core/res/res/values-ar/strings.xml b/core/res/res/values-ar/strings.xml
index 7d1e01d..cf9cab1 100644
--- a/core/res/res/values-ar/strings.xml
+++ b/core/res/res/values-ar/strings.xml
@@ -215,7 +215,7 @@
<string name="power_dialog" product="tv" msgid="7792839006640933763">"خيارات Android TV"</string>
<string name="power_dialog" product="default" msgid="1107775420270203046">"خيارات الهاتف"</string>
<string name="silent_mode" msgid="8796112363642579333">"وضع صامت"</string>
- <string name="turn_on_radio" msgid="2961717788170634233">"تشغيل اللاسلكي"</string>
+ <string name="turn_on_radio" msgid="2961717788170634233">"تفعيل اللاسلكي"</string>
<string name="turn_off_radio" msgid="7222573978109933360">"إيقاف تفعيل الشبكة اللاسلكية"</string>
<string name="screen_lock" msgid="2072642720826409809">"قفل الشاشة"</string>
<string name="power_off" msgid="4111692782492232778">"إيقاف التشغيل"</string>
@@ -261,10 +261,8 @@
<item quantity="other">سيتم التقاط لقطة شاشة لتقرير الخطأ خلال <xliff:g id="NUMBER_1">%d</xliff:g> ثانية.</item>
<item quantity="one">سيتم التقاط لقطة شاشة لتقرير الخطأ خلال <xliff:g id="NUMBER_0">%d</xliff:g> ثانية.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"تم التقاط لقطة شاشة من خلال تقرير خطأ."</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"تعذّر التقاط لقطة شاشة من خلال تقرير خطأ."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"وضع صامت"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"الصوت متوقف"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"الصوت قيد التفعيل"</string>
@@ -466,9 +464,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"السماح للتطبيق بمواصلة مكالمة بدأت في تطبيق آخر."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"قراءة أرقام الهواتف"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"للسماح للتطبيق بالوصول إلى أرقام الهواتف على هذا الجهاز."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"الاحتفاظ بشاشة السيارة مفعَّلة"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"منع الجهاز اللوحي من الدخول في وضع السكون"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"منع جهاز Android TV من الانتقال إلى وضع السكون"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"منع الهاتف من الدخول في وضع السكون"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"يسمح هذا الإذن للتطبيق بالاحتفاظ بشاشة السيارة مفعَّلة."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"للسماح للتطبيق بمنع الجهاز اللوحي من الانتقال إلى وضع السكون."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"للسماح للتطبيق بمنع جهاز Android TV من الانتقال إلى وضع السكون."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"للسماح للتطبيق بمنع الهاتف من الانتقال إلى وضع السكون."</string>
@@ -617,7 +617,7 @@
<string name="face_icon_content_description" msgid="465030547475916280">"رمز الوجه"</string>
<string name="permlab_readSyncSettings" msgid="6250532864893156277">"قراءة إعدادات المزامنة"</string>
<string name="permdesc_readSyncSettings" msgid="1325658466358779298">"للسماح للتطبيق بقراءة الإعدادات المتزامنة لحساب ما. على سبيل المثال، يمكن أن يؤدي هذا إلى تحديد ما إذا تمت مزامنة تطبيق \"الأشخاص\" مع حساب ما."</string>
- <string name="permlab_writeSyncSettings" msgid="6583154300780427399">"التبديل بين تشغيل المزامنة وإيقافها"</string>
+ <string name="permlab_writeSyncSettings" msgid="6583154300780427399">"التبديل بين تفعيل المزامنة وإيقافها"</string>
<string name="permdesc_writeSyncSettings" msgid="6029151549667182687">"للسماح للتطبيق بتعديل إعدادات المزامنة لحساب ما. على سبيل المثال، يمكن استخدام ذلك لتفعيل مزامنة تطبيق \"الأشخاص\" مع حساب ما."</string>
<string name="permlab_readSyncStats" msgid="3747407238320105332">"قراءة إحصاءات المزامنة"</string>
<string name="permdesc_readSyncStats" msgid="3867809926567379434">"للسماح للتطبيق بقراءة إحصائيات المزامنة لحساب ما، بما في ذلك سجل الأحداث المتزامنة ومقدار البيانات التي تمت مزامنتها."</string>
@@ -853,7 +853,7 @@
<string name="lockscreen_transport_pause_description" msgid="6705284702135372494">"إيقاف مؤقت"</string>
<string name="lockscreen_transport_play_description" msgid="106868788691652733">"تشغيل"</string>
<string name="lockscreen_transport_stop_description" msgid="1449552232598355348">"إيقاف"</string>
- <string name="lockscreen_transport_rew_description" msgid="7680106856221622779">"إرجاع"</string>
+ <string name="lockscreen_transport_rew_description" msgid="7680106856221622779">"ترجيع"</string>
<string name="lockscreen_transport_ffw_description" msgid="4763794746640196772">"تقديم سريع"</string>
<string name="emergency_calls_only" msgid="3057351206678279851">"مكالمات الطوارئ فقط"</string>
<string name="lockscreen_network_locked_message" msgid="2814046965899249635">"الشبكة مؤمّنة"</string>
@@ -1719,6 +1719,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"هل تريد رفع مستوى الصوت فوق المستوى الموصى به؟\n\nقد يضر سماع صوت عالٍ لفترات طويلة بسمعك."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"هل تريد استخدام اختصار \"سهولة الاستخدام\"؟"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"عند تفعيل الاختصار، يؤدي الضغط على زرّي التحكّم في مستوى الصوت معًا لمدة 3 ثوانٍ إلى تفعيل إحدى ميزات إمكانية الوصول."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"تعديل الاختصارات"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"إلغاء"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"إيقاف الاختصار"</string>
@@ -1981,8 +1987,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"غير مصنفة"</string>
<string name="importance_from_user" msgid="2782756722448800447">"لقد عيَّنت أهمية هذه الإشعارات."</string>
<string name="importance_from_person" msgid="4235804979664465383">"هذه الرسالة مهمة نظرًا لأهمية الأشخاص المعنيين."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"إشعار تطبيق مخصّص"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"هل تسمح لتطبيق <xliff:g id="APP">%1$s</xliff:g> بإنشاء مستخدم جديد باستخدام <xliff:g id="ACCOUNT">%2$s</xliff:g> (يوجد مستخدم بهذا الحساب مسبقًا)؟"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"هل تسمح لتطبيق <xliff:g id="APP">%1$s</xliff:g> بإنشاء مستخدم جديد باستخدام <xliff:g id="ACCOUNT">%2$s</xliff:g> ؟"</string>
<string name="language_selection_title" msgid="52674936078683285">"إضافة لغة"</string>
@@ -2164,14 +2169,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"تم وضع <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> في الحزمة \"محظورة\"."</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"شخصي"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"عمل"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"تتعذّر المشاركة مع تطبيقات العمل"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"تتعذّر المشاركة مع التطبيقات الشخصية"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"حظر مشرف تكنولوجيا المعلومات لديك المشاركة بين التطبيقات الشخصية وتطبيقات العمل."</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"تشغيل تطبيقات العمل"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"تشغيل تطبيقات العمل للوصول إلى تطبيقات العمل وجهات الاتصال"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ليس هناك تطبيقات متاحة"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"تعذّر العثور على أي تطبيقات"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"تفعيل الملف الشخصي للعمل"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"تسجيل الصوت أو تشغيله في المكالمات الهاتفية"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"يسمح الإذن لهذا التطبيق بتسجيل الصوت أو تشغيله في المكالمات الهاتفية عندما يتم تخصيصه كالتطبيق التلقائي لبرنامج الاتصال."</string>
</resources>
diff --git a/core/res/res/values-as/strings.xml b/core/res/res/values-as/strings.xml
index b646b40..75308c0 100644
--- a/core/res/res/values-as/strings.xml
+++ b/core/res/res/values-as/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">ত্ৰুটি সম্পর্কীয় অভিযোগৰ বাবে <xliff:g id="NUMBER_1">%d</xliff:g>ছেকেণ্ডৰ ভিতৰত স্ক্ৰীণশ্বট লোৱা হ\'ব।</item>
<item quantity="other">ত্ৰুটি সম্পর্কীয় অভিযোগৰ বাবে <xliff:g id="NUMBER_1">%d</xliff:g>ছেকেণ্ডৰ ভিতৰত স্ক্ৰীণশ্বট লোৱা হ\'ব।</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"বাগ ৰিপ’ৰ্টৰ সৈতে স্ক্ৰীনশ্বট লোৱা হ’ল"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"বাগ ৰিপ’ৰ্টৰ সৈতে স্ক্ৰীনশ্বট ল’ব পৰা নগ’ল"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"নিঃশব্দ ম\'ড"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ধ্বনি অফ আছে"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ধ্বনি অন আছে"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"এপটোক এনে কল কৰিবলৈ দিয়ে যিটোৰ আৰম্ভণি অইন এটা এপত হৈছিল।"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ফ\'ন নম্বৰসমূহ পঢ়ে"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"এপটোক ডিভাইচটোৰ ফ\'ন নম্বৰসমূহ চাবলৈ অনুমতি দিয়ে।"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"গাড়ীৰ স্ক্রীনখন অন কৰি ৰখা"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"টে\'বলেট সুপ্ত অৱস্থালৈ যোৱাত বাধা দিয়ক"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"আপোনাৰ Android TV ডিভাইচটো সুপ্ত অৱস্থালৈ যোৱাত বাধা দিয়ক"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ফ\'ন সুপ্ত অৱস্থালৈ যোৱাত বাধা দিয়ক"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"এপ্টোক গাড়ীৰ স্ক্রীনখন অন কৰি ৰাখিবলৈ অনুমতি দিয়ে।"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"টে\'বলেট সুপ্ত অৱস্থালৈ যোৱাৰ পৰা প্ৰতিৰোধ কৰিবলৈ এপটোক অনুমতি দিয়ে।"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"এপ্টোক আপোনাৰ Android TV ডিভাইচটো সুপ্ত অৱস্থালৈ যোৱাত বাধা দিবলৈ অনুমতি দিয়ে।"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ফ\'ন সুপ্ত অৱস্থালৈ যোৱাৰ পৰা প্ৰতিৰোধ কৰিবলৈ এপটোক অনুমতি দিয়ে।"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"অনুমোদিত স্তৰতকৈ ওপৰলৈ ভলিউম বঢ়াব নেকি?\n\nদীৰ্ঘ সময়ৰ বাবে উচ্চ ভলিউমত শুনাৰ ফলত শ্ৰৱণ ক্ষমতাৰ ক্ষতি হ\'ব পাৰে।"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"দিব্যাংগসকলৰ সুবিধাৰ শ্বৰ্টকাট ব্যৱহাৰ কৰেনে?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"শ্বৰ্টকাটটো অন হৈ থকাৰ সময়ত দুয়োটা ভলিউম বুটাম ৩ ছেকেণ্ডৰ বাবে হেঁচি ধৰি ৰাখিলে এটা সাধ্য সুবিধা আৰম্ভ হ’ব।"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"শ্বৰ্টকাটসমূহ সম্পাদনা কৰক"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"বাতিল কৰক"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"শ্বৰ্টকাট অফ কৰক"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>ক সীমাবদ্ধ বাকেটটোত ৰখা হৈছে"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ব্যক্তিগত"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"কৰ্মস্থান"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"কৰ্মস্থানৰ এপ্সমূহৰ সৈতে শ্বেয়াৰ কৰিব নোৱাৰি"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ব্যক্তিগত এপ্সমূহৰ সৈতে শ্বেয়াৰ কৰিব নোৱাৰি"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"আপোনাৰ আইটি প্ৰশাসকে ব্যক্তিগত আৰু কৰ্মস্থানৰ এপ্সমূহৰ মাজত সমল শ্বেয়াৰ কৰাটো অৱৰোধ কৰিছে"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"কৰ্মস্থানৰ এপ্সমূহ অন কৰক"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"কৰ্মস্থানৰ এপ্ আৰু সম্পৰ্কসমূহ এক্সেছ কৰিবলৈ কৰ্মস্থানৰ এপ্সমূহ অন কৰক"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"কোনো এপ্ উপলব্ধ নহয়"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"আমি কোনো এপ্ বিচাৰি নাপালোঁ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"কৰ্মস্থানৰ প্ৰ’ফাইল অন কৰক"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"টেলিফ’নী কলসমূহত অডিঅ’ ৰেকৰ্ড অথবা প্লে’ কৰক"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ডিফ’ল্ট ডায়েলাৰ এপ্লিকেশ্বন হিচাপে আবণ্টন কৰিলে, এই এপ্টোক টেলিফ’নী কলসমূহত অডিঅ’ ৰেকৰ্ড অথবা প্লে’ কৰিবলৈ অনুমতি দিয়ে।"</string>
</resources>
diff --git a/core/res/res/values-az/strings.xml b/core/res/res/values-az/strings.xml
index fe5e4cf..fa3dbf6 100644
--- a/core/res/res/values-az/strings.xml
+++ b/core/res/res/values-az/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Baq hesabatı üçün <xliff:g id="NUMBER_1">%d</xliff:g> saniyədə sktinşot çəkilir.</item>
<item quantity="one">Baq hesabatı üçün <xliff:g id="NUMBER_0">%d</xliff:g> saniyədə skrinşot çəkilir.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Xəta hesabatı ilə ekran şəkli çəkildi"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Xəta hesabatı ilə ekran şəkli çəkmək alınmadı."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Səssiz rejim"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Səs qapalıdır"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Səs Aktivdir"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Tətbiqə digər tətbiqdə başlayan zəngə davam etmək icazəsi verilir."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"telefon nömrələrini oxuyun"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Tətbiqə cihazın telefon nömrələrinə daxil olmağa icazə verir."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"avtomobilin ekranını aktiv saxlamaq"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"planşetin yuxu rejiminin qarşısını almaq"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV-nin yuxu rejiminə keçməsinə icazə verməyin"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"telefonun yuxu rejiminə keçməsini əngəllə"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Tətbiqə avtomobilin ekranını aktiv saxlamaq icazəsi verir."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Tətbiqə planşetin yuxu rejimini qadağan etməyə imkan verir."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Tətbiqə Android TV cihazında yuxu sessiyasını deaktiv etmək icazəsi verir."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Tətbiqə telefonun yuxu rejimini qadağan etmək imkanı verir."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Səsin həcmi tövsiyə olunan səviyyədən artıq olsun?\n\nYüksək səsi uzun zaman dinləmək eşitmə qabiliyyətinizə zərər vura bilər."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Əlçatımlılıq Qısayolu istifadə edilsin?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Qısayol aktiv olduqda, hər iki səs düyməsinə 3 saniyə basıb saxlamaqla əlçatımlılıq funksiyası başladılacaq."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Qısayolları redaktə edin"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Ləğv edin"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Qısayolu Deaktiv edin"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Kateqoriyasız"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Bildirişlərin əhəmiyyətini Siz ayarlaryırsınız."</string>
<string name="importance_from_person" msgid="4235804979664465383">"İnsanlar cəlb olunduğu üçün bu vacibdir."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Fərdi tətbiq bildirişi"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> tətbiqinə <xliff:g id="ACCOUNT">%2$s</xliff:g> (artıq bu hesabı olan İstifadəçi mövcuddur) ilə yeni İstifadəçi yaratmağa icazə verilsin?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> tətbiqinə <xliff:g id="ACCOUNT">%2$s</xliff:g> ilə yeni İstifadəçi yartmağa icazə verilsin?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dil əlavə edin"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> MƏHDUDLAŞDIRILMIŞ səbətinə yerləşdirilib"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Şəxsi"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"İş"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"İş tətbiqləri ilə paylaşmaq olmur"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Şəxsi tətbiqlərlə paylaşmaq olmur"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"İT admininiz şəxsi və iş tətbiqləri arasında paylaşımı bloklayıb"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"İş tətbiqlərini aktiv edin"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"İş tətbiqləri və kontaktlara giriş üçün iş tətbiqlərini aktiv edin"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Heç bir tətbiq əlçatan deyil"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Heç bir tətbiq tapılmadı"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"İş profilini aktiv edin"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Telefon zənglərində audio yazmaq və ya oxutmaq"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Defolt nömrəyığan tətbiq kimi təyin edildikdə, bu tətbiqə telefon zənglərində audio yazmaq və ya oxutmaq üçün icazə verir."</string>
</resources>
diff --git a/core/res/res/values-b+sr+Latn/strings.xml b/core/res/res/values-b+sr+Latn/strings.xml
index 528b11b..c128521 100644
--- a/core/res/res/values-b+sr+Latn/strings.xml
+++ b/core/res/res/values-b+sr+Latn/strings.xml
@@ -252,10 +252,8 @@
<item quantity="few">Napravićemo snimak ekrana radi izveštaja o grešci za <xliff:g id="NUMBER_1">%d</xliff:g> sekunde.</item>
<item quantity="other">Napravićemo snimak ekrana radi izveštaja o grešci za <xliff:g id="NUMBER_1">%d</xliff:g> sekundi.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Ekran sa izveštajem o grešci je snimljen"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Snimanje ekrana sa izveštajem o grešci nije uspelo"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Nečujni režim"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zvuk je ISKLJUČEN"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zvuk je UKLJUČEN"</string>
@@ -457,9 +455,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Dozvoljava aplikaciji da nastavi poziv koji je započet u drugoj aplikaciji."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"čitanje brojeva telefona"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Dozvoljava aplikaciji da pristupa brojevima telefona na uređaju."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ne isključuj ekran u automobilu"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"sprečavanje prelaska tableta u stanje spavanja"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"sprečava Android TV uređaj da pređe u stanje spavanja"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"sprečavanje prelaska telefona u stanje spavanja"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Dozvoljava aplikaciji da ne isključuje ekran u automobilu."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Dozvoljava aplikaciji da spreči tablet da pređe u stanje spavanja."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Dozvoljava aplikaciji da spreči Android TV uređaj da pređe u stanje spavanja."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Dozvoljava aplikaciji da spreči telefon da pređe u stanje spavanja."</string>
@@ -1653,6 +1653,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Želite da pojačate zvuk iznad preporučenog nivoa?\n\nSlušanje glasne muzike duže vreme može da vam ošteti sluh."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Želite li da koristite prečicu za pristupačnost?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kada je prečica uključena, pritisnite oba dugmeta za jačinu zvuka da biste pokrenuli funkciju pristupačnosti."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Izmenite prečice"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Otkaži"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Isključi prečicu"</string>
@@ -1885,8 +1891,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nekategorizovano"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Vi podešavate važnost ovih obaveštenja."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ovo je važno zbog ljudi koji učestvuju."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Prilagođeno obaveštenje o aplikaciji"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Želite li da dozvolite da <xliff:g id="APP">%1$s</xliff:g> napravi novog korisnika sa nalogom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik sa tim nalogom već postoji)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Želite li da dozvolite da <xliff:g id="APP">%1$s</xliff:g> napravi novog korisnika sa nalogom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dodajte jezik"</string>
@@ -2062,14 +2067,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Paket <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> je dodat u segment OGRANIČENO"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Lični"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Poslovni"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ne možete da delite sadržaj sa aplikacijama za posao"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Ne možete da delite sadržaj sa ličnim aplikacijama"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT administrator je blokirao deljenje između ličnih aplikacija i aplikacija za posao"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Uključite aplikacije za posao"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Uključite aplikacije za posao da biste pristupili aplikacijama i kontaktima za posao"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nema dostupnih aplikacija"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nismo pronašli nijednu aplikaciju"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Uključi profil za Work"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Snimanje ili puštanje zvuka u telefonskim pozivima"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Omogućava ovoj aplikaciji, kada je dodeljena kao podrazumevana aplikacija za pozivanje, da snima ili pušta zvuk u telefonskim pozivima."</string>
</resources>
diff --git a/core/res/res/values-be/strings.xml b/core/res/res/values-be/strings.xml
index 1303126..87ccfe5 100644
--- a/core/res/res/values-be/strings.xml
+++ b/core/res/res/values-be/strings.xml
@@ -91,7 +91,7 @@
<string name="EmergencyCallWarningSummary" msgid="1194185880092805497">"Экстранныя выклікі ў сетцы Wi‑Fi недаступныя"</string>
<string name="notification_channel_network_alert" msgid="4788053066033851841">"Абвесткі"</string>
<string name="notification_channel_call_forward" msgid="8230490317314272406">"Пераадрасацыя выкліку"</string>
- <string name="notification_channel_emergency_callback" msgid="54074839059123159">"Рэжым экстраннага зваротнага выкліку"</string>
+ <string name="notification_channel_emergency_callback" msgid="54074839059123159">"Рэжым экстранных зваротных выклікаў"</string>
<string name="notification_channel_mobile_data_status" msgid="1941911162076442474">"Стан мабільнай перадачы даных"</string>
<string name="notification_channel_sms" msgid="1243384981025535724">"SMS-паведамленні"</string>
<string name="notification_channel_voice_mail" msgid="8457433203106654172">"Паведамленні галасавой пошты"</string>
@@ -255,10 +255,8 @@
<item quantity="many">Здымак экрана для справаздачы пра памылкі будзе зроблены праз <xliff:g id="NUMBER_1">%d</xliff:g> секунд.</item>
<item quantity="other">Здымак экрана для справаздачы пра памылкі будзе зроблены праз <xliff:g id="NUMBER_1">%d</xliff:g> секунды.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Зроблены здымак экрана са справаздачай пра памылкі"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Не ўдалося зрабіць здымак экрана са справаздачай пра памылкі"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Бязгучны рэжым"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Гук выкл."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Гук уключаны"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Дазваляе праграме працягваць выклік, які пачаўся ў іншай праграме."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"счытваць нумары тэлефонаў"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Дазваляе праграме атрымліваць доступ да нумароў тэлефонаў на прыладзе."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"пакідаць экран аўтамабіля ўключаным"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"прадухіліць планшэт ад пераходу ў рэжым сну"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"прадухіляць пераход прылады Android TV у рэжым сну"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"забараняць тэлефону пераходзіць ў рэжым сну"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Дазваляе праграме пакідаць экран аўтамабіля ўключаным."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Дазваляе прыкладанням прадухіляць пераход планшэта ў рэжым сну."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Дазваляе праграме прадухіляць пераход прылады Android TV у рэжым сну."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Дазваляе прыкладанням прадухіляць тэлефон ад пераходу ў рэжым сну."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Павялiчыць гук вышэй рэкамендаванага ўзроўню?\n\nДоўгае праслухоўванне музыкi на вялiкай гучнасцi можа пашкодзiць ваш слых."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Выкарыстоўваць камбінацыю хуткага доступу для спецыяльных магчымасцей?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Калі хуткі доступ уключаны, вы можаце націснуць абедзве кнопкі гучнасці і ўтрымліваць іх 3 секунды, каб запусціць функцыю спецыяльных магчымасцей."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Змяніць ярлыкі"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Скасаваць"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Дэактываваць камбінацыю хуткага доступу"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Некатэгарызаванае"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Вы задалі важнасць гэтых апавяшчэнняў."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Гэта важна, бо з гэтым звязаны пэўныя людзі."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Апавяшчэнне пра карыстальніцкую праграму"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Дазволіць праграме \"<xliff:g id="APP">%1$s</xliff:g>\" стварыць новага Карыстальніка з уліковым запісам <xliff:g id="ACCOUNT">%2$s</xliff:g> (Карыстальнік з гэтым уліковым запісам ужо існуе)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Дазволіць праграме \"<xliff:g id="APP">%1$s</xliff:g>\" стварыць новага Карыстальніка з уліковым запісам <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Дадаць мову"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Пакет \"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>\" дададзены ў АБМЕЖАВАНУЮ групу"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Асабістыя"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Працоўныя"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Не ўдалося абагуліць з працоўнымі праграмамі"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Не ўдалося абагуліць з асабістымі праграмамі"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Ваш ІТ-адміністратар заблакіраваў абагульванне паміж асабістымі і працоўнымі праграмамі"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Уключыце працоўныя праграмы"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Уключыце працоўныя праграмы, каб мець доступ да іх і да кантактаў"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Няма даступных праграм"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Нам не ўдалося знайсці ніводнай праграмы"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Пераключыцца на працоўны профіль"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Запісваць або прайграваць аўдыя ў тэлефонных выкліках"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Дазваляе гэтай праграме (калі яна наладжана ў якасці стандартнага набіральніка нумара) запісваць або прайграваць аўдыя ў тэлефонных выкліках."</string>
</resources>
diff --git a/core/res/res/values-bg/strings.xml b/core/res/res/values-bg/strings.xml
index 33e59aa..d683062 100644
--- a/core/res/res/values-bg/strings.xml
+++ b/core/res/res/values-bg/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Екранната снимка за сигнала за програмна грешка ще бъде направена след <xliff:g id="NUMBER_1">%d</xliff:g> секунди.</item>
<item quantity="one">Екранната снимка за сигнала за програмна грешка ще бъде направена след <xliff:g id="NUMBER_0">%d</xliff:g> секунда.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Екранната снимка със сигнал за програмна грешка бе направена"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Правенето на екранна снимка със сигнал за програмна грешка не бе успешно"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Тих режим"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Звукът е ИЗКЛЮЧЕН"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Звукът е ВКЛЮЧЕН"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Разрешава на приложението да продължи обаждане, стартирано в друго приложение."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"четене на телефонните номера"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Разрешава на приложението да осъществява достъп до телефонните номера на устройството."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"постоянно включен екран на автомобила"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"предотвратяване на спящия режим на таблета"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"предотвратяване на активирането на спящия режим на устройството ви с Android TV"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"предотвратява спящ режим на телефона"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Дава възможност на приложението да поддържа екрана на автомобила включен."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Разрешава на приложението да предотвратява преминаването на таблета в спящ режим."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Дава възможност на приложението да предотвратява преминаването в спящ режим на устройството ви с Android TV."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Разрешава на приложението да предотвратява преминаването на телефона в спящ режим."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Да се увеличи ли силата на звука над препоръчителното ниво?\n\nПродължителното слушане при висока сила на звука може да увреди слуха ви."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Искате ли да използвате пряк път към функцията за достъпност?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Когато прекият път е включен, можете да стартирате дадена функция за достъпност, като натиснете двата бутона за силата на звука и ги задържите за 3 секунди."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Редактиране на преките пътища"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Отказ"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Изключване на прекия път"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Некатегоризирани"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Зададохте важността на тези известия."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Това е важно заради участващите хора."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Персонализирано известие за приложение"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Да се разреши ли на <xliff:g id="APP">%1$s</xliff:g> да създаде нов потребител с профила <xliff:g id="ACCOUNT">%2$s</xliff:g> (вече съществува потребител с този профил)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Да се разреши ли на <xliff:g id="APP">%1$s</xliff:g> да създаде нов потребител с профила <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Добавяне на език"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Пакетът <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> е поставен в ОГРАНИЧЕНИЯ контейнер"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Лични"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Служебни"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Споделянето със служебни приложения не е възможно"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Споделянето с лични приложения не е възможно"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Системният ви администратор е блокирал споделянето между лични и служебни приложения"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Включете служебните приложения"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Включете служебните приложения, за да имате достъп до тях и служебните контакти"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Няма приложения"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Не успяхме да намерим приложения"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Включване на служебния потребителски профил"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Записване или възпроизвеждане на аудио при телефонни обаждания"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Дава възможност на това приложение да записва или възпроизвежда аудио при телефонни обаждания, когато е зададено като основно приложение за набиране."</string>
</resources>
diff --git a/core/res/res/values-bn/strings.xml b/core/res/res/values-bn/strings.xml
index 386c303..8994e86 100644
--- a/core/res/res/values-bn/strings.xml
+++ b/core/res/res/values-bn/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one"><xliff:g id="NUMBER_1">%d</xliff:g> সেকেন্ডের মধ্যে ত্রুটির প্রতিবেদনের জন্য স্ক্রিনশট নেওয়া হচ্ছে৷</item>
<item quantity="other"><xliff:g id="NUMBER_1">%d</xliff:g> সেকেন্ডের মধ্যে ত্রুটির প্রতিবেদনের জন্য স্ক্রিনশট নেওয়া হচ্ছে৷</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"সমস্যা সংক্রান্ত রিপোর্টের স্ক্রিনশট নেওয়া হয়েছে"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"সমস্যার সংক্রান্ত রিপোর্টের স্ক্রিনশট নেওয়া যায়নি"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"নীরব মোড"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"শব্দ বন্ধ করা আছে"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"শব্দ চালু করা আছে"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"অন্য কোনও অ্যাপ দিয়ে কল করলে এই অ্যাপটিকে সেটি চালিয়ে যেতে দেয়।"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ফোন নম্বরগুলি পড়া হোক"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"অ্যাপটিকে এই ডিভাইসের ফোন নম্বরগুলি অ্যাক্সেস করতে দেয়।"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"গাড়ির স্ক্রিন চালু রাখা আছে"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ঘুমানো থেকে ট্যাবলেটকে প্রতিরোধ করে"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"আপনার Android TV ডিভাইসকে স্লিপ মোডে চলে যাওয়া থেকে আটকান"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ঘুমানো থেকে ফোনটিকে প্রতিরোধ করে"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"গাড়ির স্ক্রিন চালু রাখতে অ্যাপকে অনুমতি দেয়।"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"অ্যাপ্লিকেশানকে ট্যাবলেট নিদ্রায় যাওয়া থেকে প্রতিরোধ করার মঞ্জুরি দেয়৷"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"অ্যাপটিকে আপনার Android TV ডিভাইস স্লিপ মোডে চলে যাওয়া থেকে আটকানোর অনুমতি দেয়।"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"অ্যাপ্লিকেশানকে ফোনকে নিদ্রায় যাওয়া থেকে প্রতিরোধ করার মঞ্জুরি দেয়৷"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"প্রস্তাবিত স্তরের চেয়ে বেশি উঁচুতে ভলিউম বাড়াবেন?\n\nউঁচু ভলিউমে বেশি সময় ধরে কিছু শুনলে আপনার শ্রবনশক্তির ক্ষতি হতে পারে।"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"অ্যাক্সেসযোগ্যতা শর্টকাট ব্যবহার করবেন?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"শর্টকাট চালু করা থাকাকালীন দুটি ভলিউম বোতাম একসাথে ৩ সেকেন্ড টিপে ধরে রাখলে একটি অ্যাকসেসিবিলিটি ফিচার চালু হবে।"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"শর্টকাট এডিট করুন"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"বাতিল করুন"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"শর্টকাট বন্ধ করুন"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> সীমাবদ্ধ গ্রুপে অন্তর্ভুক্ত করা হয়েছে"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ব্যক্তিগত"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"অফিস"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"অফিস অ্যাপের সাথে শেয়ার করা যাচ্ছে না"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ব্যক্তিগত অ্যাপের সাথে শেয়ার করা যাচ্ছে না"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"আপনার IT অ্যাডমিন ব্যক্তিগত ও অফিস অ্যাপের মধ্যে শেয়ার করা ব্লক করে রেখেছেন"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"অফিসের অ্যাপ চালু করুন"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"অফিসের অ্যাপ ও পরিচিতি অ্যাক্সেস করার জন্য অফিসের অ্যাপ চালু করুন"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"কোনও অ্যাপ উপলভ্য নেই"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"কোনও অ্যাপ খুঁজে পাওয়া যায়নি"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"অফিস প্রোফাইল চালু করুন"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"টেলিফোন কলে অডিও রেকর্ড বা প্লে করুন"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ডিফল্ট ডায়ালার অ্যাপ্লিকেশন হিসেবে বেছে নেওয়া হলে, টেলিফোন কলে অডিও রেকর্ড বা প্লে করার জন্য এই অ্যাপকে অনুমতি দেয়।"</string>
</resources>
diff --git a/core/res/res/values-bs/strings.xml b/core/res/res/values-bs/strings.xml
index 743e8c4..724c1c36 100644
--- a/core/res/res/values-bs/strings.xml
+++ b/core/res/res/values-bs/strings.xml
@@ -252,10 +252,8 @@
<item quantity="few">Snimak ekrana za prijavu greške pravim za <xliff:g id="NUMBER_1">%d</xliff:g> sekunde.</item>
<item quantity="other">Snimak ekrana za prijavu greške pravim za <xliff:g id="NUMBER_1">%d</xliff:g> sekundi.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Napravljen je snimak ekrana s izvještajem o grešci"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Snimanje ekrana s izvještajem o grešci nije uspjelo"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Nečujni način rada"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zvuk je isključen"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zvuk je uključen"</string>
@@ -457,9 +455,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Dozvoljava aplikaciji nastavljanje poziva koji je započet u drugoj aplikaciji."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"čitanje telefonskih brojeva"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Dozvoljava aplikaciji pristup telefonskim brojevima uređaja."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ostavi ekran automobila uključenim"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"sprečavanje tableta da uđe u režim mirovanja"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"sprečavanje stupanja Android TV uređaja u stanje mirovanja"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"sprečavanje telefona da uđe u režim mirovanja"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Dozvoljava aplikaciji da ostavi ekran automobila uključenim."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Dozvoljava aplikaciji da spriječi tablet da ode u stanje mirovanja."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Omogućava aplikaciji da spriječi stupanje Android TV uređaja u stanje mirovanja."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Dozvoljava aplikaciji da spriječi telefon da ode u stanje mirovanja."</string>
@@ -1655,6 +1655,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Želite li pojačati zvuk iznad preporučenog nivoa?\n\nDužim slušanjem glasnog zvuka možete oštetiti sluh."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Želite li koristiti Prečicu za pristupačnost?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kada je prečica uključena, pritiskom i držanjem oba dugmeta za jačinu zvuka u trajanju od 3 sekunde pokrenut će se funkcija pristupačnosti."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Uredi prečice"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Otkaži"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Isključi prečicu"</string>
@@ -1887,8 +1893,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nije kategorizirano"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Vi određujete značaj ovih obavještenja."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ovo je značajno zbog osoba koje su uključene."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Prilagođeno obavještenje aplikacije"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Dozvoliti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da kreira novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik s ovim računom već postoji)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Dozvoliti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da kreira novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dodajte jezik"</string>
@@ -2064,14 +2069,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Paket <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> je stavljen u odjeljak OGRANIČENO"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Lično"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Posao"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nije moguće dijeliti s poslovnim aplikacijama"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nije moguće dijeliti s ličnim aplikacijama"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Vaš IT administrator je blokirao dijeljenje između ličnih i poslovnih aplikacija"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Uključite poslovne aplikacije"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Uključite poslovne aplikacije da pristupite poslovnim aplikacijama i kontaktima"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nema dostupnih aplikacija"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nismo pronašli nijednu aplikaciju"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Prebaci na radni"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Snimanje ili reproduciranje zvuka u telefonskim pozivima"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Kad je ova aplikacija postavljena kao zadana aplikacija za pozivanje, omogućava joj snimanje ili reproduciranje zvuka u telefonskim pozivima."</string>
</resources>
diff --git a/core/res/res/values-ca/strings.xml b/core/res/res/values-ca/strings.xml
index 481cafd..f3d8c36 100644
--- a/core/res/res/values-ca/strings.xml
+++ b/core/res/res/values-ca/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Es farà una captura de pantalla de l\'informe d\'errors d\'aquí a <xliff:g id="NUMBER_1">%d</xliff:g> segons.</item>
<item quantity="one">Es farà una captura de pantalla de l\'informe d\'errors d\'aquí a <xliff:g id="NUMBER_0">%d</xliff:g> segon.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"S\'ha fet la captura de pantalla amb l\'informe d\'errors"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"No s\'ha pogut fer la captura de pantalla amb l\'informe d\'errors"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mode silenciós"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"So desactivat"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"El so està activat"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permet que l\'aplicació continuï una trucada que s\'havia iniciat en una altra aplicació."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"llegir els números de telèfon"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permet que l\'aplicació accedeixi als números de telèfon del dispositiu."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"mantén la pantalla del cotxe encesa"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"evita que la tauleta entri en mode de repòs"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"evita que el dispositiu Android TV activi el mode en repòs"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"impedir que el telèfon entri en mode de repòs"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permet que l\'aplicació mantingui la pantalla del cotxe encesa."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permet que l\'aplicació impedeixi que la tauleta entri en repòs."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permet que l\'aplicació impedeixi que el dispositiu Android TV entri en repòs."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permet que l\'aplicació impedeixi que el telèfon entri en repòs."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Vols apujar el volum per sobre del nivell recomanat?\n\nSi escoltes música a un volum alt durant períodes llargs, pots danyar-te l\'oïda."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Vols fer servir la drecera d\'accessibilitat?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Si la drecera està activada, prem els dos botons de volum durant 3 segons per iniciar una funció d\'accessibilitat."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edita les dreceres"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancel·la"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desactiva la drecera"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sense classificar"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Has definit la importància d\'aquestes notificacions."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Aquest missatge és important per les persones implicades."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificació d\'aplicació personalitzada"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Concedeixes permís a <xliff:g id="APP">%1$s</xliff:g> per crear un usuari amb el compte <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Ja hi ha un usuari amb aquest compte.)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Concedeixes permís a <xliff:g id="APP">%1$s</xliff:g> per crear un usuari amb el compte <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Afegeix un idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> s\'ha transferit al segment RESTRINGIT"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Feina"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"No es pot compartir amb les aplicacions de treball"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"No es pot compartir amb les aplicacions personals"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"L\'administrador de TI ha bloquejat la compartició entre aplicacions personals i de treball"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activa les aplicacions de treball"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activa les aplicacions de treball per accedir a aquestes aplicacions i als contactes de feina"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No hi ha cap aplicació disponible"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"No hem trobat cap aplicació"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Activa el perfil de treball"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Gravar o reproduir àudio en trucades"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permet que l\'aplicació gravi o reprodueixi àudio en trucades si està assignada com a aplicació de marcador predeterminada."</string>
</resources>
diff --git a/core/res/res/values-cs/strings.xml b/core/res/res/values-cs/strings.xml
index 8594e1f..f4b02f1 100644
--- a/core/res/res/values-cs/strings.xml
+++ b/core/res/res/values-cs/strings.xml
@@ -255,10 +255,8 @@
<item quantity="other">Snímek obrazovky pro zprávu o chybě bude pořízen za <xliff:g id="NUMBER_1">%d</xliff:g> sekund.</item>
<item quantity="one">Snímek obrazovky pro zprávu o chybě bude pořízen za <xliff:g id="NUMBER_0">%d</xliff:g> sekundu.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Se zprávou o chybě byl pořízen snímek obrazovky"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Pořízení snímku obrazovky se zprávou o chybě se nezdařilo"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Tichý režim"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zvuk je VYPNUTÝ."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zvuk je zapnutý"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Umožňuje aplikace pokračovat v hovoru, který byl zahájen v jiné aplikaci."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"přístup k telefonním číslům"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Umožňuje aplikaci přístup k telefonním číslům v zařízení."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ponechání zapnuté obrazovky auta"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"bránění přechodu tabletu do režimu spánku"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"bránění přechodu zařízení Android TV do režimu spánku"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"bránění přechodu telefonu do režimu spánku"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Umožňuje aplikaci nechat obrazovku auta zapnutou."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Umožňuje aplikaci zabránit přechodu tabletu do režimu spánku."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Umožňuje aplikaci zabránit přechodu zařízení Android TV do režimu spánku."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Umožňuje aplikaci zabránit přechodu telefonu do režimu spánku."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Zvýšit hlasitost nad doporučenou úroveň?\n\nDlouhodobý poslech hlasitého zvuku může poškodit sluch."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Použít zkratku přístupnosti?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Když je tato zkratka zapnutá, můžete funkci přístupnosti spustit tím, že na tři sekundy podržíte obě tlačítka hlasitosti."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Upravit zkratky"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Zrušit"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Vypnout zkratku"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Neklasifikováno"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Důležitost oznámení určujete vy."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Tato zpráva je důležitá kvůli lidem zapojeným do konverzace."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Vlastní oznámení aplikace"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Povolit aplikaci <xliff:g id="APP">%1$s</xliff:g> vytvořit nového uživatele s účtem <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Uživatel s tímto účtem již existuje.)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Povolit aplikaci <xliff:g id="APP">%1$s</xliff:g> vytvořit nového uživatele s účtem <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Přidat jazyk"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Balíček <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> byl vložen do sekce OMEZENO"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Osobní"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Pracovní"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Sdílení s pracovními aplikacemi je zakázáno"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Sdílení s osobními aplikacemi je zakázáno"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Sdílení mezi osobními a pracovními aplikacemi zablokoval váš administrátor IT"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Zapnout pracovní aplikace"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Zapnutím pracovních aplikací získáte přístup k pracovním aplikacím a kontaktům"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Žádné aplikace k dispozici"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nenalezli jsme žádné aplikace"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Zapnout práci"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Záznam a přehrávání zvuků při telefonických hovorech"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Pokud aplikace bude mít toto oprávnění a bude vybrána jako výchozí aplikace pro vytáčení, bude při telefonických hovorech moci přehrávat a zaznamenávat zvuky."</string>
</resources>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index 617bc88..47fd69d 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Der tages et screenshot til fejlrapporten om <xliff:g id="NUMBER_1">%d</xliff:g> sekund.</item>
<item quantity="other">Der tages et screenshot til fejlrapporten om <xliff:g id="NUMBER_1">%d</xliff:g> sekunder.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Der er taget et screenshot af fejlrapporten"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Der kunne ikke tages et screenshot af fejlrapporten"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Lydløs"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Lyden er slået FRA"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Lyden er TIL"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Tillader, at appen fortsætter et opkald, der blev startet i en anden app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"læse telefonnumre"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Tillader, at appen får adgang til telefonnumrene på denne enhed."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"hold bilens skærm tændt"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"afholde tabletcomputeren fra at gå i dvale"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"undgå, at din Android TV-enhed ikke går i dvale"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"afholde telefonen fra at gå i dvale"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Tillader, at appen holder bilens skærm tændt."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Tillader, at appen kan forhindre tabletten i at gå i dvale."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Tillader, at appen kan forhindre din Android TV-enhed i at gå i dvale."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Tillader, at appen kan forhindre, at telefonen går i dvale."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Vil du skrue højere op end det anbefalede lydstyrkeniveau?\n\nDu kan skade hørelsen ved at lytte til meget høj musik over længere tid."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Vil du bruge genvejen til Hjælpefunktioner?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Når genvejen er aktiveret, kan du starte en hjælpefunktion ved at trykke på begge lydstyrkeknapper i tre sekunder."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Rediger genveje"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Annuller"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Deaktiver genvej"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uden kategori"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Du angiver, hvor vigtige disse notifikationer er."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Dette er vigtigt på grund af de personer, det handler om."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Tilpasset appnotifikation"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Vil du give <xliff:g id="APP">%1$s</xliff:g> tilladelse til at oprette en ny bruger med <xliff:g id="ACCOUNT">%2$s</xliff:g> (der findes allerede en bruger med denne konto)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Vil du give <xliff:g id="APP">%1$s</xliff:g> tilladelse til at oprette en nye bruger med <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Tilføj et sprog"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> er blevet placeret i samlingen BEGRÆNSET"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personlig"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Arbejde"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Der kan ikke deles med arbejdsapps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Der kan ikke deles med personlige apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Din it-administrator har blokeret deling mellem personlige apps og arbejdsapps"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Aktivér arbejdsapps"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Aktivér arbejdsapps for at få adgang til arbejdsapps og -kontakter"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Ingen tilgængelige apps"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Vi kunne ikke finde nogen apps"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Aktivér arbejdsprofil"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Optage eller afspille lyd i telefonopkald"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Tillader, at denne app kan optage og afspille lyd i telefonopkald, når den er angivet som standardapp til opkald."</string>
</resources>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index f211b40..d61d961 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Screenshot für den Fehlerbericht wird in <xliff:g id="NUMBER_1">%d</xliff:g> Sekunden aufgenommen.</item>
<item quantity="one">Screenshot für den Fehlerbericht wird in <xliff:g id="NUMBER_0">%d</xliff:g> Sekunde aufgenommen.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Screenshot mit Fehlerbericht erstellt"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Fehler beim Erstellen eines Screenshots mit Fehlerbericht"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Lautlos-Modus"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Ton ist AUS."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Ton ist AN."</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Ermöglicht der App, einen Anruf weiterzuführen, der in einer anderen App begonnen wurde."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"Telefonnummern vorlesen"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Ermöglicht der App, auf die Telefonnummern auf dem Gerät zuzugreifen."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"Autodisplay eingeschaltet lassen"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"Ruhezustand des Tablets deaktivieren"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV-Gerät daran hindern, in den Ruhemodus zu wechseln"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"Ruhezustand deaktivieren"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Ermöglicht der App, das Autodisplay eingeschaltet zu lassen."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Ermöglicht der App, den Ruhezustand des Tablets zu deaktivieren"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Ermöglicht der App zu verhindern, dass das Android TV-Gerät in den Ruhemodus wechselt."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Ermöglicht der App, den Ruhezustand des Telefons zu deaktivieren"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Lautstärke über den Schwellenwert anheben?\n\nWenn du über einen längeren Zeitraum Musik in hoher Lautstärke hörst, kann dies dein Gehör schädigen."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Verknüpfung für Bedienungshilfen verwenden?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Wenn die Verknüpfung aktiviert ist, kannst du die beiden Lautstärketasten drei Sekunden lang gedrückt halten, um eine Bedienungshilfe zu starten."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Verknüpfungen bearbeiten"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Abbrechen"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Verknüpfung deaktivieren"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> wurde in den BESCHRÄNKT-Bucket gelegt"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Privat"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Geschäftlich"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Teilen mit geschäftlichen Apps nicht möglich"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Teilen mit privaten Apps nicht möglich"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Dein IT-Administrator lässt das Teilen zwischen privaten und geschäftlichen Apps nicht zu"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Geschäftliche Apps aktivieren"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Für Zugriff auf geschäftliche Apps und Kontakte geschäftliche Apps aktivieren"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Keine Apps verfügbar"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Keine Apps gefunden"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Arbeitsprofil aktivieren"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Audio bei Telefonanrufen aufnehmen oder wiedergeben"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Ermöglicht dieser App das Aufnehmen und Wiedergeben von Audio bei Telefonanrufen, wenn sie als Standard-Telefon-App festgelegt wurde."</string>
</resources>
diff --git a/core/res/res/values-el/strings.xml b/core/res/res/values-el/strings.xml
index c915bba..16daec8 100644
--- a/core/res/res/values-el/strings.xml
+++ b/core/res/res/values-el/strings.xml
@@ -452,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Επιτρέπει στην εφαρμογή να συνεχίσει μια κλήση η οποία ξεκίνησε σε άλλη εφαρμογή."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ανάγνωση αριθμών τηλεφώνου"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Επιτρέπει στην εφαρμογή να αποκτήσει πρόσβαση στους αριθμούς τηλεφώνου της συσκευής"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"διατήρηση ενεργοποίησης οθόνης αυτοκινήτου"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"αποτρέπει την μετάβαση του tablet σε κατάσταση αδράνειας"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"απαγόρευση μετάβασης της συσκευής Android TV σε κατάσταση αδράνειας"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"αποτρέπει το τηλεφώνο να μεταβεί σε κατάσταση αδράνειας"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Επιτρέπει στην εφαρμογή να διατηρεί την οθόνη του αυτοκινήτου ενεργοποιημένη."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Επιτρέπει στην εφαρμογή την παρεμπόδιση της μετάβασης του tablet σε κατάσταση αδράνειας."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Επιτρέπει στην εφαρμογή να εμποδίζει τη μετάβαση της συσκευής Android TV σε κατάσταση αδράνειας."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Επιτρέπει στην εφαρμογή την παρεμπόδιση της μετάβασης του τηλεφώνου σε κατάσταση αδράνειας."</string>
@@ -1629,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Αυξάνετε την ένταση ήχου πάνω από το επίπεδο ασφαλείας;\n\nΑν ακούτε μουσική σε υψηλή ένταση για μεγάλο χρονικό διάστημα ενδέχεται να προκληθεί βλάβη στην ακοή σας."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Να χρησιμοποιείται η συντόμευση προσβασιμότητας;"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Όταν η συντόμευση είναι ενεργοποιημένη, το πάτημα και των δύο κουμπιών έντασης ήχου για 3 δευτερόλεπτα θα ξεκινήσει μια λειτουργία προσβασιμότητας."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Επεξεργασία συντομεύσεων"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Άκυρο"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Απενεργοποίηση συντόμευσης"</string>
@@ -1851,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Μη κατηγοριοποιημένο"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Μπορείτε να ρυθμίσετε τη βαρύτητα αυτών των ειδοποιήσεων."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Αυτό είναι σημαντικό λόγω των ατόμων που συμμετέχουν."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Προσαρμοσμένη ειδοποίηση εφαρμογής"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Επιτρέπετε στην εφαρμογή <xliff:g id="APP">%1$s</xliff:g> να δημιουργήσει έναν νέο χρήστη με τον λογαριασμό <xliff:g id="ACCOUNT">%2$s</xliff:g> (υπάρχει ήδη χρήστης με αυτόν τον λογαριασμό);"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Επιτρέπετε στην εφαρμογή <xliff:g id="APP">%1$s</xliff:g> να δημιουργήσει έναν νέο χρήστη με τον λογαριασμό <xliff:g id="ACCOUNT">%2$s</xliff:g>;"</string>
<string name="language_selection_title" msgid="52674936078683285">"Προσθήκη γλώσσας"</string>
@@ -2026,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Το πακέτο <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> τοποθετήθηκε στον κάδο ΠΕΡΙΟΡΙΣΜΕΝΗΣ ΠΡΟΣΒΑΣΗΣ."</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Προσωπικό"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Εργασία"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Δεν είναι δυνατή η κοινοποίηση σε εφαρμογές εργασιών"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Δεν είναι δυνατή η κοινοποίηση σε προσωπικές εφαρμογές"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Ο διαχειριστής IT απέκλεισε την κοινοποίηση μεταξύ των προσωπικών εφαρμογών και των εφαρμογών εργασιών σας"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ενεργοποίηση εφαρμογών εργασιών"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ενεργοποίηση εφαρμογών εργασιών για πρόσβαση στις εφαρμογές εργασιών και τις επαφές"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Δεν υπάρχουν διαθέσιμες εφαρμογές"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Δεν ήταν δυνατή η εύρεση εφαρμογών"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Διακόπτης ενεργοποίησης προφίλ εργασίας"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Εγγραφή ή αναπαραγωγή ήχου σε τηλεφωνικές κλήσεις"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Επιτρέπει σε αυτήν την εφαρμογή, όταν ορίζεται ως προεπιλεγμένη εφαρμογή κλήσης, να εγγράφει ή να αναπαράγει ήχο σε τηλεφωνικές κλήσεις."</string>
</resources>
diff --git a/core/res/res/values-en-rAU/strings.xml b/core/res/res/values-en-rAU/strings.xml
index c5259fd..c8e03c6 100644
--- a/core/res/res/values-en-rAU/strings.xml
+++ b/core/res/res/values-en-rAU/strings.xml
@@ -452,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Allows the app to continue a call which was started in another app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"read phone numbers"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Allows the app to access the phone numbers of the device."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"keep car screen turned on"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"prevent tablet from sleeping"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"prevent your Android TV device from sleeping"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"prevent phone from sleeping"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Allows the app to keep the car screen turned on."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Allows the app to prevent the tablet from going to sleep."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Allows the app to prevent your Android TV device from going to sleep."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Allows the app to prevent the phone from going to sleep."</string>
@@ -1629,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Raise volume above recommended level?\n\nListening at high volume for long periods may damage your hearing."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Use Accessibility Shortcut?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"When the shortcut is on, pressing both volume buttons for three seconds will start an accessibility feature."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Tap the accessibility app that you want to use"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Choose apps that you want to use with Accessibility button"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Choose apps that you want to use with volume key shortcut"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit shortcuts"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancel"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Turn off Shortcut"</string>
@@ -1851,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uncategorised"</string>
<string name="importance_from_user" msgid="2782756722448800447">"You set the importance of these notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"This is important because of the people involved."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Custom app notification"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Add a language"</string>
@@ -2026,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> has been put into the RESTRICTED bucket"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Work"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Personal view"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Work view"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Can’t share with work apps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Can’t share with personal apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Your IT admin blocked sharing between personal and work apps"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Turn on work apps"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Turn on work apps to access work apps and contacts"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Your IT admin blocked sharing between personal and work profiles"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Can’t access work apps"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Your IT admin doesn’t let you view personal content in work apps"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Can’t access personal apps"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Your IT admin doesn’t let you view work content in personal apps"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Turn on work profile to share content"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Turn on work profile to view content"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No apps available"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"We couldn’t find any apps"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Switch on work"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Turn on"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Record or play audio in telephony calls"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Allows this app, when assigned as a default dialler application, to record or play audio in telephony calls."</string>
</resources>
diff --git a/core/res/res/values-en-rCA/strings.xml b/core/res/res/values-en-rCA/strings.xml
index 78db758..07d1862 100644
--- a/core/res/res/values-en-rCA/strings.xml
+++ b/core/res/res/values-en-rCA/strings.xml
@@ -452,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Allows the app to continue a call which was started in another app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"read phone numbers"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Allows the app to access the phone numbers of the device."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"keep car screen turned on"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"prevent tablet from sleeping"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"prevent your Android TV device from sleeping"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"prevent phone from sleeping"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Allows the app to keep the car screen turned on."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Allows the app to prevent the tablet from going to sleep."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Allows the app to prevent your Android TV device from going to sleep."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Allows the app to prevent the phone from going to sleep."</string>
@@ -1629,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Raise volume above recommended level?\n\nListening at high volume for long periods may damage your hearing."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Use Accessibility Shortcut?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"When the shortcut is on, pressing both volume buttons for three seconds will start an accessibility feature."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Tap the accessibility app that you want to use"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Choose apps that you want to use with Accessibility button"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Choose apps that you want to use with volume key shortcut"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit shortcuts"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancel"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Turn off Shortcut"</string>
@@ -1851,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uncategorised"</string>
<string name="importance_from_user" msgid="2782756722448800447">"You set the importance of these notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"This is important because of the people involved."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Custom app notification"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Add a language"</string>
@@ -2026,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> has been put into the RESTRICTED bucket"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Work"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Personal view"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Work view"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Can’t share with work apps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Can’t share with personal apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Your IT admin blocked sharing between personal and work apps"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Turn on work apps"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Turn on work apps to access work apps and contacts"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Your IT admin blocked sharing between personal and work profiles"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Can’t access work apps"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Your IT admin doesn’t let you view personal content in work apps"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Can’t access personal apps"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Your IT admin doesn’t let you view work content in personal apps"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Turn on work profile to share content"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Turn on work profile to view content"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No apps available"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"We couldn’t find any apps"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Switch on work"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Turn on"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Record or play audio in telephony calls"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Allows this app, when assigned as a default dialler application, to record or play audio in telephony calls."</string>
</resources>
diff --git a/core/res/res/values-en-rGB/strings.xml b/core/res/res/values-en-rGB/strings.xml
index c5259fd..c8e03c6 100644
--- a/core/res/res/values-en-rGB/strings.xml
+++ b/core/res/res/values-en-rGB/strings.xml
@@ -452,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Allows the app to continue a call which was started in another app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"read phone numbers"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Allows the app to access the phone numbers of the device."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"keep car screen turned on"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"prevent tablet from sleeping"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"prevent your Android TV device from sleeping"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"prevent phone from sleeping"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Allows the app to keep the car screen turned on."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Allows the app to prevent the tablet from going to sleep."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Allows the app to prevent your Android TV device from going to sleep."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Allows the app to prevent the phone from going to sleep."</string>
@@ -1629,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Raise volume above recommended level?\n\nListening at high volume for long periods may damage your hearing."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Use Accessibility Shortcut?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"When the shortcut is on, pressing both volume buttons for three seconds will start an accessibility feature."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Tap the accessibility app that you want to use"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Choose apps that you want to use with Accessibility button"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Choose apps that you want to use with volume key shortcut"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit shortcuts"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancel"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Turn off Shortcut"</string>
@@ -1851,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uncategorised"</string>
<string name="importance_from_user" msgid="2782756722448800447">"You set the importance of these notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"This is important because of the people involved."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Custom app notification"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Add a language"</string>
@@ -2026,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> has been put into the RESTRICTED bucket"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Work"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Personal view"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Work view"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Can’t share with work apps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Can’t share with personal apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Your IT admin blocked sharing between personal and work apps"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Turn on work apps"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Turn on work apps to access work apps and contacts"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Your IT admin blocked sharing between personal and work profiles"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Can’t access work apps"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Your IT admin doesn’t let you view personal content in work apps"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Can’t access personal apps"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Your IT admin doesn’t let you view work content in personal apps"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Turn on work profile to share content"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Turn on work profile to view content"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No apps available"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"We couldn’t find any apps"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Switch on work"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Turn on"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Record or play audio in telephony calls"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Allows this app, when assigned as a default dialler application, to record or play audio in telephony calls."</string>
</resources>
diff --git a/core/res/res/values-en-rIN/strings.xml b/core/res/res/values-en-rIN/strings.xml
index c5259fd..c8e03c6 100644
--- a/core/res/res/values-en-rIN/strings.xml
+++ b/core/res/res/values-en-rIN/strings.xml
@@ -452,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Allows the app to continue a call which was started in another app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"read phone numbers"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Allows the app to access the phone numbers of the device."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"keep car screen turned on"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"prevent tablet from sleeping"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"prevent your Android TV device from sleeping"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"prevent phone from sleeping"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Allows the app to keep the car screen turned on."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Allows the app to prevent the tablet from going to sleep."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Allows the app to prevent your Android TV device from going to sleep."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Allows the app to prevent the phone from going to sleep."</string>
@@ -1629,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Raise volume above recommended level?\n\nListening at high volume for long periods may damage your hearing."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Use Accessibility Shortcut?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"When the shortcut is on, pressing both volume buttons for three seconds will start an accessibility feature."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Tap the accessibility app that you want to use"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Choose apps that you want to use with Accessibility button"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Choose apps that you want to use with volume key shortcut"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit shortcuts"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancel"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Turn off Shortcut"</string>
@@ -1851,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uncategorised"</string>
<string name="importance_from_user" msgid="2782756722448800447">"You set the importance of these notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"This is important because of the people involved."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Custom app notification"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Add a language"</string>
@@ -2026,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> has been put into the RESTRICTED bucket"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Work"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Personal view"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Work view"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Can’t share with work apps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Can’t share with personal apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Your IT admin blocked sharing between personal and work apps"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Turn on work apps"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Turn on work apps to access work apps and contacts"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Your IT admin blocked sharing between personal and work profiles"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Can’t access work apps"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Your IT admin doesn’t let you view personal content in work apps"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Can’t access personal apps"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Your IT admin doesn’t let you view work content in personal apps"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Turn on work profile to share content"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Turn on work profile to view content"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No apps available"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"We couldn’t find any apps"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Switch on work"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Turn on"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Record or play audio in telephony calls"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Allows this app, when assigned as a default dialler application, to record or play audio in telephony calls."</string>
</resources>
diff --git a/core/res/res/values-en-rXC/strings.xml b/core/res/res/values-en-rXC/strings.xml
index eb54653..c30c10e 100644
--- a/core/res/res/values-en-rXC/strings.xml
+++ b/core/res/res/values-en-rXC/strings.xml
@@ -452,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Allows the app to continue a call which was started in another app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"read phone numbers"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Allows the app to access the phone numbers of the device."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"keep car screen turned on"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"prevent tablet from sleeping"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"prevent your Android TV device from sleeping"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"prevent phone from sleeping"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Allows the app to keep the car screen turned on."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Allows the app to prevent the tablet from going to sleep."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Allows the app to prevent your Android TV device from going to sleep."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Allows the app to prevent the phone from going to sleep."</string>
@@ -1629,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Raise volume above recommended level?\n\nListening at high volume for long periods may damage your hearing."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Use Accessibility Shortcut?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"When the shortcut is on, pressing both volume buttons for 3 seconds will start an accessibility feature."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Tap the accessibility app you want to use"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Choose apps you want to use with accessibility button"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Choose apps you want to use with volume key shortcut"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit shortcuts"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancel"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Turn off Shortcut"</string>
@@ -1851,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uncategorized"</string>
<string name="importance_from_user" msgid="2782756722448800447">"You set the importance of these notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"This is important because of the people involved."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Custom app notification"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> (a User with this account already exists) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Allow <xliff:g id="APP">%1$s</xliff:g> to create a new User with <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Add a language"</string>
@@ -2026,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> has been put into the RESTRICTED bucket"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Work"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Personal view"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Work view"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Can’t share with work apps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Can’t share with personal apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Your IT admin blocked sharing between personal and work apps"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Turn on work apps"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Turn on work apps to access work apps & contacts"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Your IT admin blocked sharing between personal and work profiles"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Can’t access work apps"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Your IT admin doesn’t let you view personal content in work apps"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Can’t access personal apps"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Your IT admin doesn’t let you view work content in personal apps"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Turn on work profile to share content"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Turn on work profile to view content"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No apps available"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"We couldn’t find any apps"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Switch on work"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Turn on"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Record or play audio in telephony calls"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Allows this app, when assigned as default dialer application, to record or play audio in telephony calls."</string>
</resources>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index 7933f68..af4b577 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Se tomará una captura de pantalla para el informe de errores en <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
<item quantity="one">Se tomará una captura de pantalla para el informe de errores en <xliff:g id="NUMBER_0">%d</xliff:g> segundo.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Se tomó la captura de pantalla con el informe de errores"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"No se pudo tomar la captura de pantalla con el informe de errores"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modo silencioso"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"El sonido está Desactivado"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"El sonido está Activado"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite que la app continúe con una llamada que se inició en otra app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"leer números de teléfono"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Le permite a la app acceder a los números de teléfono del dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"mantener la pantalla del vehículo encendida"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"evitar que el tablet entre en estado de inactividad"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"evita que se suspenda el dispositivo Android TV"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"evitar que el dispositivo entre en estado de inactividad"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite que la app mantenga la pantalla del vehículo encendida."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite que la aplicación evite que la tablet entre en estado de inactividad."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite que la app evite que se suspenda tu dispositivo Android TV."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite que la aplicación evite que el dispositivo entre en estado de inactividad."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"¿Quieres subir el volumen por encima del nivel recomendado?\n\nEscuchar a un alto volumen durante largos períodos puede dañar tu audición."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"¿Usar acceso directo de accesibilidad?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Cuando la combinación de teclas está activada, puedes presionar los botones de volumen durante 3 segundos para iniciar una función de accesibilidad."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editar accesos directos"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancelar"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desactivar acceso directo"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sin categoría"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Estableciste la importancia de estas notificaciones."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Es importante debido a las personas involucradas."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificación de app personalizada"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"¿Quieres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario nuevo con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Ya existe un usuario con esta cuenta)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"¿Deseas permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario nuevo con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Agregar un idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Se colocó <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> en el depósito RESTRICTED"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Trabajo"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"No se puede compartir con apps de trabajo"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"No se puede compartir con apps personales"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Tu administrador de TI bloqueó el uso compartido entre las apps personales y de trabajo"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activa las apps de trabajo"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activa las apps de trabajo para acceder a apps y contactos de trabajo"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No hay apps disponibles"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"No se pudo encontrar ninguna app"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Activar perfil de trabajo"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Graba o reproduce audio en llamadas de telefonía"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permite que esta app grabe o reproduzca audio en llamadas de telefonía cuando se la asigna como aplicación de teléfono predeterminada."</string>
</resources>
diff --git a/core/res/res/values-es/strings.xml b/core/res/res/values-es/strings.xml
index 7bbfcae..518b132 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">La captura de pantalla para el informe de errores se realizará en <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
<item quantity="one">La captura de pantalla para el informe de errores se realizará en <xliff:g id="NUMBER_0">%d</xliff:g> segundo.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Se ha hecho la captura de pantalla con el informe de errores"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"No se ha podido hacer la captura de pantalla con el informe de errores"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modo silencio"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"El sonido está desactivado. Activar"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"El sonido está activado. Desactivar"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite que la aplicación continúe una llamada que se ha iniciado en otra aplicación."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"leer números de teléfono"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permite que la aplicación acceda a los números de teléfono del dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"mantener la pantalla del coche encendida"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"impedir que el tablet entre en modo de suspensión"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"evitar que tu dispositivo Android TV entre en modo de suspensión"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"impedir que el teléfono entre en modo de suspensión"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite que la aplicación deje la pantalla del coche encendida."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite que la aplicación impida que el tablet entre en modo de suspensión."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite que la aplicación impida que tu dispositivo Android TV entre en modo de suspensión."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite que la aplicación impida que el teléfono entre en modo de suspensión."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"¿Quieres subir el volumen por encima del nivel recomendado?\n\nEscuchar sonidos fuertes durante mucho tiempo puede dañar los oídos."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"¿Utilizar acceso directo de accesibilidad?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Si el acceso directo está activado, pulsa los dos botones de volumen durante 3 segundos para iniciar una función de accesibilidad."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editar accesos directos"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancelar"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desactivar acceso directo"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sin clasificar"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Tú determinas la importancia de estas notificaciones."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Esto es importante por los usuarios implicados."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificación de aplicación personalizada"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"¿Permitir que <xliff:g id="APP">%1$s</xliff:g> cree otro usuario con la cuenta <xliff:g id="ACCOUNT">%2$s</xliff:g>, que ya tiene uno?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"¿Permitir que <xliff:g id="APP">%1$s</xliff:g> cree otro usuario con la cuenta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Añadir un idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> se ha incluido en el grupo de restringidos"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Trabajo"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"No se puede compartir con las aplicaciones de trabajo"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"No se puede compartir con las aplicaciones personales"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"No se puede compartir contenido entre las aplicaciones personales y las de trabajo porque el administrador de TI ha bloqueado esta función"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activa las aplicaciones de trabajo"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activa las aplicaciones de trabajo para acceder a ellas y a los contactos"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"No hay ninguna aplicación disponible"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"No se ha podido encontrar ninguna aplicación"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Switch on work"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Grabar o reproducir audio en llamadas telefónicas"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permite que la aplicación grabe o reproduzca audio en las llamadas telefónicas si está asignada como aplicación Teléfono predeterminada."</string>
</resources>
diff --git a/core/res/res/values-et/strings.xml b/core/res/res/values-et/strings.xml
index 34f3a6a..a0ccf68 100644
--- a/core/res/res/values-et/strings.xml
+++ b/core/res/res/values-et/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Veaaruande jaoks ekraanipildi jäädvustamine <xliff:g id="NUMBER_1">%d</xliff:g> sekundi pärast.</item>
<item quantity="one">Veaaruande jaoks ekraanipildi jäädvustamine <xliff:g id="NUMBER_0">%d</xliff:g> sekundi pärast.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Veaaruandega koos jäädvustati ekraanipilt"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Ekraanipildi jäädvustamine koos veaaruandega ebaõnnestus"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Hääletu režiim"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Heli on VÄLJAS"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Heli on SEES"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Lubab rakendusel jätkata kõnet, mida alustati teises rakenduses."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lugeda telefoninumbreid"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Rakendusel lubatakse juurde pääseda seadme telefoninumbritele."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"hoida auto ekraani sisselülitatuna"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"tahvelarvuti uinumise vältimine"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"takistada Android TV seadme unerežiimi lülitumist"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"väldi telefoni uinumist"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Lubab rakendusel auto ekraani sisselülitatuna hoida."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Võimaldab rakendusel vältida tahvelarvuti uinumist."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Võimaldab rakendusel takistada Android TV seadme unerežiimi aktiveerumist."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Võimaldab rakendusel vältida telefoni uinumist."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Kas suurendada helitugevuse taset üle soovitatud taseme?\n\nPikaajaline valju helitugevusega kuulamine võib kuulmist kahjustada."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Kas kasutada juurdepääsetavuse otseteed?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kui otsetee on sisse lülitatud, käivitab mõlema helitugevuse nupu kolm sekundit all hoidmine juurdepääsetavuse funktsiooni."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Muuda otseteid"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Tühista"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Lülita otsetee välja"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Kategoriseerimata"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Teie määrasite nende märguannete tähtsuse."</string>
<string name="importance_from_person" msgid="4235804979664465383">"See on tähtis osalevate inimeste tõttu."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Rakenduse kohandatud märguanne"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Kas lubada rakendusel <xliff:g id="APP">%1$s</xliff:g> luua uus kasutaja kontoga <xliff:g id="ACCOUNT">%2$s</xliff:g> (selle kontoga kasutaja on juba olemas)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Kas lubada rakendusel <xliff:g id="APP">%1$s</xliff:g> luua uus kasutaja kontoga <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Keele lisamine"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> on lisatud salve PIIRANGUTEGA"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Isiklik"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Töö"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Töörakendustega ei saa jagada"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Isiklike rakendustega ei saa jagada"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Teie IT-administraator blokeeris isiklike ja töörakenduste vahel jagamise"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Lülita sisse töörakendused"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Lülitage sisse töörakendused, et töörakendustele ja -kontaktidele juurde pääseda"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Ühtegi rakendust pole saadaval"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Me ei leidnud ühtegi rakendust"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Lülita sisse tööprofiil"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Telefonikõnede heli salvestamine ja esitamine"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Kui see rakendus on määratud helistamise vaikerakenduseks, lubatakse sellel salvestada ja esitada telefonikõnede heli."</string>
</resources>
diff --git a/core/res/res/values-eu/strings.xml b/core/res/res/values-eu/strings.xml
index 34cb6fb..047e998 100644
--- a/core/res/res/values-eu/strings.xml
+++ b/core/res/res/values-eu/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Akatsen txostenaren argazkia aterako da <xliff:g id="NUMBER_1">%d</xliff:g> segundo barru.</item>
<item quantity="one">Akatsen txostenaren argazkia aterako da <xliff:g id="NUMBER_0">%d</xliff:g> segundo barru.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Pantaila-argazkia egin da akatsen txostenarekin"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Ezin izan da egin pantaila-argazkia akatsen txostenarekin"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Isilik modua"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Soinua DESAKTIBATUTA dago"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Soinua AKTIBATUTA dago"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Beste aplikazio batean hasitako dei bat jarraitzea baimentzen dio aplikazioari."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"irakurri telefono-zenbakiak"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Gailuaren telefono-zenbakiak atzitzeko baimena ematen die aplikazioei."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"mantendu piztuta autoko pantaila"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"eragotzi tableta inaktibo ezartzea"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV gailua inaktibo ezar dadin eragotzi"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"eragotzi telefonoa inaktibo ezartzea"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Autoko pantaila piztuta mantentzeko baimena ematen dio aplikazioari."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Tableta inaktibo ezartzea galaraztea baimentzen die aplikazioei."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Android TV gailua inaktibo ezartzea eragozteko baimena ematen die aplikazioei."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Telefonoa inaktibo ezartzea galaraztea baimentzen die aplikazioei."</string>
@@ -492,7 +492,7 @@
<string name="permdesc_changeWifiMulticastState" product="tablet" msgid="191079868596433554">"Wi-Fi sarearen bidez gailu guztiei bidalitako paketeak jasotzeko baimena ematen die aplikazioei multidifusio-helbideak erabilita, ez tableta soilik. Multidifusiokoa ez den moduak baino bateria gehiago erabiltzen du."</string>
<string name="permdesc_changeWifiMulticastState" product="tv" msgid="1336952358450652595">"Multidifusio-helbideak erabiliz wifi-sare bateko gailu guztiei (ez bakarrik Android TV gailuari) bidalitako paketeak jasotzeko baimena ematen die aplikazioei. Multidifusiokoa ez den moduak baino bateria gehiago erabiltzen du."</string>
<string name="permdesc_changeWifiMulticastState" product="default" msgid="8296627590220222740">"Wi-Fi sarearen bidez gailu guztiei bidalitako paketeak jasotzeko baimena ematen die aplikazioei multidifusio-helbideak erabilita, ez telefonoa soilik. Multidifusiokoa ez den moduak baino bateria gehiago erabiltzen du."</string>
- <string name="permlab_bluetoothAdmin" msgid="6490373569441946064">"atzitu Bluetooth ezarpenak"</string>
+ <string name="permlab_bluetoothAdmin" msgid="6490373569441946064">"atzitu Bluetooth-aren ezarpenak"</string>
<string name="permdesc_bluetoothAdmin" product="tablet" msgid="5370837055438574863">"Tokiko Bluetooth tableta konfiguratzea eta urruneko gailuak detektatzea eta haiekin parekatzea baimentzen die aplikazioei."</string>
<string name="permdesc_bluetoothAdmin" product="tv" msgid="1623992984547014588">"Android TV gailuan Bluetooth-a konfiguratzeko eta urruneko gailuak hautemateko eta haiekin parekatzeko baimena ematen die aplikazioei."</string>
<string name="permdesc_bluetoothAdmin" product="default" msgid="7381341743021234863">"Tokiko Bluetooth telefonoa konfiguratzea eta urruneko gailuak detektatzea eta haiekin parekatzea baimentzen die aplikazioei."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Bolumena gomendatutako mailatik gora igo nahi duzu?\n\nMusika bolumen handian eta denbora luzez entzuteak entzumena kalte diezazuke."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Erabilerraztasun-lasterbidea erabili nahi duzu?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Lasterbidea aktibatuta dagoenean, bi bolumen-botoiak hiru segundoz sakatuta abiaraziko da erabilerraztasun-eginbidea."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editatu lasterbideak"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Utzi"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desaktibatu lasterbidea"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Kategoriarik gabea"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Zuk ezarri duzu jakinarazpen hauen garrantzia."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Garrantzitsua da eragiten dien pertsonengatik."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Aplikazio-jakinarazpen pertsonalizatua"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="ACCOUNT">%2$s</xliff:g> kontua duen erabiltzailea sortzeko baimena eman nahi diozu <xliff:g id="APP">%1$s</xliff:g> aplikazioari? (Badago kontu hori duen erabiltzaile bat)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="ACCOUNT">%2$s</xliff:g> kontua duen erabiltzailea sortzeko baimena eman nahi diozu <xliff:g id="APP">%1$s</xliff:g> aplikazioari?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Gehitu hizkuntza"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Murriztuen edukiontzian ezarri da <xliff:g id="PACKAGE_NAME">%1$s</xliff:g>"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Pertsonala"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Lanekoa"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ezin da partekatu laneko aplikazioekin"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Ezin da partekatu aplikazio pertsonalekin"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IKT administratzaileak blokeatu egin du edukia aplikazio pertsonalen eta laneko aplikazioen artean partekatzeko aukera"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Aktibatu laneko aplikazioak"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Aktibatu laneko aplikazioak, haiek eta kontaktuak atzitzeko"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Ez dago aplikaziorik erabilgarri"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Ezin izan dugu aurkitu aplikaziorik"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Aktibatu laneko profila"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Grabatu edo erreproduzitu telefono-deietako audioa"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Aplikazio hau markagailu lehenetsia denean, telefono-deietako audioa grabatu edo erreproduzitzeko aukera ematen dio."</string>
</resources>
diff --git a/core/res/res/values-fa/strings.xml b/core/res/res/values-fa/strings.xml
index 472bd0f..f3572dc 100644
--- a/core/res/res/values-fa/strings.xml
+++ b/core/res/res/values-fa/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">تا <xliff:g id="NUMBER_1">%d</xliff:g> ثانیه دیگر عکس صفحهنمایش برای گزارش اشکال گرفته میشود.</item>
<item quantity="other">تا <xliff:g id="NUMBER_1">%d</xliff:g> ثانیه دیگر عکس صفحهنمایش برای گزارش اشکال گرفته میشود.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"نماگرفت با گزارش اشکال گرفته شد"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"نماگرفت با گزارش اشکال گرفته نشد"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"حالت ساکت"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"صدا خاموش است"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"صدا روشن است"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"به برنامه اجازه میدهد تماسی را که در برنامه دیگری شروع شده ادامه دهد."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"خواندن شماره تلفنها"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"به برنامه امکان میدهد به شماره تلفنهای دستگاه دسترسی داشته باشد."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"روشن نگه داشتن صفحهنمایش خودرو"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ممانعت از به خواب رفتن رایانهٔ لوحی"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"مانع از خوابیدن دستگاه Android TV میشود"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ممانعت از به خواب رفتن تلفن"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"به برنامه اجازه میدهد صفحهنمایش خودرو را روشن نگه دارد."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"به برنامه اجازه میدهد تا از غیرفعال شدن رایانهٔ لوحی جلوگیری کند."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"به برنامه اجازه میدهد مانع از بهخواب رفتن دستگاه Android TV شود."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"به برنامه اجازه میدهد تا از غیرفعال شدن تلفن جلوگیری کند."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"میزان صدا را به بالاتر از حد توصیه شده افزایش میدهید؟\n\nگوش دادن به صداهای بلند برای مدت طولانی میتواند به شنواییتان آسیب وارد کند."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"از میانبر دسترسپذیری استفاده شود؟"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"وقتی میانبر روشن باشد، با فشار دادن هردو دکمه صدا بهمدت ۳ ثانیه ویژگی دسترسپذیری فعال میشود."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ویرایش میانبرها"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"لغو"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"خاموش کردن میانبر"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"دستهبندینشده"</string>
<string name="importance_from_user" msgid="2782756722448800447">"شما اهمیت این اعلانها را تنظیم میکنید."</string>
<string name="importance_from_person" msgid="4235804979664465383">"به دلیل افراد درگیر مهم است."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"اعلان برنامه سفارشی"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"به<xliff:g id="APP">%1$s</xliff:g> اجازه میدهید با <xliff:g id="ACCOUNT">%2$s</xliff:g> (کاربری با این حساب درحالحاضر وجود دارد) کاربری جدید ایجاد کند؟"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"به <xliff:g id="APP">%1$s</xliff:g> اجازه میدهید با <xliff:g id="ACCOUNT">%2$s</xliff:g> کاربری جدید ایجاد کند؟"</string>
<string name="language_selection_title" msgid="52674936078683285">"افزودن زبان"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> در سطل «محدودشده» قرار گرفت"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"شخصی"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"کاری"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"همرسانی بااستفاده از «برنامههای کاری» امکانپذیر نیست"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"همرسانی بااستفاده از برنامههای شخصی امکانپذیر نیست"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"سرپرست فناوری اطلاعات شما همرسانی بین برنامههای شخصی و کاری را مسدود کرده است"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"روشن کردن «برنامههای کاری»"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"برای دسترسی به برنامههای کاری و مخاطبین، «برنامههای کاری» را روشن کنید"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"هیچ برنامهای در دسترس نیست"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"هیچ برنامهای پیدا نکردیم"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"فعال کردن نمایه کاری"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ضبط یا پخش صدا در تماسهای تلفنی"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"به این برنامه اجازه میدهد وقتی بهعنوان برنامه شمارهگیر پیشفرض تنظیم شده است، در تماسهای تلفنی صدا ضبط یا پخش کند."</string>
</resources>
diff --git a/core/res/res/values-fi/strings.xml b/core/res/res/values-fi/strings.xml
index 6aa1a9b..a70d9a4 100644
--- a/core/res/res/values-fi/strings.xml
+++ b/core/res/res/values-fi/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Virheraporttiin otetaan kuvakaappaus <xliff:g id="NUMBER_1">%d</xliff:g> sekunnin kuluttua.</item>
<item quantity="one">Virheraporttiin otetaan kuvakaappaus <xliff:g id="NUMBER_0">%d</xliff:g> sekunnin kuluttua.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Kuvakaappaus otettu virheraportin kanssa"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Kuvakaappauksen ottaminen virheraportin kanssa epäonnistui"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Äänetön tila"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Äänet ovat POISSA KÄYTÖSTÄ"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Äänet ovat KÄYTÖSSÄ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Antaa sovelluksen jatkaa puhelua, joka aloitettiin toisessa sovelluksessa."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lukea puhelinnumeroita"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Anna sovelluksen käyttää laitteella olevia puhelinnumeroita."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"pitää auton näytön päällä"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"estä tablet-laitetta menemästä virransäästötilaan"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"estää Android TV ‑laitetta siirtymästä virransäästötilaan"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"estä puhelinta menemästä virransäästötilaan"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Sallii sovelluksen pitää auton näytön päällä."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Antaa sovelluksen estää tablet-laitetta siirtymästä virransäästötilaan."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Antaa sovelluksen estää Android TV ‑laitetta siirtymästä virransäästötilaan."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Antaa sovelluksen estää puhelinta siirtymästä virransäästötilaan."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Nostetaanko äänenvoimakkuus suositellun tason yläpuolelle?\n\nPitkäkestoinen kova äänenvoimakkuus saattaa heikentää kuuloa."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Käytetäänkö esteettömyyden pikanäppäintä?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kun pikanäppäin on käytössä, voit käynnistää esteettömyystoiminnon pitämällä molempia äänenvoimakkuuspainikkeita painettuna kolmen sekunnin ajan."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Muokkaa pikakuvakkeita"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Peruuta"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Poista pikanäppäin käytöstä"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Luokittelematon"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Voit valita näiden ilmoitusten tärkeyden."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Tämä on tärkeää siihen liittyvien ihmisten perusteella."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Oma sovellusilmoitus"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Saako <xliff:g id="APP">%1$s</xliff:g> luoda uuden käyttäjän (<xliff:g id="ACCOUNT">%2$s</xliff:g>) – tällä käyttäjällä on jo tili?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Saako <xliff:g id="APP">%1$s</xliff:g> luoda uuden käyttäjän (<xliff:g id="ACCOUNT">%2$s</xliff:g>)?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Lisää kieli"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> on nyt rajoitettujen ryhmässä"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Henkilökohtainen"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Työ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ei voi jakaa työsovellusten kanssa"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Ei voi jakaa henkilökohtaisten sovellusten kanssa"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT-järjestelmänvalvojasi esti jakamisen henkilökohtaisten ja työsovellusten välillä"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ota työsovellukset käyttöön"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ota työsovellukset käyttöön päästäksesi työsovelluksiin ja yhteystietoihin"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Sovelluksia ei ole käytettävissä"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Sovelluksia ei löytynyt"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ota työprofiili käyttöön"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Äänen tallentaminen tai toistaminen puheluiden aikana"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Sallii tämän sovelluksen tallentaa tai toistaa ääntä puheluiden aikana, kun sovellus on valittu oletuspuhelusovellukseksi."</string>
</resources>
diff --git a/core/res/res/values-fr-rCA/strings.xml b/core/res/res/values-fr-rCA/strings.xml
index 6f47049..af4be33 100644
--- a/core/res/res/values-fr-rCA/strings.xml
+++ b/core/res/res/values-fr-rCA/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Saisie d\'écran pour le rapport de bogue dans <xliff:g id="NUMBER_1">%d</xliff:g> seconde.</item>
<item quantity="other">Saisie d\'écran pour le rapport de bogue dans <xliff:g id="NUMBER_1">%d</xliff:g> secondes.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Capture d\'écran prise avec le rapport de bogue"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Échec de la prise de capture d\'écran avec le rapport de bogue"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mode silencieux"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Le son est désactivé."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Le son est activé."</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permet à l\'application de continuer un appel commencé dans une autre application."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lire les numéros de téléphone"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permet à l\'application d\'accéder aux numéros de téléphone de l\'appareil."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"garder l\'écran de la voiture allumé"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"empêcher la tablette de passer en mode veille"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Empêcher votre appareil Android TV de passer en mode Veille"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"empêcher le téléphone de passer en mode veille"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permet à l\'application de garder l\'écran de la voiture allumé."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permet à l\'application d\'empêcher la tablette de passer en mode veille."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permet à l\'application d\'empêcher votre appareil Android TV de passer en mode Veille."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permet à l\'application d\'empêcher le téléphone de passer en mode veille."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Augmenter le volume au-dessus du niveau recommandé?\n\nL\'écoute prolongée à un volume élevé peut endommager vos facultés auditives."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Utiliser le raccourci d\'accessibilité?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Quand le raccourci est activé, appuyez sur les deux boutons de volume pendant trois secondes pour lancer une fonctionnalité d\'accessibilité."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Modifier les raccourcis"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Annuler"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Désactiver le raccourci"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sans catégorie"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Vous définissez l\'importance de ces notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ces notifications sont importantes en raison des participants."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notification d\'application personnalisée"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un utilisateur <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Un utilisateur est déjà associé à ce compte)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil d\'utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Ajouter une langue"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> a été placé dans le compartiment RESTREINT"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personnel"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Bureau"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Partage impossible avec les applications professionnelles"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Partage impossible avec les applications personnelles"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Votre administrateur informatique a bloqué le partage entre vos applications personnelles et professionnelles"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activer les applications professionnelles"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activez les applications professionnelles pour accéder à celles-ci ainsi qu\'à vos contacts professionnels"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Aucune application disponible"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nous n\'avons trouvé aucune application"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Activer le profil professionnel"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Enregistrer ou lire du contenu audio lors des appels téléphoniques"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permet à cette application, lorsqu\'elle est définie comme composeur par défaut, d\'enregistrer ou de lire du contenu audio lors des appels téléphoniques."</string>
</resources>
diff --git a/core/res/res/values-fr/strings.xml b/core/res/res/values-fr/strings.xml
index 20f0406..f4309ba 100644
--- a/core/res/res/values-fr/strings.xml
+++ b/core/res/res/values-fr/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Capture d\'écran pour le rapport de bug dans <xliff:g id="NUMBER_1">%d</xliff:g> seconde</item>
<item quantity="other">Capture d\'écran pour le rapport de bug dans <xliff:g id="NUMBER_1">%d</xliff:g> secondes</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Capture d\'écran avec rapport de bug effectuée"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Échec de la capture d\'écran avec le rapport de bug"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mode silencieux"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Le son est désactivé."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Le son est activé."</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Autorise l\'application à continuer un appel qui a été démarré dans une autre application."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lire les numéros de téléphone"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permet à l\'application d\'accéder aux numéros de téléphone de l\'appareil."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"laisser l\'écran de la voiture allumé"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"empêcher la tablette de passer en mode veille"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Empêcher votre appareil Android TV de passer en mode veille"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"empêcher le téléphone de passer en mode veille"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permet à l\'application de laisser l\'écran de la voiture allumé."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permet à l\'application d\'empêcher la tablette de passer en mode veille."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permet à l\'application d\'empêcher votre appareil Android TV de passer en mode veille."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permet à l\'application d\'empêcher le téléphone de passer en mode veille."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Augmenter le volume au dessus du niveau recommandé ?\n\nL\'écoute prolongée à un volume élevé peut endommager vos facultés auditives."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Utiliser le raccourci d\'accessibilité ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Quand le raccourci est activé, appuyez sur les deux boutons de volume pendant trois secondes pour démarrer une fonctionnalité d\'accessibilité."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Modifier les raccourcis"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Annuler"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Désactiver le raccourci"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sans catégorie"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Vous définissez l\'importance de ces notifications."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ces notifications sont importantes en raison des participants."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notification d\'application personnalisée"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g> (un utilisateur associé à ce compte existe déjà) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Autoriser <xliff:g id="APP">%1$s</xliff:g> à créer un profil utilisateur avec le compte <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Ajouter une langue"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> a été placé dans le bucket RESTRICTED"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personnel"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Professionnel"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Partage impossible avec les applications professionnelles"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Partage impossible avec les applications personnelles"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Votre administrateur informatique a bloqué le partage entre vos applications personnelles et professionnelles"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activer les applications professionnelles"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activez les applications professionnelles pour accéder à celles-ci ainsi qu\'à vos contacts pour le travail"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Aucune application disponible"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Aucune application détectée"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Activer le profil professionnel"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Enregistrer ou lire du contenu audio lors des appels téléphoniques"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permet à cette application d\'enregistrer ou de lire du contenu audio lors des appels téléphoniques lorsqu\'elle est définie comme clavier par défaut."</string>
</resources>
diff --git a/core/res/res/values-gl/strings.xml b/core/res/res/values-gl/strings.xml
index cee03a1..838ea9e 100644
--- a/core/res/res/values-gl/strings.xml
+++ b/core/res/res/values-gl/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Vaise facer unha captura de pantalla para o informe de erros en <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
<item quantity="one">Vaise facer unha captura de pantalla para o informe de erros en <xliff:g id="NUMBER_0">%d</xliff:g> segundo.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Realizouse a captura de pantalla co informe de erros"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Produciuse un erro ao realizar a captura de pantalla co informe de erros"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modo de silencio"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"O son está desactivado"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"O son está activado"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite que a aplicación continúe unha chamada que se iniciou noutra aplicación."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ler números de teléfono"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permite que a aplicación acceda aos números de teléfono do dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"manter acendida a pantalla do coche"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"evitar que a tableta entre en modo de inactividade"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"evitar que o dispositivo Android TV entre en modo de suspensión"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"evitar que o teléfono entre en modo de suspensión"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite que a aplicación manteña acendida a pantalla do coche."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite á aplicación evitar que a tableta acceda ao modo de suspensión."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite que a aplicación evite que o dispositivo Android TV entre en modo de suspensión."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite á aplicación evitar que o teléfono acceda ao modo de suspensión."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Queres subir o volume máis do nivel recomendado?\n\nA reprodución de son a un volume elevado durante moito tempo pode provocar danos nos oídos."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Queres utilizar o atallo de accesibilidade?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Cando o atallo está activado, podes premer os dous botóns de volume durante 3 segundos para iniciar unha función de accesibilidade."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editar atallos"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancelar"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desactivar atallo"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sen clasificar"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ti defines a importancia destas notificacións."</string>
<string name="importance_from_person" msgid="4235804979664465383">"É importante polas persoas involucradas."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificación de aplicacións personalizada"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Queres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario novo con <xliff:g id="ACCOUNT">%2$s</xliff:g>? (Xa existe un usuario con esta conta)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Queres permitir que <xliff:g id="APP">%1$s</xliff:g> cree un usuario novo con <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Engadir un idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> incluíuse no grupo RESTRINXIDO"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Persoal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Traballo"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Non se pode compartir información coas aplicacións do traballo"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Non se pode compartir información coas aplicacións persoais"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"O teu administrador de TI bloqueou a función de compartir información entre as aplicacións persoais e as do traballo"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activa as aplicacións do traballo"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activa as aplicacións do traballo para acceder a elas e aos contactos do traballo"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Non hai aplicacións dispoñibles"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Non se puideron atopar aplicacións"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Activar perfil do traballo"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Gravar ou reproducir audio en chamadas telefónicas"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permite que esta aplicación, cando está asignada como aplicación predeterminada do marcador, grave e reproduza audio en chamadas telefónicas."</string>
</resources>
diff --git a/core/res/res/values-gu/strings.xml b/core/res/res/values-gu/strings.xml
index c718124..6dba380 100644
--- a/core/res/res/values-gu/strings.xml
+++ b/core/res/res/values-gu/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">બગ રિપોર્ટ માટે <xliff:g id="NUMBER_1">%d</xliff:g> સેકન્ડમાં સ્ક્રીનશોટ લઈ રહ્યાં છે.</item>
<item quantity="other">બગ રિપોર્ટ માટે <xliff:g id="NUMBER_1">%d</xliff:g> સેકન્ડમાં સ્ક્રીનશોટ લઈ રહ્યાં છે.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ખામીની જાણકારી સાથે સ્ક્રીનશૉટ લેવામાં આવ્યો"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ખામીની જાણકારી સાથે સ્ક્રીનશૉટ લેવામાં નિષ્ફળ થયા"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"સાઇલેન્ટ મોડ"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"અવાજ બંધ છે"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ધ્વનિ ચાલુ છે"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"એક અન્ય તૃતીય પક્ષ ઍપમાં ચાલુ થયેલા કૉલને આ ઍપમાં ચાલુ રાખવાની મંજૂરી આપે છે."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ફોન નંબર વાંચો"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ઍપ્લિકેશનને ઉપકરણનાં ફોન નંબરને ઍક્સેસ કરવાની મંજૂરી આપે છે."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"કારની સ્ક્રીન ચાલુ રાખો."</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ટેબ્લેટને નિષ્ક્રિય થતું અટકાવો"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"તમારા Android TV ડિવાઇસને નિષ્ક્રિય થવાથી અટકાવો"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ફોનને નિષ્ક્રિય થતો અટકાવો"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ઍપને કારની સ્ક્રીન ચાલુ રાખવાની મંજૂરી આપો."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"એપ્લિકેશનને ટેબ્લેટને નિષ્ક્રિય થઈ જતો અટકાવવાની મંજૂરી આપે છે."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ઍપને તમારા Android TV ડિવાઇસને નિષ્ક્રિય થઈ જવાથી અટકાવવાની મંજૂરી આપે છે."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"એપ્લિકેશનને ફોનને નિષ્ક્રિય થઈ જતો અટકાવવાની મંજૂરી આપે છે."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"ભલામણ કરેલ સ્તરની ઉપર વૉલ્યૂમ વધાર્યો?\n\nલાંબા સમય સુધી ઊંચા અવાજે સાંભળવું તમારી શ્રવણક્ષમતાને નુકસાન પહોંચાડી શકે છે."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ઍક્સેસિબિલિટી શૉર્ટકટનો ઉપયોગ કરીએ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"જ્યારે શૉર્ટકટ ચાલુ હોય, ત્યારે બન્ને વૉલ્યૂમ બટનને 3 સેકન્ડ સુધી દબાવી રાખવાથી ઍક્સેસિબિલિટી સુવિધા શરૂ થઈ જશે."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"શૉર્ટકટમાં ફેરફાર કરો"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"રદ કરો"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"શૉર્ટકટ બંધ કરો"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>ને પ્રતિબંધિત સમૂહમાં મૂકવામાં આવ્યું છે"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"વ્યક્તિગત"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"કાર્યાલય"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ઑફિસ માટેની ઍપની સાથે શેર કરી શકતાં નથી"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"વ્યક્તિગત ઍપની સાથે શેર કરી શકતાં નથી"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"તમારા IT વ્યવસ્થાપકે વ્યક્તિગત અને ઑફિસ માટેની ઍપ વચ્ચે શેરિંગની સુવિધાને બ્લૉક કરી છે"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ઑફિસ માટેની ઍપ ચાલુ કરો"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ઑફિસ માટેની ઍપ અને સંપર્કોને ઍક્સેસ કરવા માટે ઑફિસ માટેની ઍપ ચાલુ કરો"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"કોઈ ઍપ ઉપલબ્ધ નથી"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"અમે કોઈપણ ઍપ શોધી શક્યાં નથી"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ઑફિસ માટેની પ્રોફાઇલ પર સ્વિચ કરો"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ટેલિફોની કૉલમાં ઑડિયો રેકૉર્ડ કરો અથવા ચલાવો"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ડિફૉલ્ટ ડાયલર ઍપ તરીકે સોંપણી કરવામાં આવવા પર આ ઍપને ટેલિફોની કૉલમાં ઑડિયો રેકૉર્ડ કરવાની અથવા ચલાવવાની મંજૂરી આપે છે."</string>
</resources>
diff --git a/core/res/res/values-hi/strings.xml b/core/res/res/values-hi/strings.xml
index eab79c0..e73bafa 100644
--- a/core/res/res/values-hi/strings.xml
+++ b/core/res/res/values-hi/strings.xml
@@ -191,10 +191,8 @@
<string name="device_ownership_relinquished" msgid="4080886992183195724">"एडमिन ने निजी इस्तेमाल के लिए डिवाइस दे दिया है"</string>
<string name="network_logging_notification_title" msgid="554983187553845004">"डिवाइस प्रबंधित है"</string>
<string name="network_logging_notification_text" msgid="1327373071132562512">"आपका संगठन इस डिवाइस का प्रबंधन करता है और वह नेटवर्क ट्रैफ़िक की निगरानी भी कर सकता है. विवरण के लिए टैप करें."</string>
- <!-- no translation found for location_changed_notification_title (4119726617105166830) -->
- <skip />
- <!-- no translation found for location_changed_notification_text (198907268219396399) -->
- <skip />
+ <string name="location_changed_notification_title" msgid="4119726617105166830">"आपके एडमिन ने जगह की सेटिंग बदली है"</string>
+ <string name="location_changed_notification_text" msgid="198907268219396399">"जगह की सेटिंग देखने के लिए टैप करें."</string>
<!-- no translation found for country_detector (7023275114706088854) -->
<skip />
<!-- no translation found for location_service (2439187616018455546) -->
@@ -255,10 +253,8 @@
<item quantity="one">गड़बड़ी की रिपोर्ट के लिए <xliff:g id="NUMBER_1">%d</xliff:g> सेकंड में स्क्रीनशॉट लिया जा रहा है.</item>
<item quantity="other">गड़बड़ी की रिपोर्ट के लिए <xliff:g id="NUMBER_1">%d</xliff:g> सेकंड में स्क्रीनशॉट लिया जा रहा है.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"गड़बड़ी की रिपोर्ट का स्क्रीनशॉट लिया गया"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"गड़बड़ी की रिपोर्ट का स्क्रीनशॉट नहीं लिया जा सका"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"साइलेंट मोड (खामोश)"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ध्वनि बंद है"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ध्वनि चालू है"</string>
@@ -445,8 +441,7 @@
<string name="permdesc_systemCamera" msgid="544730545441964482">"यह सिस्टम ऐप्लिकेशन तस्वीरें लेने और वीडियो रिकॉर्ड करने के लिए जब चाहे, सिस्टम के कैमरे का इस्तेमाल कर सकता है. ऐप्लिकेशन को android.permission.CAMERA की अनुमति देना भी ज़रूरी है"</string>
<string name="permlab_vibrate" msgid="8596800035791962017">"कंपन (वाइब्रेशन) को नियंत्रित करें"</string>
<string name="permdesc_vibrate" msgid="8733343234582083721">"ऐप्स को कंपनकर्ता नियंत्रित करने देता है."</string>
- <!-- no translation found for permdesc_vibrator_state (7050024956594170724) -->
- <skip />
+ <string name="permdesc_vibrator_state" msgid="7050024956594170724">"इससे ऐप्लिकेशन, डिवाइस का वाइब्रेटर ऐक्सेस कर पाएगा."</string>
<string name="permlab_callPhone" msgid="1798582257194643320">"फ़ोन नंबर पर सीधे कॉल करें"</string>
<string name="permdesc_callPhone" msgid="5439809516131609109">"ऐप्लिकेशन को आपके हस्तक्षेप के बिना फ़ोन नंबर पर कॉल करने देता है. इसके परिणाम अनचाहे शुल्क या कॉल हो सकते हैं. ध्यान दें कि यह ऐप्लिकेशन को आपातकालीन नंबर पर कॉल नहीं करने देता. नुकसान पहुंचाने वाला ऐप्लिकेशन आपकी पुष्टि के बिना कॉल करके आपके पैसे खर्च करवा सकते हैं."</string>
<string name="permlab_accessImsCallService" msgid="442192920714863782">"IMS कॉल सेवा ऐक्सेस करें"</string>
@@ -461,9 +456,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"इसके ज़रिए आप, किसी ऐप्लिकेशन में शुरू किया गया कॉल दूसरे ऐप्लिकेशन में जारी रख सकते हैं."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"फ़ोन नंबर पढ़ना"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ऐप को डिवाइस के फ़ोन नंबर का इस्तेमाल करने देती है."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"कार की स्क्रीन चालू रखना"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"टैबलेट को सोने (कम बैटरी मोड) से रोकें"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"अपने Android TV डिवाइस को स्लीप मोड (कम बैटरी मोड में जाने) से रोकें"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"फ़ोन को सोने (कम बैटरी मोड) से रोकें"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"यह अनुमति देने पर, ऐप्लिकेशन कार की स्क्रीन चालू रख पाएगा."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ऐप्स को टैबलेट को प्रयोग में नहीं हो जाने से रोकता है."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"यह ऐप्लिकेशन को आपके Android TV डिवाइस को स्लीप मोड (कम बैटरी मोड में जाने) से रोकने की अनुमति देता है."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ऐप्स को फ़ोन को प्रयोग में नहीं होने से रोकता है."</string>
@@ -1638,6 +1635,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"वॉल्यूम को सुझाए गए स्तर से ऊपर बढ़ाएं?\n\nअत्यधिक वॉल्यूम पर ज़्यादा समय तक सुनने से आपकी सुनने की क्षमता को नुकसान हो सकता है."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"सुलभता शॉर्टकट का इस्तेमाल करना चाहते हैं?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"शॉर्टकट के चालू होने पर, दाेनाें वॉल्यूम बटन (आवाज़ कम या ज़्यादा करने वाले बटन) को तीन सेकंड तक दबाने से, सुलभता सुविधा शुरू हाे जाएगी."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"शॉर्टकट में बदलाव करें"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"अभी नहीं"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"शॉर्टकट बंद करें"</string>
@@ -2035,16 +2038,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> को प्रतिबंधित बकेट में रखा गया है"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"निजी प्रोफ़ाइल"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"वर्क प्रोफ़ाइल"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ऑफ़िस के काम से जुड़े ऐप्लिकेशन के साथ चीज़ें शेयर नहीं की जा सकतीं"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"निजी ऐप्लिकेशन के साथ कुछ शेयर नहीं किया जा सकता"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"आपके आईटी एडमिन ने निजी ऐप्लिकेशन और ऑफ़िस के काम से जुड़े ऐप्लिकेशन के बीच कुछ शेयर करने की सुविधा पर रोक लगा दी है"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ऑफ़िस के काम से जुड़े ऐप्लिकेशन चालू करें"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ऑफ़िस के काम से जुड़े ऐप्लिकेशन और संपर्क ऐक्सेस करने के लिए, इन ऐप्लिकेशन को चालू करें"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"कोई ऐप्लिकेशन उपलब्ध नहीं है"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"हमें कोई ऐप्लिकेशन नहीं मिला"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"वर्क प्रोफ़ाइल को चालू करें"</string>
- <!-- no translation found for permlab_accessCallAudio (1682957511874097664) -->
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
<skip />
- <!-- no translation found for permdesc_accessCallAudio (8448360894684277823) -->
- <skip />
+ <string name="permlab_accessCallAudio" msgid="1682957511874097664">"फ़ोन कॉल के दौरान, ऑडियो रिकॉर्ड करने या उसे चलाने की अनुमति"</string>
+ <string name="permdesc_accessCallAudio" msgid="8448360894684277823">"डिफ़ॉल्ट डायलर ऐप्लिकेशन के तौर पर असाइन होने पर, इस ऐप्लिकेशन को फ़ोन कॉल के दौरान ऑडियो रिकॉर्ड करने और उसे चलाने की मंज़ूरी मिल जाती है."</string>
</resources>
diff --git a/core/res/res/values-hr/strings.xml b/core/res/res/values-hr/strings.xml
index 5b7ec23..202c3ca 100644
--- a/core/res/res/values-hr/strings.xml
+++ b/core/res/res/values-hr/strings.xml
@@ -252,10 +252,8 @@
<item quantity="few">Izrada snimke zaslona za izvješće o programskoj pogrešci za <xliff:g id="NUMBER_1">%d</xliff:g> sekunde.</item>
<item quantity="other">Izrada snimke zaslona za izvješće o programskoj pogrešci za <xliff:g id="NUMBER_1">%d</xliff:g> sekundi.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Snimka zaslona je izrađena s izvješćem o programskoj pogrešci"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Snimanje zaslona s izvješćem o programskoj pogrešci nije uspjelo."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Bešumni način"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zvuk je isključen"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zvuk je uključen"</string>
@@ -457,9 +455,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Omogućuje aplikaciji da nastavi poziv započet u nekoj drugoj aplikaciji."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"čitati telefonske brojeve"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Aplikaciji omogućuje da pristupi telefonskim brojevima na uređaju."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"zadržati zaslon automobila uključenim"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"spriječi mirovanje tabletnog uređaja"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"sprječava prelazak Android TV uređaja u mirovanje"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"sprečava telefon da prijeđe u stanje mirovanja"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Aplikaciji omogućuje da zaslon automobila zadrži uključenim."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Aplikaciji omogućuje sprječavanje prelaska tabletnog računala u mirovanje."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Aplikaciji omogućuje sprječavanje prelaska Android TV uređaja u mirovanje."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Aplikaciji omogućuje da spriječi prelazak telefona u mirovanje."</string>
@@ -1653,6 +1653,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Želite li pojačati zvuk iznad preporučene razine?\n\nDugotrajno slušanje glasne glazbe može vam oštetiti sluh."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Želite li upotrebljavati prečac za pristupačnost?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kad je taj prečac uključen, pritiskom na obje tipke za glasnoću na tri sekunde pokrenut će se značajka pristupačnosti."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Uredi prečace"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Otkaži"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Isključi prečac"</string>
@@ -1885,8 +1891,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nema kategorije"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Postavili ste važnost tih obavijesti."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Važno je zbog uključenih osoba."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Prilagođena obavijest aplikacije"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Dopustiti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da izradi novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g> (korisnik s ovim računom već postoji)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Dopustiti aplikaciji <xliff:g id="APP">%1$s</xliff:g> da izradi novog korisnika s računom <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dodavanje jezika"</string>
@@ -2062,14 +2067,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Paket <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> premješten je u spremnik OGRANIČENO"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Osobno"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Posao"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Dijeljenje s poslovnim aplikacijama nije moguće"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Dijeljenje s osobnim aplikacijama nije moguće"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Vaš IT administrator blokirao je dijeljenje između osobnih i poslovnih aplikacija"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Uključite poslovne aplikacije"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Uključite poslovne aplikacije da biste pristupili poslovnim aplikacijama i kontaktima"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Aplikacije nisu dostupne"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nismo pronašli nijednu aplikaciju"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Prebaci na poslovni profil"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Snimanje ili reprodukcija zvuka u telefonskim pozivima"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Kad je ova aplikacija postavljena kao zadana aplikacija za biranje, omogućuje joj snimanje ili reprodukciju zvuka u telefonskim pozivima."</string>
</resources>
diff --git a/core/res/res/values-hu/strings.xml b/core/res/res/values-hu/strings.xml
index a474ac7..356d179 100644
--- a/core/res/res/values-hu/strings.xml
+++ b/core/res/res/values-hu/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Képernyőkép készítése a hibajelentéshez <xliff:g id="NUMBER_1">%d</xliff:g> másodpercen belül.</item>
<item quantity="one">Képernyőkép készítése a hibajelentéshez <xliff:g id="NUMBER_0">%d</xliff:g> másodpercen belül.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Sikerült a képernyőkép elkészítése a hibajelentéshez"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Nem sikerült képernyőképet készíteni a hibajelentéshez"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Néma üzemmód"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Hang kikapcsolva"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Hang bekapcsolva"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Engedélyezi az alkalmazásnak, hogy folytassa a hívást, amelyet valamelyik másik alkalmazásban kezdtek meg."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"telefonszámok olvasása"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Engedélyezi az alkalmazás számára az eszköz telefonszámaihoz való hozzáférést."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"az autó képernyőjének bekapcsolva tartása"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"táblagép alvás üzemmódjának megakadályozása"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"megakadályozza, hogy az Android TV eszköz alvó üzemmódra váltson"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"telefon alvó üzemmódjának megakadályozása"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Lehetővé teszi az alkalmazás számára az autó képernyőjének bekapcsolva tartását."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Lehetővé teszi az alkalmazás számára, hogy megakadályozza, hogy a táblagép alvó üzemmódra váltson."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Lehetővé teszi az alkalmazás számára, hogy megakadályozza, hogy az Android TV eszköz alvó üzemmódra váltson."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Lehetővé teszi az alkalmazás számára, hogy megakadályozza, hogy a telefon alvó üzemmódra váltson."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Az ajánlott szint fölé szeretné emelni a hangerőt?\n\nHa hosszú időn át teszi ki magát nagy hangerőnek, azzal károsíthatja a hallását."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Szeretné használni a Kisegítő lehetőségek billentyűparancsot?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Ha a gyorsparancs aktív, akkor a két hangerőgomb három másodpercig tartó együttes lenyomásával kisegítő funkciót indíthat el."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Gyorsparancsszerkesztés"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Mégse"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Billentyűparancs kikapcsolása"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nincs kategóriába sorolva"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ön állította be ezen értesítések fontossági szintjét."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ez az üzenet a résztvevők miatt fontos."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Egyéni alkalmazásértesítés"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Engedélyezi a(z) <xliff:g id="APP">%1$s</xliff:g> számára, hogy új felhasználót hozzon létre a(z) <xliff:g id="ACCOUNT">%2$s</xliff:g> fiókkal? (Már létezik felhasználó ezzel a fiókkal.)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Engedélyezi a(z) <xliff:g id="APP">%1$s</xliff:g> számára, hogy új felhasználót hozzon létre a(z) <xliff:g id="ACCOUNT">%2$s</xliff:g> fiókkal?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Nyelv hozzáadása"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"A következő csomag a KORLÁTOZOTT csoportba került: <xliff:g id="PACKAGE_NAME">%1$s</xliff:g>"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Személyes"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Munka"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nem lehetséges a munkahelyi alkalmazásokkal való megosztás"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nem lehetséges a személyes alkalmazásokkal való megosztás"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Rendszergazdája letiltotta a személyes és a munkahelyi alkalmazások közti megosztást"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Kapcsolja be a munkahelyi alkalmazásokat"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Kapcsolja be a munkahelyi alkalmazásokat a munkahelyi alkalmazásokhoz és a névjegyekhez való hozzáférés érdekében"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nem áll rendelkezésre alkalmazás"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nem találtunk egy alkalmazást sem"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Munkaprofil bekapcsolása"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Audiotartalmak felvétele és lejátszása telefonhívások közben"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Lehetővé teszi ennek az alkalmazásnak audiotartalmak felvételét és lejátszását telefonhívások közben, amennyiben az alkalmazás alapértelmezett tárcsázóalkalmazásként van kijelölve."</string>
</resources>
diff --git a/core/res/res/values-hy/strings.xml b/core/res/res/values-hy/strings.xml
index 80b7985..ca98331 100644
--- a/core/res/res/values-hy/strings.xml
+++ b/core/res/res/values-hy/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Սքրինշոթը կարվի <xliff:g id="NUMBER_1">%d</xliff:g> վայրկյանից:</item>
<item quantity="other">Սքրինշոթը կարվի <xliff:g id="NUMBER_1">%d</xliff:g> վայրկյանից:</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Վրիպակների հաշվետվության պատկերով սքրինշոթ արվեց"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Չհաջողվեց վրիպակների հաշվետվության պատկերով սքրինշոթ անել"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Անձայն ռեժիմ"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Ձայնը անջատված է"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Ձայնը միացված է"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Թույլ է տալիս հավելվածին շարունակել մեկ այլ հավելվածի միջոցով սկսած զանգը:"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"օգտագործել հեռախոսահամարները"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Հավելվածին թույլ է տալիս օգտագործել սարքի հեռախոսահամարները:"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"միացրած թողնել մեքենայի էկրանը"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"զերծ պահել պլանշետը քնելուց"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"թույլ չտալ, որ Android TV սարքն անցնի քնի ռեժիմի"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"կանխել հեռախոսի քնի ռեժիմին անցնելը"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Հավելվածին թույլ է տալիս միացրած թողնել մեքենայի էկրանը։"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Թույլ է տալիս հավելվածին կանխել պլանշետի` քնի ռեժիմին անցնելը:"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Թույլ է տալիս հավելվածին կանխել, որ Android TV սարքը չանցնի քնի ռեժիմի:"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Թույլ է տալիս հավելվածին կանխել հեռախոսի` քնի ռեժիմին անցնելը:"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Ձայնը բարձրացնե՞լ խորհուրդ տրվող մակարդակից ավել:\n\nԵրկարատև բարձրաձայն լսելը կարող է վնասել ձեր լսողությունը:"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Օգտագործե՞լ Մատչելիության դյուրանցումը։"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Հատուկ գործառույթն օգտագործելու համար սեղմեք և 3 վայրկյան սեղմած պահեք ձայնի ուժգնության երկու կոճակները, երբ գործառույթը միացված է:"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Փոփոխել դյուրանցումները"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Չեղարկել"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Անջատել դյուրանցումը"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Չդասակարգված"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Դուք սահմանել եք այս ծանուցումների կարևորությունը:"</string>
<string name="importance_from_person" msgid="4235804979664465383">"Կարևոր է, քանի որ որոշակի մարդիկ են ներգրավված:"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Հավելվածի հատուկ ծանուցում"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Թույլատրե՞լ <xliff:g id="APP">%1$s</xliff:g> հավելվածին <xliff:g id="ACCOUNT">%2$s</xliff:g> հաշվով նոր Օգտատեր ստեղծել (նման հաշվով Օգտատեր արդեն գոյություն ունի):"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Թույլատրե՞լ <xliff:g id="APP">%1$s</xliff:g> հավելվածին <xliff:g id="ACCOUNT">%2$s</xliff:g> հաշվով նոր Օգտատեր ստեղծել:"</string>
<string name="language_selection_title" msgid="52674936078683285">"Ավելացնել լեզու"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> փաթեթը գցվեց ՍԱՀՄԱՆԱՓԱԿՎԱԾ զամբյուղի մեջ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Անձնական"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Աշխատանքային"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Հնարավոր չէ կիսվել աշխատանքային հավելվածների հետ"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Հնարավոր չէ կիսվել անձնական հավելվածների հետ"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Ձեր ՏՏ ադմինիստրատորն արգելափակել է աշխատանքային և անձնական հավելվածների միջև տվյալների փոխանակումը։"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Միացրեք աշխատանքային հավելվածները"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Միացրեք աշխատանքային հավելվածները, որպեսզի կարողանաք օգտագործել աշխատանքային տվյալները (հավելվածներն ու կոնտակտները)"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Հասանելի հավելվածներ չկան"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Չհաջողվեց գտնել հավելվածներ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Անցնել աշխատանքային հաշվին"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Հեռախոսային զանգերի ձայնագրում և նվագարկում"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Եթե այս հավելվածն ըստ կանխադրման օգտագործվում է զանգերի համար, այն կարող է ձայնագրել և նվագարկել հեռախոսային խոսակցությունները։"</string>
</resources>
diff --git a/core/res/res/values-in/strings.xml b/core/res/res/values-in/strings.xml
index d45370a..8b28f63 100644
--- a/core/res/res/values-in/strings.xml
+++ b/core/res/res/values-in/strings.xml
@@ -89,7 +89,7 @@
<string name="EmergencyCallWarningSummary" msgid="1194185880092805497">"Tidak dapat melakukan panggilan darurat melalui Wi-Fi"</string>
<string name="notification_channel_network_alert" msgid="4788053066033851841">"Notifikasi"</string>
<string name="notification_channel_call_forward" msgid="8230490317314272406">"Penerusan panggilan"</string>
- <string name="notification_channel_emergency_callback" msgid="54074839059123159">"Mode panggilan balik darurat"</string>
+ <string name="notification_channel_emergency_callback" msgid="54074839059123159">"Mode telepon balik darurat"</string>
<string name="notification_channel_mobile_data_status" msgid="1941911162076442474">"Status data seluler"</string>
<string name="notification_channel_sms" msgid="1243384981025535724">"Pesan SMS"</string>
<string name="notification_channel_voice_mail" msgid="8457433203106654172">"Notifikasi pesan suara"</string>
@@ -249,10 +249,8 @@
<item quantity="other">Mengambil screenshot untuk laporan bug dalam <xliff:g id="NUMBER_1">%d</xliff:g> detik.</item>
<item quantity="one">Mengambil screenshot untuk laporan bug dalam <xliff:g id="NUMBER_0">%d</xliff:g> detik.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Screenshot berisi laporan bug diambil"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Gagal mengambil screenshot berisi laporan bug"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mode senyap"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Suara MATI"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Suara AKTIF"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Mengizinkan aplikasi melanjutkan panggilan yang dimulai di aplikasi lain."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"membaca nomor telepon"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Mengizinkan aplikasi mengakses nomor telepon perangkat."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"tetap aktifkan layar mobil"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"cegah tablet dari tidur"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"cegah perangkat Android TV tidur"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"mencegah ponsel menjadi tidak aktif"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Mengizinkan aplikasi untuk menjaga agar layar mobil tetap aktif."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Mengizinkan apl mencegah tablet tidur."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Mengizinkan aplikasi untuk mencegah perangkat Android TV tidur."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Mengizinkan apl mencegah ponsel tidur."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Mengeraskan volume di atas tingkat yang disarankan?\n\nMendengarkan dengan volume keras dalam waktu yang lama dapat merusak pendengaran Anda."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Gunakan Pintasan Aksesibilitas?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Saat pintasan aktif, menekan kedua tombol volume selama 3 detik akan memulai fitur aksesibilitas."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit pintasan"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Batal"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Nonaktifkan Pintasan"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Belum dikategorikan"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Anda menyetel nilai penting notifikasi ini."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ini penting karena orang-orang yang terlibat."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notifikasi aplikasi kustom"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Izinkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baru dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> (Pengguna dengan akun ini sudah ada) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Izinkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baru dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Tambahkan bahasa"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> telah dimasukkan ke dalam bucket DIBATASI"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Pribadi"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Kerja"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Tidak dapat membagikan ke aplikasi kerja"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Tidak dapat membagikan ke aplikasi pribadi"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Admin IT memblokir berbagi antara aplikasi kerja dan pribadi"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Aktifkan aplikasi kerja"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Aktifkan aplikasi kerja untuk mengakses aplikasi kerja & kontak"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Tidak ada aplikasi yang tersedia"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Kami tidak menemukan aplikasi"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Aktifkan profil kerja"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Rekam atau putar audio dalam panggilan telepon"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Mengizinkan aplikasi ini, saat ditetapkan sebagai aplikasi telepon default, untuk merekam atau memutar audio dalam panggilan telepon."</string>
</resources>
diff --git a/core/res/res/values-is/strings.xml b/core/res/res/values-is/strings.xml
index 342f6f2..1aecb57 100644
--- a/core/res/res/values-is/strings.xml
+++ b/core/res/res/values-is/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Tekur skjámynd fyrir villutilkynningu eftir <xliff:g id="NUMBER_1">%d</xliff:g> sekúndu.</item>
<item quantity="other">Tekur skjámynd fyrir villutilkynningu eftir <xliff:g id="NUMBER_1">%d</xliff:g> sekúndur.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Skjámynd með villutilkynningu tekin"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Mistókst að taka skjámynd með villutilkynningu"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Hljóðlaus stilling"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"SLÖKKT er á hljóði"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"KVEIKT er á hljóði"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Leyfir forritinu að halda áfram með símtal sem hófst í öðru forriti."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lesa símanúmer"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Veitir forritinu aðgang að símanúmerum tækisins."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"hafa kveikt á skjá bílsins"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"koma í veg fyrir að spjaldtölvan fari í biðstöðu"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"koma í veg fyrir að Android TV fari í biðstöðu"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"koma í veg fyrir að síminn fari í biðstöðu"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Gerir forritinu kleift að hafa kveikt á skjá bílsins."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Leyfir forriti að koma í veg fyrir að spjaldtölvan fari í biðstöðu."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Leyfir forritinu að koma í veg fyrir að Android TV tækið fari í biðstöðu."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Leyfir forriti að koma í veg fyrir að síminn fari í biðstöðu."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Hækka hljóðstyrk umfram ráðlagðan styrk?\n\nEf hlustað er á háum hljóðstyrk í langan tíma kann það að skaða heyrnina."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Viltu nota aðgengisflýtileið?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Þegar flýtileiðin er virk er kveikt á aðgengiseiginleikanum með því að halda báðum hljóðstyrkshnöppunum inni í þrjár sekúndur."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Breyta flýtileiðum"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Hætta við"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Slökkva á flýtileið"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Óflokkað"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Þú stilltir mikilvægi þessara tilkynninga."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Þetta er mikilvægt vegna fólksins sem tekur þátt í þessu."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Sérsniðin forritatilkynning"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Viltu leyfa <xliff:g id="APP">%1$s</xliff:g> að stofna nýjan notanda með <xliff:g id="ACCOUNT">%2$s</xliff:g> (notandi með þennan reikning er þegar fyrir hendi)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Leyfa <xliff:g id="APP">%1$s</xliff:g> að stofna nýjan notanda með <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Bæta við tungumáli"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> var sett í flokkinn TAKMARKAÐ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Persónulegt"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Vinna"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ekki er hægt að deila með vinnuforritum"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Ekki er hægt að deila með persónulegum forritum"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Kerfisstjórinn þinn hefur lokað á deilingu milli persónulegra forrita og vinnuforrita"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Kveikja á vinnuforritum"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Kveiktu á vinnuforritum til að fá aðgang að þeim og vinnutengiliðum"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Engin forrit í boði"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Við fundum engin forrit"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Skipta yfir í vinnu"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Taka upp eða spila hljóð í símtölum"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Gerir þessu forriti kleift að taka upp og spila hljóð í símtölum þegar það er valið sem sjálfgefið hringiforrit."</string>
</resources>
diff --git a/core/res/res/values-it/strings.xml b/core/res/res/values-it/strings.xml
index 783e45e..85fbf61 100644
--- a/core/res/res/values-it/strings.xml
+++ b/core/res/res/values-it/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Lo screenshot per la segnalazione di bug verrà acquisito tra <xliff:g id="NUMBER_1">%d</xliff:g> secondi.</item>
<item quantity="one">Lo screenshot per la segnalazione di bug verrà acquisito tra <xliff:g id="NUMBER_0">%d</xliff:g> secondo.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Screenshot con segnalazione di bug effettuato correttamente"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Impossibile acquisire screenshot con segnalazione di bug"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modalità silenziosa"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Audio non attivo"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Audio attivo"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Consente all\'app di continuare una chiamata che è stata iniziata in un\'altra app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lettura dei numeri di telefono"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Consente all\'app di accedere ai numeri di telefono del dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"Mantenere attivo lo schermo dell\'auto"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"disattivazione stand-by del tablet"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Blocco dell\'attivazione della modalità di sospensione del dispositivo Android TV"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"disattivazione stand-by del telefono"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Consente all\'app di mantenere attivo lo schermo dell\'auto."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Consente all\'applicazione di impedire lo stand-by del tablet."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Consente all\'app di impedire l\'attivazione della modalità di sospensione del dispositivo Android TV."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Consente all\'applicazione di impedire lo stand-by del telefono."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Vuoi aumentare il volume oltre il livello consigliato?\n\nL\'ascolto ad alto volume per lunghi periodi di tempo potrebbe danneggiare l\'udito."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Usare la scorciatoia Accessibilità?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Quando la scorciatoia è attiva, puoi premere entrambi i pulsanti del volume per tre secondi per avviare una funzione di accessibilità."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Modifica scorciatoie"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Annulla"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Disattiva scorciatoia"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Senza categoria"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Stabilisci tu l\'importanza di queste notifiche."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Importante a causa delle persone coinvolte."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notifica app personalizzata"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Consentire a <xliff:g id="APP">%1$s</xliff:g> di creare un nuovo utente con l\'account <xliff:g id="ACCOUNT">%2$s</xliff:g> (esiste già un utente con questo account)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Consentire a <xliff:g id="APP">%1$s</xliff:g> di creare un nuovo utente con l\'account <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Aggiungi una lingua"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> è stato inserito nel bucket RESTRICTED"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personale"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Lavoro"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Impossibile condividere con app di lavoro"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Impossibile condividere con app personali"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Il tuo amministratore IT ha bloccato la condivisione tra app personali e di lavoro"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Attiva app di lavoro"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Attiva le app di lavoro per accedere alle app e ai contatti di lavoro"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nessuna app disponibile"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nessuna app trovata"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Attiva profilo di lavoro"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Registrazione o riproduzione dell\'audio delle telefonate"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Consente a questa app, se assegnata come applicazione telefono predefinita, di registrare o riprodurre l\'audio delle telefonate."</string>
</resources>
diff --git a/core/res/res/values-iw/strings.xml b/core/res/res/values-iw/strings.xml
index b2b5657..b4e47e3 100644
--- a/core/res/res/values-iw/strings.xml
+++ b/core/res/res/values-iw/strings.xml
@@ -255,10 +255,8 @@
<item quantity="other">יוצר צילום מסך לדוח על באג בעוד <xliff:g id="NUMBER_1">%d</xliff:g> שניות.</item>
<item quantity="one">יוצר צילום מסך לדוח על באג בעוד שנייה <xliff:g id="NUMBER_0">%d</xliff:g>.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"בוצע צילום מסך של דוח על באג"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"הניסיון לצילום המסך של דוח על באג נכשל"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"מצב שקט"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"הקול כבוי"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"קול מופעל"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"הרשאה זו מתירה לאפליקציה להמשיך שיחה שהחלה באפליקציה אחרת."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"גישה למספרי הטלפון"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"מתירה לאפליקציה גישה למספרי הטלפון במכשיר."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"מסך המכונית יישאר דלוק"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"מנע מהטאבלט לעבור למצב שינה"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"מונעת ממכשיר ה-Android TV להיכנס למצב שינה"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"מניעת מעבר הטלפון למצב שינה"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"מסך המכונית יישאר דלוק כשהאפליקציה פועלת."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"מאפשר לאפליקציה למנוע מהטאבלט לעבור למצב שינה."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"מאפשרת לאפליקציה למנוע ממכשיר ה-Android TV לעבור למצב שינה."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"מאפשר לאפליקציה למנוע מהטלפון לעבור למצב שינה."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"האם להעלות את עוצמת הקול מעל לרמה המומלצת?\n\nהאזנה בעוצמת קול גבוהה למשכי זמן ממושכים עלולה לפגוע בשמיעה."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"להשתמש בקיצור הדרך לתכונת הנגישות?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"כשקיצור הדרך מופעל, לחיצה על שני לחצני עוצמת הקול למשך שלוש שניות מפעילה את תכונת הנגישות."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"עריכת קיצורי הדרך"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ביטול"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"כבה את קיצור הדרך"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"ללא שיוך לקטגוריה"</string>
<string name="importance_from_user" msgid="2782756722448800447">"עליך להגדיר את החשיבות של ההתראות האלה."</string>
<string name="importance_from_person" msgid="4235804979664465383">"ההודעה חשובה בשל האנשים המעורבים."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"התראות אפליקציה בהתאמה אישית"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"האם לאפשר לאפליקציה <xliff:g id="APP">%1$s</xliff:g> ליצור משתמש חדש באמצעות <xliff:g id="ACCOUNT">%2$s</xliff:g> (כבר קיים משתמש לחשבון הזה) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"האם לאפשר לאפליקציה <xliff:g id="APP">%1$s</xliff:g> ליצור משתמש חדש באמצעות <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"הוספת שפה"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> התווספה לקטגוריה \'מוגבל\'"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"אישי"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"עבודה"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"לא ניתן לשתף עם אפליקציות לעבודה"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"לא ניתן לשתף עם אפליקציות פרטיות"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"השיתוף בין אפליקציות לעבודה לאפליקציות פרטיות נחסמה על ידי מנהל ה-IT"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"הפעלה של אפליקציות לעבודה"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"יש להפעיל אפליקציות לעבודה כדי לגשת אל אפליקציות ואנשי קשר לעבודה"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"אין אפליקציות זמינות"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"לא מצאנו אפליקציות"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"הפעלה לעבודה"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"הקלטה או הפעלה של אודיו בשיחות טלפוניות"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"כאשר האפליקציה הזו מוגדרת כאפליקציית חייגן בברירת מחדל, תהיה לה הרשאה להקליט ולהפעיל אודיו בשיחות טלפוניות."</string>
</resources>
diff --git a/core/res/res/values-ja/strings.xml b/core/res/res/values-ja/strings.xml
index 850f601..1a7f301 100644
--- a/core/res/res/values-ja/strings.xml
+++ b/core/res/res/values-ja/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other"><xliff:g id="NUMBER_1">%d</xliff:g> 秒後にバグレポートのスクリーンショットが作成されます。</item>
<item quantity="one"><xliff:g id="NUMBER_0">%d</xliff:g> 秒後にバグレポートのスクリーンショットが作成されます。</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"バグレポートのスクリーンショットを取得しました"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"バグレポートのスクリーンショットを取得できませんでした"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"マナーモード"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"サウンドOFF"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"サウンドON"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"別のアプリで通話を続行することをこのアプリに許可します。"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"電話番号の読み取り"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"デバイスの電話番号へのアクセスをアプリに許可します。"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"車の画面を常にオンにする"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"タブレットのスリープを無効化"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV デバイスのスリープの無効化"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"デバイスのスリープを無効にする"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"車の画面を常にオンにすることをアプリに許可します。"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"タブレットのスリープを無効にすることをアプリに許可します。"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Android TV デバイスのスリープを無効にすることをアプリに許可します。"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"モバイル デバイスのスリープを無効にすることをアプリに許可します。"</string>
@@ -1631,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"推奨レベルを超えるまで音量を上げますか?\n\n大音量で長時間聞き続けると、聴力を損なう恐れがあります。"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ユーザー補助機能のショートカットの使用"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ショートカットが ON の場合、両方の音量ボタンを 3 秒ほど長押しするとユーザー補助機能が起動します。"</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"使用するユーザー補助アプリをタップ"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"ユーザー補助機能ボタンで使用できるアプリを選択"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"音量キーのショートカットで使用できるアプリを選択"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ショートカットの編集"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"キャンセル"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ショートカットを OFF にする"</string>
@@ -1773,8 +1776,8 @@
<string name="package_updated_device_owner" msgid="7560272363805506941">"管理者により更新されています"</string>
<string name="package_deleted_device_owner" msgid="2292335928930293023">"管理者により削除されています"</string>
<string name="confirm_battery_saver" msgid="5247976246208245754">"OK"</string>
- <string name="battery_saver_description_with_learn_more" msgid="1817385558636532621">"電池を長持ちさせるためにバッテリー セーバーが行う操作:\n·ダークテーマをオンにする\n·バックグラウンド アクティビティ、一部の視覚効果や、「OK Google」などの機能をオフにする、または制限する\n\n"<annotation id="url">"詳細"</annotation></string>
- <string name="battery_saver_description" msgid="7618492104632328184">"電池を長持ちさせるためにバッテリー セーバーが行う操作:\n·ダークテーマをオンにする\n·バックグラウンド アクティビティ、一部の視覚効果や、「OK Google」などの機能をオフにする、または制限する"</string>
+ <string name="battery_saver_description_with_learn_more" msgid="1817385558636532621">"電池を長持ちさせるためにバッテリー セーバーが行う操作:\n·ダークテーマを ON にする\n·バックグラウンド アクティビティ、一部の視覚効果や、「OK Google」などの機能を OFF にする、または制限する\n\n"<annotation id="url">"詳細"</annotation></string>
+ <string name="battery_saver_description" msgid="7618492104632328184">"電池を長持ちさせるためにバッテリー セーバーが行う操作:\n·ダークテーマを ON にする\n·バックグラウンド アクティビティ、一部の視覚効果や、「OK Google」などの機能を OFF にする、または制限する"</string>
<string name="data_saver_description" msgid="4995164271550590517">"データセーバーは、一部のアプリによるバックグラウンドでのデータ送受信を停止することでデータ使用量を抑制します。使用中のアプリからデータにアクセスすることはできますが、その頻度は低くなる場合があります。この影響として、たとえば画像はタップしないと表示されないようになります。"</string>
<string name="data_saver_enable_title" msgid="7080620065745260137">"データセーバーを ON にしますか?"</string>
<string name="data_saver_enable_button" msgid="4399405762586419726">"ON にする"</string>
@@ -1853,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"カテゴリなし"</string>
<string name="importance_from_user" msgid="2782756722448800447">"このような通知の重要度を設定します。"</string>
<string name="importance_from_person" msgid="4235804979664465383">"関係するユーザーのため、この設定は重要です。"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"カスタムアプリ通知"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> が <xliff:g id="ACCOUNT">%2$s</xliff:g> で新しいユーザーを作成できるようにしますか?(このアカウントのユーザーはすでに存在します)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> が <xliff:g id="ACCOUNT">%2$s</xliff:g> で新しいユーザーを作成できるようにしますか?"</string>
<string name="language_selection_title" msgid="52674936078683285">"言語を追加"</string>
@@ -2028,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> は RESTRICTED バケットに移動しました。"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"個人用"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"仕事用"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"個人用ビュー"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"仕事用ビュー"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"仕事用アプリと共有できません"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"個人用アプリと共有できません"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT 管理者が個人用アプリと仕事用アプリの間の共有をブロックしました"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"仕事用アプリを ON にする"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"仕事用のアプリや連絡先にアクセスするには、仕事用アプリを ON にしてください"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"IT 管理者が個人用プロファイルと仕事用プロファイルの間の共有をブロックしました"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"仕事用アプリにアクセスできません"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"IT 管理者は個人用コンテンツを仕事用アプリで表示することを許可していません"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"個人用アプリにアクセスできません"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"IT 管理者は仕事用コンテンツを個人用アプリで表示することを許可していません"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"コンテンツを共有するには、仕事用プロファイルをオンにしてください"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"コンテンツを表示するには、仕事用プロファイルをオンにしてください"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"利用できるアプリはありません"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"アプリが見つかりませんでした"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"仕事用に切り替え"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"オンにする"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"通話中に録音または音声の再生を行う"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"デフォルトの電話アプリケーションとして割り当てられている場合、このアプリに通話中の録音または音声の再生を許可します。"</string>
</resources>
diff --git a/core/res/res/values-ka/strings.xml b/core/res/res/values-ka/strings.xml
index 1ed4854..e1c9733 100644
--- a/core/res/res/values-ka/strings.xml
+++ b/core/res/res/values-ka/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">ხარვეზის შესახებ ანგარიშის ეკრანის ანაბეჭდის გადაღება მოხდება <xliff:g id="NUMBER_1">%d</xliff:g> წამში.</item>
<item quantity="one">ხარვეზის შესახებ ანგარიშის ეკრანის ანაბეჭდის გადაღება მოხდება <xliff:g id="NUMBER_0">%d</xliff:g> წამში.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"სისტემის ხარვეზის ანგარიშის ეკრანის ანაბეჭდი გადაღებულია"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"სისტემის ხარვეზის ანგარიშის ეკრანის ანაბეჭდის გადაღება ვერ მოხერხდა"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"ჩუმი რეჟიმი"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ხმა გამორთულია"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ხმა ჩართულია"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"ნებას რთავს აპს, გააგრძელოს ზარი, რომელიც სხვა აპშია წამოწყებული."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ტელეფონის ნომრების წაკითხვა"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"აპს მოწყობილობის ტელეფონის ნომრებზე წვდომის საშუალებას მისცემს."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ჩართული ჰქონდეს მანქანის ეკრანი"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"დაიცავით ტაბლეტი დაძინებისგან"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"არ მისცეთ დაძინების საშუალება Android TV მოწყობილობას"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ტელეფონის ძილის რეჟიმში გადასვლის აღკვეთა"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ნებას რთავს აპს, ჩართული ჰქონდეს მანქანის ეკრანი."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"აპს შეეძლება ხელი შეუშალოს ტაბლეტის დაძინებას."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ნებას რთავს აპს, ხელი შეუშალოს Android TV მოწყობილობას დაძინებაში."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"აპს შეეძლება ხელი შეუშალოს ტელეფონის დაძინებას."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"გსურთ ხმის რეკომენდებულ დონეზე მაღლა აწევა?\n\nხანგრძლივად ხმამაღლა მოსმენით შესაძლოა სმენადობა დაიზიანოთ."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"გსურთ მარტივი წვდომის მალსახმობის გამოყენება?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"თუ მალსახმობი ჩართულია, ხმის ორივე ღილაკზე 3 წამის განმავლობაში დაჭერით მარტივი წვდომის ფუნქცია ჩაირთვება."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"მალსახმობების რედაქტირება"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"გაუქმება"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"მალსახმობის გამორთვა"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"კატეგორიის გარეშე"</string>
<string name="importance_from_user" msgid="2782756722448800447">"ამ შეტყობინებების მნიშვნელობის დონე განისაზღვრა თქვენ მიერ."</string>
<string name="importance_from_person" msgid="4235804979664465383">"მნიშვნელოვანია ჩართული მომხმარებლების გამო."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"აპის მორგებული შეტყობინება"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"მიეცეს უფლება <xliff:g id="APP">%1$s</xliff:g>-ს <xliff:g id="ACCOUNT">%2$s</xliff:g>-ის მეშვეობით ახალი მომხმარებელი შექმნას (ამ ანგარიშის მქონე მომხმარებელი უკვე არსებობს)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"მიეცეს უფლება <xliff:g id="APP">%1$s</xliff:g>-ს <xliff:g id="ACCOUNT">%2$s</xliff:g>-ის მეშვეობით ახალი მომხმარებელი შექმნას?"</string>
<string name="language_selection_title" msgid="52674936078683285">"ენის დამატება"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> მოთავსდა კალათაში „შეზღუდული“"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"პირადი"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"სამსახური"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"სამსახურის აპებით გაზიარება შეუძლებელია"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"პირადი აპებით გაზიარება შეუძლებელია"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"თქვენმა IT ადმინისტრატორმა დაბლოკა გაზიარება პირად და სამსახურის აპებს შორის"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"სამსახურის აპების ჩართვა"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"სამსახურის აპებსა და კონტაქტებზე წვდომისთვის ჩართეთ სამსახურის აპები"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ხელმისაწვდომი აპები არ არის"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"აპები ვერ მოიძებნა"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"სამსახურზე გადართვა"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"სატელეფონო ზარებში აუდიოს ჩაწერა ან დაკვრა"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ნაგულისხმევ დასარეკ აპლიკაციად არჩევის შემთხვევაში, ნებას რთავს აპს ჩაიწეროს ან დაუკრას აუდიო სატელეფონო ზარებში."</string>
</resources>
diff --git a/core/res/res/values-kk/strings.xml b/core/res/res/values-kk/strings.xml
index 2e10b16..f3108d2 100644
--- a/core/res/res/values-kk/strings.xml
+++ b/core/res/res/values-kk/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other"><xliff:g id="NUMBER_1">%d</xliff:g> секундтан кейін қате туралы есептің скриншоты түсіріледі.</item>
<item quantity="one"><xliff:g id="NUMBER_0">%d</xliff:g> секундтан кейін қате туралы есептің скриншоты түсіріледі.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Қате туралы есеп түсірілген скриншот"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Қате туралы есеп скриншоты түсірілмеді."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Үнсіз режимі"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Дыбыс ӨШІРУЛІ"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Дыбыс ҚОСУЛЫ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Қолданбаға басқа қолданбадағы қоңырауды жалғастыруға рұқсат береді."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"телефон нөмірлерін оқу"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Қолданбаға құрылғының телефон нөмірлерін алуға мүмкіндік береді."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"көлік экранын қосулы күйде ұстау"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"планшетті ұйқыдан бөгеу"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV құрылғыңызды ұйқы режиміне өткізбеу"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"телефонды ұйқыдан бөгеу"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Қолданбаға көлік экранын қосулы күйде ұстауға мүмкіндік береді."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Қолданбаға планшеттің ұйқыға кетуін болдырмауға рұқсат береді."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Қолданба Android TV құрылғысын \"Ұйқы\" режиміне өткізбейтін болады."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Қолданбаға телефонның ұйқыға кетуін болдырмауға рұқсат береді."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Дыбыс деңгейін ұсынылған деңгейден көтеру керек пе?\n\nЖоғары дыбыс деңгейінде ұзақ кезеңдер бойы тыңдау есту қабілетіңізге зиян тигізуі мүмкін."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Арнайы мүмкіндік төте жолын пайдалану керек пе?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Түймелер тіркесімі қосулы кезде, екі дыбыс түймесін 3 секунд басып тұрсаңыз, \"Арнайы мүмкіндіктер\" функциясы іске қосылады."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Таңбашаларды өзгерту"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Бас тарту"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Төте жолды өшіру"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Санатқа жатқызылмаған"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Сіз осы хабарландырулардың маңыздылығын орнатасыз."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Қатысты адамдарға байланысты бұл маңызды."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Арнаулы хабар хабарландыруы"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> қолданбасына <xliff:g id="ACCOUNT">%2$s</xliff:g> есептік жазбасы бар жаңа пайдаланушы (мұндай есептік жазбаға ие пайдаланушы бұрыннан бар) жасауға рұқсат етілсін бе?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> қолданбасына <xliff:g id="ACCOUNT">%2$s</xliff:g> есептік жазбасы бар жаңа пайдаланушы жасауға рұқсат етілсін бе?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Тілді қосу"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ШЕКТЕЛГЕН себетке салынды."</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Жеке"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Жұмыс"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Жұмыс қолданбаларымен бөлісілмейді"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Жеке қолданбалармен бөлісілмейді"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"АТ әкімшісі жеке және жұмыс қолданбалары арасында деректер бөлісуді бөгеді."</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Жұмыс қолданбаларын іске қосу"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Жұмыс қолданбаларын және контактілерді пайдалану үшін, оларды іске қосыңыз."</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Қолданбалар жоқ"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Ешқандай қолданба табылмады."</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Жұмыс профилін іске қосу"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Телефон қоңырауларында аудио жазу немесе ойнату"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Қолданба әдепкі нөмір тергіш қолданба ретінде тағайындалған кезде, телефон қоңырауларында аудионы жазуға немесе ойнатуға мүмкіндік береді."</string>
</resources>
diff --git a/core/res/res/values-km/strings.xml b/core/res/res/values-km/strings.xml
index ce89832..180031a 100644
--- a/core/res/res/values-km/strings.xml
+++ b/core/res/res/values-km/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">នឹងថតរូបអេក្រង់សម្រាប់របាយការណ៍កំហុសក្នុងរយៈពេល <xliff:g id="NUMBER_1">%d</xliff:g> វិនាទីទៀត។</item>
<item quantity="one">នឹងថតរូបអេក្រង់សម្រាប់របាយការណ៍កំហុសក្នុងរយៈពេល <xliff:g id="NUMBER_0">%d</xliff:g> វិនាទីទៀត។</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"បានថតរូបថតអេក្រង់ដែលមានរបាយការណ៍អំពីបញ្ហា"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"មិនអាចថតរូបថតអេក្រង់ដែលមានរបាយការណ៍អំពីបញ្ហាបានទេ"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"របៀបស្ងាត់"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"បិទសំឡេង"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"បើកសំឡេង"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"អនុញ្ញាតឱ្យកម្មវិធីបន្តការហៅទូរសព្ទ ដែលបានចាប់ផ្តើមនៅក្នុងកម្មវិធីផ្សេង។"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"អានលេខទូរសព្ទ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"អនុញ្ញាតឲ្យកម្មវិធីនេះចូលប្រើប្រាស់លេខទូរសព្ទរបស់ឧបករណ៍នេះ។"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"បន្តបើកអេក្រង់រថយន្ត"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ការពារកុំព្យូទ័របន្ទះមិនឲ្យដេក"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ទប់ស្កាត់មិនឱ្យឧបករណ៍ Android TV របស់អ្នកដេក"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ការពារទូរស័ព្ទមិនឲ្យដេក"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"អនុញ្ញាតឱ្យកម្មវិធីបន្តបើកអេក្រង់រថយន្ត។"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ឲ្យកម្មវិធីការពារកុំព្យូទ័របន្ទះមិនឲ្យដេក។"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"អនុញ្ញាតឱ្យកម្មវិធីទប់ស្កាត់មិនឱ្យឧបករណ៍ Android TV របស់អ្នកដេក។"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ឲ្យកម្មវិធីការពារទូរស័ព្ទមិនឲ្យដេក។"</string>
@@ -1633,6 +1633,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"បង្កើនកម្រិតសំឡេងលើសពីកម្រិតបានផ្ដល់យោបល់?\n\nការស្ដាប់នៅកម្រិតសំឡេងខ្លាំងយូរអាចធ្វើឲ្យខូចត្រចៀក។"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ប្រើប្រាស់ផ្លូវកាត់ភាពងាយស្រួល?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"នៅពេលបើកផ្លូវកាត់ ការចុចប៊ូតុងកម្រិតសំឡេងទាំងពីររយៈពេល 3 វិនាទីនឹងចាប់ផ្តើមមុខងារភាពងាយប្រើ។"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"កែផ្លូវកាត់"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"បោះបង់"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"បិទផ្លូវកាត់"</string>
@@ -1855,8 +1861,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"មិនបែងចែកប្រភេទ"</string>
<string name="importance_from_user" msgid="2782756722448800447">"អ្នកបានកំណត់សារៈសំខាន់នៃការជូនដំណឹងទាំងនេះ"</string>
<string name="importance_from_person" msgid="4235804979664465383">"វាមានសារៈសំខាន់ដោយសារតែមនុស្សដែលពាក់ព័ន្ធ"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"ការជូនដំណឹងកម្មវិធីផ្ទាល់ខ្លួន"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"អនុញ្ញាតឱ្យ <xliff:g id="APP">%1$s</xliff:g> បង្កើតអ្នកប្រើប្រាស់ថ្មីដោយប្រើ <xliff:g id="ACCOUNT">%2$s</xliff:g> (អ្នកប្រើប្រាស់ដែលមានគណនីនេះមានរួចហើយ) ដែរឬទេ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"អនុញ្ញាតឱ្យ <xliff:g id="APP">%1$s</xliff:g> បង្កើតអ្នកប្រើប្រាស់ថ្មីដោយប្រើ <xliff:g id="ACCOUNT">%2$s</xliff:g> ដែរឬទេ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"បន្ថែមភាសា"</string>
@@ -2030,14 +2035,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ត្រូវបានដាក់ទៅក្នុងធុងដែលបានដាក់កំហិត"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ផ្ទាល់ខ្លួន"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ការងារ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"មិនអាចចែករំលែកជាមួយកម្មវិធីការងារបានទេ"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"មិនអាចចែករំលែកជាមួយកម្មវិធីផ្ទាល់ខ្លួនបានទេ"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"អ្នកគ្រប់គ្រងផ្នែកព័ត៌មានវិទ្យារបស់អ្នកបានទប់ស្កាត់ការចែករំលែករវាងកម្មវិធីការងារ និងផ្ទាល់ខ្លួន"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"បើកកម្មវិធីការងារ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"បើកកម្មវិធីការងារ ដើម្បីចូលប្រើទំនាក់ទំនង និងកម្មវិធីការងារ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"មិនមានកម្មវិធីដែលអាចប្រើបានទេ"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"យើងរកមិនឃើញកម្មវិធីណាមួយទេ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"បើកកម្រងព័ត៌មានការងារ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ថត ឬចាក់សំឡេងនៅក្នុងការហៅទូរសព្ទ"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"នៅពេលកំណត់ជាកម្មវិធីផ្ទាំងចុចហៅទូរសព្ទលំនាំដើម សូមអនុញ្ញាតឱ្យកម្មវិធីនេះថត ឬចាក់សំឡេងនៅក្នុងការហៅទូរសព្ទ។"</string>
</resources>
diff --git a/core/res/res/values-kn/strings.xml b/core/res/res/values-kn/strings.xml
index 93721a5..8072123 100644
--- a/core/res/res/values-kn/strings.xml
+++ b/core/res/res/values-kn/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">ಬಗ್ ವರದಿ ಮಾಡಲು <xliff:g id="NUMBER_1">%d</xliff:g> ಸೆಕೆಂಡುಗಳಲ್ಲಿ ಸ್ಕ್ರೀನ್ಶಾಟ್ ತೆಗೆದುಕೊಳ್ಳಲಾಗುತ್ತಿದೆ.</item>
<item quantity="other">ಬಗ್ ವರದಿ ಮಾಡಲು <xliff:g id="NUMBER_1">%d</xliff:g> ಸೆಕೆಂಡುಗಳಲ್ಲಿ ಸ್ಕ್ರೀನ್ಶಾಟ್ ತೆಗೆದುಕೊಳ್ಳಲಾಗುತ್ತಿದೆ.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ಬಗ್ ವರದಿಯ ಜೊತೆಗೆ ಸ್ಕ್ರೀನ್ಶಾಟ್ ತೆಗೆದುಕೊಳ್ಳಲಾಗಿದೆ"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ಬಗ್ ವರದಿಯ ಜೊತೆಗೆ ಸ್ಕ್ರೀನ್ಶಾಟ್ ತೆಗೆದುಕೊಳ್ಳಲು ವಿಫಲವಾಗಿದೆ"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"ಶಾಂತ ಮೋಡ್"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ಶಬ್ಧ ಆಫ್ ಆಗಿದೆ"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ಶಬ್ಧ ಆನ್ ಆಗಿದೆ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"ಮತ್ತೊಂದು ಅಪ್ಲಿಕೇಶನ್ನಲ್ಲಿ ಪ್ರಾರಂಭವಾದ ಕರೆಯನ್ನು ಮುಂದುವರಿಸಲು ಅಪ್ಲಿಕೇಶನ್ಗೆ ಅವಕಾಶ ಮಾಡಿಕೊಡಿ."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ಫೋನ್ ಸಂಖ್ಯೆಗಳನ್ನು ಓದಿ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ಸಾಧನದ ಫೋನ್ ಸಂಖ್ಯೆಗಳಿಗೆ ಪ್ರವೇಶ ಪಡೆಯಲು ಅಪ್ಲಿಕೇಶನ್ಗೆ ಅನುಮತಿ ನೀಡುತ್ತದೆ."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ಕಾರ್ ಸ್ಕ್ರೀನ್ ಅನ್ನು ಆನ್ನಲ್ಲೇ ಇರಿಸಿ"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ಟ್ಯಾಬ್ಲೆಟ್ ನಿದ್ರಾವಸ್ಥೆಯನ್ನು ತಡೆಯಿರಿ"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ನಿಮ್ಮ Android TV ಸಾಧನವು ನಿದ್ರಾವಸ್ಥೆಗೆ ಹೋಗುವುದನ್ನು ತಡೆಯಿರಿ"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ಫೋನ್ ಆಫ್ ಆಗುವುದರಿಂದ ತಡೆಯಿರಿ"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ಕಾರ್ ಸ್ಕ್ರೀನ್ ಅನ್ನು ಆನ್ನಲ್ಲೇ ಇರಿಸಲು ಆ್ಯಪ್ಗೆ ಅನುಮತಿಸುತ್ತದೆ."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ಟ್ಯಾಬ್ಲೆಟ್ ನಿದ್ರೆಗೆ ಹೋಗುವುದನ್ನು ತಡೆಯಲು ಅಪ್ಲಿಕೇಶನ್ಗೆ ಅನುಮತಿಸುತ್ತದೆ."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ನಿಮ್ಮ Android TV ಸಾಧನವು ನಿದ್ರಾವಸ್ಥೆಗೆ ಹೋಗುವುದನ್ನು ತಡೆಯಲು ಅಪ್ಲಿಕೇಶನ್ಗೆ ಅನುಮತಿಸುತ್ತದೆ."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ಫೋನ್ ನಿದ್ರೆಗೆ ಹೋಗುವುದನ್ನು ತಡೆಯಲು ಅಪ್ಲಿಕೇಶನ್ಗೆ ಅನುಮತಿಸುತ್ತದೆ."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"ವಾಲ್ಯೂಮ್ ಅನ್ನು ಶಿಫಾರಸು ಮಾಡಲಾದ ಮಟ್ಟಕ್ಕಿಂತಲೂ ಹೆಚ್ಚು ಮಾಡುವುದೇ?\n\nದೀರ್ಘ ಅವಧಿಯವರೆಗೆ ಹೆಚ್ಚಿನ ವಾಲ್ಯೂಮ್ನಲ್ಲಿ ಆಲಿಸುವುದರಿಂದ ನಿಮ್ಮ ಆಲಿಸುವಿಕೆ ಸಾಮರ್ಥ್ಯಕ್ಕೆ ಹಾನಿಯುಂಟು ಮಾಡಬಹುದು."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ಪ್ರವೇಶಿಸುವಿಕೆ ಶಾರ್ಟ್ಕಟ್ ಬಳಸುವುದೇ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ಶಾರ್ಟ್ಕಟ್ ಆನ್ ಆಗಿರುವಾಗ, ಎರಡೂ ವಾಲ್ಯೂಮ್ ಬಟನ್ಗಳನ್ನು 3 ಸೆಕೆಂಡುಗಳ ಕಾಲ ಒತ್ತಿದರೆ ಪ್ರವೇಶಿಸುವಿಕೆ ವೈಶಿಷ್ಟ್ಯವೊಂದು ಪ್ರಾರಂಭವಾಗುತ್ತದೆ."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ಶಾರ್ಟ್ಕಟ್ಗಳನ್ನು ಎಡಿಟ್ ಮಾಡಿ"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ರದ್ದುಗೊಳಿಸಿ"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ಶಾರ್ಟ್ಕಟ್ ಆಫ್ ಮಾಡಿ"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ಅನ್ನು ನಿರ್ಬಂಧಿತ ಬಕೆಟ್ಗೆ ಹಾಕಲಾಗಿದೆ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ವೈಯಕ್ತಿಕ"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ಕೆಲಸ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ಕೆಲಸದ ಆ್ಯಪ್ಗಳೊಂದಿಗೆ ಹಂಚಿಕೊಳ್ಳಲು ಸಾಧ್ಯವಿಲ್ಲ"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ವೈಯಕ್ತಿಕ ಆ್ಯಪ್ಗಳೊಂದಿಗೆ ಹಂಚಿಕೊಳ್ಳಲು ಸಾಧ್ಯವಿಲ್ಲ"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ನಿಮ್ಮ ಐಟಿ ನಿರ್ವಾಹಕರು, ವೈಯಕ್ತಿಕ ಮತ್ತು ಕೆಲಸಕ್ಕೆ ಸಂಬಂಧಿಸಿದ ಆ್ಯಪ್ಗಳ ನಡುವೆ ಹಂಚಿಕೊಳ್ಳುವುದನ್ನು ನಿರ್ಬಂಧಿಸಿದ್ದಾರೆ"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ಕೆಲಸಕ್ಕೆ ಸಂಬಂಧಿಸಿದ ಆ್ಯಪ್ಗಳನ್ನು ಆನ್ ಮಾಡಿ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ಕೆಲಸಕ್ಕೆ ಸಂಬಂಧಿಸಿದ ಆ್ಯಪ್ಗಳು ಮತ್ತು ಸಂಪರ್ಕಗಳನ್ನು ಪ್ರವೇಶಿಸಲು, ಕೆಲಸಕ್ಕೆ ಸಂಬಂಧಿಸಿದ ಆ್ಯಪ್ಗಳನ್ನು ಆನ್ ಮಾಡಿ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ಯಾವುದೇ ಆ್ಯಪ್ಗಳು ಲಭ್ಯವಿಲ್ಲ"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ನಮಗೆ ಯಾವುದೇ ಆ್ಯಪ್ಗಳನ್ನು ಹುಡುಕಲು ಸಾಧ್ಯವಾಗಲಿಲ್ಲ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ಉದ್ಯೋಗ ಪ್ರೊಫೈಲ್ ಅನ್ನು ಆನ್ ಮಾಡಿ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ಫೋನ್ ಕರೆಗಳಲ್ಲಿ ಆಡಿಯೊವನ್ನು ರೆಕಾರ್ಡ್ ಮಾಡಿ ಅಥವಾ ಪ್ಲೇ ಮಾಡಿ"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ಡೀಫಾಲ್ಟ್ ಡಯಲರ್ ಅಪ್ಲಿಕೇಶನ್ ರೀತಿ ಬಳಸಿದಾಗ ಫೋನ್ ಕರೆಗಳಲ್ಲಿ ಆಡಿಯೊವನ್ನು ರೆಕಾರ್ಡ್ ಮಾಡಲು ಅಥವಾ ಪ್ಲೇ ಮಾಡಲು ಈ ಆ್ಯಪ್ ಅನ್ನು ಅನುಮತಿಸಿ."</string>
</resources>
diff --git a/core/res/res/values-ko/strings.xml b/core/res/res/values-ko/strings.xml
index 7ec0e77..f7c24da8 100644
--- a/core/res/res/values-ko/strings.xml
+++ b/core/res/res/values-ko/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">버그 신고 스크린샷을 <xliff:g id="NUMBER_1">%d</xliff:g>초 후에 찍습니다.</item>
<item quantity="one">버그 신고 스크린샷을 <xliff:g id="NUMBER_0">%d</xliff:g>초 후에 찍습니다.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"버그 신고용 스크린샷 촬영 완료"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"버그 신고용 스크린샷 촬영 실패"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"무음 모드"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"소리 꺼짐"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"소리 켜짐"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"다른 앱에서 수신한 전화를 계속하려면 앱을 허용합니다."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"전화번호 읽기"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"앱에서 기기의 전화번호에 액세스하도록 허용합니다."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"차량 화면 켜진 상태로 유지"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"태블릿이 절전 모드로 전환되지 않도록 설정"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV 기기 절전 모드 해제"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"휴대전화가 절전 모드로 전환되지 않도록 설정"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"앱에서 차량 화면을 켜진 상태로 유지하도록 허용합니다."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"앱이 태블릿의 절전 모드 전환을 막도록 허용합니다."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"앱이 Android TV 기기가 절전 모드로 전환되지 않게 막도록 허용합니다."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"앱이 휴대전화의 절전 모드 전환을 막도록 허용합니다."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"권장 수준 이상으로 볼륨을 높이시겠습니까?\n\n높은 볼륨으로 장시간 청취하면 청력에 손상이 올 수 있습니다."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"접근성 단축키를 사용하시겠습니까?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"단축키가 사용 설정된 경우 볼륨 버튼 두 개를 동시에 3초간 누르면 접근성 기능이 시작됩니다."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"단축키 수정"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"취소"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"단축키 사용 중지"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"지정된 카테고리 없음"</string>
<string name="importance_from_user" msgid="2782756722448800447">"이러한 알림의 중요도를 설정했습니다."</string>
<string name="importance_from_person" msgid="4235804979664465383">"관련된 사용자가 있으므로 중요합니다."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"맞춤 앱 알림"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g>에서 <xliff:g id="ACCOUNT">%2$s</xliff:g> 계정으로 신규 사용자를 만들도록 허용하시겠습니까? 이 계정으로 등록된 사용자가 이미 존재합니다."</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g>에서 <xliff:g id="ACCOUNT">%2$s</xliff:g> 계정으로 신규 사용자를 만들도록 허용하시겠습니까?"</string>
<string name="language_selection_title" msgid="52674936078683285">"언어 추가"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> 항목이 RESTRICTED 버킷으로 이동함"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"개인"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"직장"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"직장 앱과 공유할 수 없음"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"개인 앱과 공유할 수 없음"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT 관리자가 개인 앱과 직장 앱 간의 공유를 차단함"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"직장 앱 사용 설정"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"직장 앱 및 연락처에 액세스하도록 직장 앱 사용 설정"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"사용 가능한 앱 없음"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"앱을 찾을 수 없음"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"직장 프로필 사용"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"전화 통화 중에 오디오 녹음 또는 재생"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"이 앱이 기본 다이얼러 애플리케이션으로 지정되었을 때 전화 통화 중에 오디오를 녹음하거나 재생하도록 허용합니다."</string>
</resources>
diff --git a/core/res/res/values-ky/strings.xml b/core/res/res/values-ky/strings.xml
index 74e03c0..b04863c 100644
--- a/core/res/res/values-ky/strings.xml
+++ b/core/res/res/values-ky/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Мүчүлүштүк тууралуу кабарлоо үчүн <xliff:g id="NUMBER_1">%d</xliff:g> секундда скриншот алынат.</item>
<item quantity="one">Мүчүлүштүк тууралуу кабарлоо үчүн <xliff:g id="NUMBER_0">%d</xliff:g> секундда скриншот алынат.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Мүчүлүштүк тууралуу кабар берүү үчүн скриншот тартылды"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Мүчүлүштүк тууралуу кабар берүү үчүн скриншот тартылган жок"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Үнсүз режим"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Добушу ӨЧҮК"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Добушу КҮЙҮК"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Башка колдонмодон аткарылган чалууну бул колдонмодо улантууга уруксат берүү."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"телефон номерлерин окуу"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Колдонмого түзмөктүн телефон номерлерин окуу мүмкүнчүлүгү берилет."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"унаанын экранын күйгүзүлгөн бойдон калтыруу"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"планшетти уктатпай сактоо"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV түзмөгүңүзгө уйку режимин күйгүзүүгө жол бербеңиз"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"телефонду уктатпай сактоо"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Колдонмого унаанын экранын күйгүзүлгөн бойдон калтырууга уруксат берет."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Колдонмо планшетти көшүү режимине өткөрбөйт."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Колдонмого Android TV түзмөгүңүзгө уйку режимин күйгүзүүгө жол бербөөгө уруксат берет."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Колдонмо телефонду көшүү режимине өткөрбөйт."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Сунушталган деңгээлден да катуулатып уккуңуз келеби?\n\nМузыканы узакка чейин катуу уксаңыз, угууңуз начарлап кетиши мүмкүн."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Ыкчам иштетесизби?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Атайын мүмкүнчүлүктөр функциясын пайдалануу үчүн ал күйгүзүлгөндө, үндү катуулатып/акырындаткан эки баскычты тең 3 секунддай коё бербей басып туруңуз."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Кыска жолдорду түзөтүү"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Жокко чыгаруу"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Кыска жолду өчүрүү"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Категорияларга бөлүнгөн эмес"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Бул эскертмелердин маанилүүлүгүн белгиледиңиз."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Булар сиз үчүн маанилүү адамдар."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Колдонмонун ыңгайлаштырылган билдирмеси"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> колдонмосуна <xliff:g id="ACCOUNT">%2$s</xliff:g> аккаунту менен жаңы колдонуучу түзүүгө уруксат бересизби (мындай аккаунту бар колдонуучу мурунтан эле бар)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> колдонмосуна <xliff:g id="ACCOUNT">%2$s</xliff:g> аккаунту менен жаңы колдонуучу түзүүгө уруксат бересизби?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Тил кошуу"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ЧЕКТЕЛГЕН чакага коюлган"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Жеке"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Жумуш"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Жумуш колдонмолору менен бөлүшүүгө болбойт"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Жеке колдонмолор менен бөлүшүүгө болбойт"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT администраторуңуз жеке жана жумуш колдонмолорунун ортосунда бөлүшүүнү бөгөттөп койгон"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Жумуш колдонмолорун күйгүзүү"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Жумуш колдонмолоруна жана байланыштарга кирүү үчүн жумуш колдонмолорун күйүгүзүңүз"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Колдонмолор жок"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Эч кандай колдонмо табылган жок"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Жумуш профилине которулуу"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Телефон чалууларда жаздырып же аудиону ойнотуу"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Бул колдонмо демейки телефон катары дайындалганда ага чалууларды жаздырууга жана аудиону ойнотууга уруксат берет."</string>
</resources>
diff --git a/core/res/res/values-lo/strings.xml b/core/res/res/values-lo/strings.xml
index 862aa53..92ab1d3 100644
--- a/core/res/res/values-lo/strings.xml
+++ b/core/res/res/values-lo/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">ກຳລັງຈະຖ່າຍພາບໜ້າຈໍສຳລັບການລາຍງານຂໍ້ຜິດພາດໃນ <xliff:g id="NUMBER_1">%d</xliff:g> ວິນາທີ.</item>
<item quantity="one">ກຳລັງຈະຖ່າຍພາບໜ້າຈໍສຳລັບການລາຍງານຂໍ້ຜິດພາດໃນ <xliff:g id="NUMBER_0">%d</xliff:g> ວິນາທີ.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ຖ່າຍຮູບໜ້າຈໍກັບການລາຍງານຂໍ້ຜິດພາດແລ້ວ"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ຖ່າຍຮູບໜ້າຈໍກັບການລາຍງານຂໍ້ຜິດພາດບໍ່ສຳເລັດ"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"ໂໝດປິດສຽງ"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ປິດສຽງແລ້ວ"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ເປິດສຽງແລ້ວ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"ອະນຸຍາດໃຫ້ແອັບສືບຕໍ່ການໂທເຊິ່ງອາດຖືກເລີ່ມຕົ້ນໃນແອັບອື່ນ."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ອ່ານເບີໂທລະສັບ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ອະນຸຍາດໃຫ້ແອັບເຂົ້າເຖິງເບີໂທລະສັບຂອງອຸປະກອນໄດ້."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ເປີດໜ້າຈໍລົດໄວ້ຕະຫຼອດ"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ຂັດຂວາງບໍ່ໃຫ້ປິດໜ້າຈໍແທັບເລັດ"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ປ້ອງກັນບໍ່ໃຫ້ອຸປະກອນ Android TV ຂອງທ່ານນອນ"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ຂັດຂວາງບໍ່ໃຫ້ໂທລະສັບປິດໜ້າຈໍ"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ອະນຸຍາດໃຫ້ແອັບເຮັດໃຫ້ໜ້າຈໍລົດເປີດໄວ້ຕະຫຼອດ."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ອະນຸຍາດໃຫ້ແອັບຯ ປ້ອງກັນບໍ່ໃຫ້ປິດໜ້າຈໍແທັບເລັດ."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ອະນຸຍາດໃຫ້ແອັບປ້ອງກັນບໍ່ໃຫ້ອຸປະກອນ Android TV ຂອງທ່ານນອນ."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ອະນຸຍາດໃຫ້ແອັບຯປ້ອງກັນບໍ່ໃຫ້ປິດໜ້າຈໍໂທລະສັບ."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"ເພີ່ມລະດັບສຽງໃຫ້ເກີນກວ່າລະດັບທີ່ແນະນຳບໍ?\n\nການຮັບຟັງສຽງໃນລະດັບທີ່ສູງເປັນໄລຍະເວລາດົນອາດເຮັດໃຫ້ການຟັງຂອງທ່ານມີບັນຫາໄດ້."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ໃຊ້ປຸ່ມລັດການຊ່ວຍເຂົ້າເຖິງບໍ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ເມື່ອເປີດໃຊ້ທາງລັດແລ້ວ, ການກົດປຸ່ມລະດັບສຽງທັງສອງຄ້າງໄວ້ 3 ວິນາທີຈະເປັນການເລີ່ມຄຸນສົມບັດການຊ່ວຍເຂົ້າເຖິງ."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ແກ້ໄຂທາງລັດ"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ຍົກເລີກ"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ປິດປຸ່ມລັດ"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"ບໍ່ມີໝວດໝູ່"</string>
<string name="importance_from_user" msgid="2782756722448800447">"ທ່ານຕັ້ງຄວາມສຳຄັນຂອງການແຈ້ງເຕືອນເຫຼົ່ານີ້."</string>
<string name="importance_from_person" msgid="4235804979664465383">"ຂໍ້ຄວາມນີ້ສຳຄັນເນື່ອງຈາກບຸກຄົນທີ່ກ່ຽວຂ້ອງ."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"ການແຈ້ງເຕືອນແອັບແບບກຳນົດເອງ"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"ອະນຸຍາດໃຫ້ <xliff:g id="APP">%1$s</xliff:g> ສ້າງຜູ້ໃຊ້ໃໝ່ກັບ <xliff:g id="ACCOUNT">%2$s</xliff:g> ໄດ້ບໍ່ (ມີຜູ້ໃຊ້ທີ່ໃຊ້ບັນຊີນີ້ຢູ່ກ່ອນແລ້ວ) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"ອະນຸຍາດໃຫ້ <xliff:g id="APP">%1$s</xliff:g> ສ້າງຜູ້ໃຊ້ໃໝ່ກັບ <xliff:g id="ACCOUNT">%2$s</xliff:g> ໄດ້ບໍ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"ເພີ່ມພາສາ"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ຖືກວາງໄວ້ໃນກະຕ່າ \"ຈຳກັດ\" ແລ້ວ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ສ່ວນຕົວ"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ວຽກ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ບໍ່ສາມາດແບ່ງປັນກັບແອັບວຽກໄດ້"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ບໍ່ສາມາດແບ່ງປັນກັບແອັບສ່ວນຕົວໄດ້"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ຜູ້ເບິ່ງແຍງໄອທີຂອງທ່ານບລັອກການແບ່ງປັນລະຫວ່າງແອັບສ່ວນຕົວ ແລະ ແອັບວຽກໄວ້"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ປຸ່ມເປີດຢູ່ແອັບວຽກ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ເປີດໃຊ້ແອັບວຽກເພື່ອເຂົ້າເຖິງແອັບ ແລະ ລາຍຊື່ຜູ້ຕິດຕໍ່ວຽກ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ບໍ່ມີແອັບທີ່ສາມາດໃຊ້ໄດ້"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ພວກເຮົາບໍ່ພົບແອັບໃດໆເລີຍ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ປຸ່ມເປີດຢູ່ວຽກ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ບັນທຶກ ຫຼື ຫຼິ້ນສຽງໃນການໂທລະສັບ"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ອະນຸຍາດແອັບນີ້, ເມື່ອມອບໝາຍເປັນແອັບພລິເຄຊັນໂທລະສັບເລີ່ມຕົ້ນເພື່ອບັນທຶກ ຫຼື ຫຼິ້ນສຽງໃນການໂທລະສັບ."</string>
</resources>
diff --git a/core/res/res/values-lt/strings.xml b/core/res/res/values-lt/strings.xml
index e816f5e..518bb18 100644
--- a/core/res/res/values-lt/strings.xml
+++ b/core/res/res/values-lt/strings.xml
@@ -255,10 +255,8 @@
<item quantity="many">Pranešimo apie riktą ekrano kopija bus užfiksuota po <xliff:g id="NUMBER_1">%d</xliff:g> sekundės.</item>
<item quantity="other">Pranešimo apie riktą ekrano kopija bus užfiksuota po <xliff:g id="NUMBER_1">%d</xliff:g> sekundžių.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Sukurta ekrano kopija su pranešimu apie riktą"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Nepavyko sukurti ekrano kopijos su pranešimu apie riktą"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Tylus režimas"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Garsas IŠJUNGTAS"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Garsas ĮJUNGTAS"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Programai leidžiama tęsti skambutį, kuris buvo pradėtas naudojant kitą programą."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"skaityti telefonų numerius"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Programai leidžiama pasiekti įrenginio telefonų numerius."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"palikti automobilio ekraną įjungtą"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"neleisti planšetiniam kompiuteriui užmigti"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"neleisti „Android TV“ įrenginiui užmigti"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"neleisti telefonui snausti"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Programai leidžiama palikti automobilio ekraną įjungtą."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Leidžiama programai neleisti planšetiniam kompiuteriui užmigti."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Programai leidžiama nustatyti, kad „Android TV“ įrenginys nebūtų perjungtas į miego būseną."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Leidžiama programai neleisti telefonui užmigti."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Padidinti garsą daugiau nei rekomenduojamas lygis?\n\nIlgai klausydami dideliu garsu galite pažeisti klausą."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Naudoti spartųjį pritaikymo neįgaliesiems klavišą?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kai spartusis klavišas įjungtas, paspaudus abu garsumo mygtukus ir palaikius 3 sekundes bus įjungta pritaikymo neįgaliesiems funkcija."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Redaguoti sparčiuosius klavišus"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Atšaukti"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Išjungti spartųjį klavišą"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Be kategorijos"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Galite nustatyti šių pranešimų svarbą."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Tai svarbu dėl susijusių žmonių."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Tinkintas programos pranešimas"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Leisti „<xliff:g id="APP">%1$s</xliff:g>“ kurti naują <xliff:g id="ACCOUNT">%2$s</xliff:g> naudotoją (šią paskyrą naudojantis naudotojas jau yra)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Leisti „<xliff:g id="APP">%1$s</xliff:g>“ kurti naują <xliff:g id="ACCOUNT">%2$s</xliff:g> naudotoją?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Pridėkite kalbą"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"„<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>“ įkeltas į grupę APRIBOTA"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Asmeninė"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Darbo"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Negalima bendrinti su darbo programomis"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Negalima bendrinti su asmeninėmis programomis"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT administratorius užblokavo bendrinimą tarp asmeninių programų ir darbo programų"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Įjunkite darbo programas"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Įjunkite darbo programas, kad galėtumėte pasiekti darbo programas ir kontaktus"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nėra pasiekiamų programų"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nepavyko rasti programų"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Įjungti darbo profilį"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Telefonų skambučių garso įrašo įrašymas arba leidimas"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Leidžiama šiai programai, esant prisijungus kaip numatytajai numerio rinkiklio programai, įrašyti ar leisti telefonų skambučių garso įrašą."</string>
</resources>
diff --git a/core/res/res/values-lv/strings.xml b/core/res/res/values-lv/strings.xml
index 8aa7e5a..afe8f9a 100644
--- a/core/res/res/values-lv/strings.xml
+++ b/core/res/res/values-lv/strings.xml
@@ -252,10 +252,8 @@
<item quantity="one">Pēc <xliff:g id="NUMBER_1">%d</xliff:g> sekundes tiks veikts ekrānuzņēmums kļūdas pārskatam.</item>
<item quantity="other">Pēc <xliff:g id="NUMBER_1">%d</xliff:g> sekundēm tiks veikts ekrānuzņēmums kļūdas pārskatam.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Izveidots ekrānuzņēmums ar kļūdas pārskatu."</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Neizdevās izveidot ekrānuzņēmumu ar kļūdas pārskatu."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Klusuma režīms"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Skaņa ir IZSLĒGTA."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Skaņa ir IESLĒGTA."</string>
@@ -457,9 +455,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Ļauj lietotnei turpināt zvanu, kas tika sākts citā lietotnē."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lasīt tālruņa numurus"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Ļauj lietotnei piekļūt ierīcē esošajiem tālruņa numuriem."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"paturēt ieslēgtu automašīnas ekrānu"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"novērst planšetdatora pāriešanu miega režīmā"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV miega režīma ieslēgšanas liegšana"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"novērst tālruņa pāriešanu miega režīmā"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Ļauj lietotnei paturēt ieslēgtu automašīnas ekrānu."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Ļauj lietotnei novērst planšetdatora pāriešanu miega režīmā."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Ļauj lietotnei novērst Android TV ierīces pāriešanu miega režīmā."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Ļauj lietotnei novērst tālruņa pāriešanu miega režīmā."</string>
@@ -1653,6 +1653,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Vai palielināt skaļumu virs ieteicamā līmeņa?\n\nIlgstoši klausoties skaņu lielā skaļumā, var tikt bojāta dzirde."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Vai izmantot pieejamības saīsni?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kad īsinājumtaustiņš ir ieslēgts, nospiežot abas skaļuma pogas un 3 sekundes turot tās, tiks aktivizēta pieejamības funkcija."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Rediģēt īsinājumtaustiņus"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Atcelt"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Izslēgt saīsni"</string>
@@ -1885,8 +1891,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nav kategorijas"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Jūs iestatījāt šo paziņojumu svarīguma līmeni."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Tas ir svarīgi iesaistīto personu dēļ."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Pielāgots lietotnes paziņojums"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Vai atļaut lietotnei <xliff:g id="APP">%1$s</xliff:g> izveidot jaunu lietotāju, izmantojot e-pasta adresi <xliff:g id="ACCOUNT">%2$s</xliff:g> (lietotājs ar šādu kontu jau pastāv)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Vai atļaut lietotnei <xliff:g id="APP">%1$s</xliff:g> izveidot jaunu lietotāju, izmantojot e-pasta adresi <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Pievienot valodu"</string>
@@ -2062,14 +2067,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Pakotne “<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>” ir ievietota ierobežotā kopā."</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Privātais profils"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Darba profils"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nevar kopīgot ar darba lietotnēm"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nevar kopīgot ar personīgajām lietotnēm"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Jūsu IT administrators bloķēja datu kopīgošanu starp personīgajām un darba lietotnēm."</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ieslēdziet darba lietotnes"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ieslēdziet darba lietotnes, lai piekļūtu darba lietotnēm un kontaktpersonām."</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nav pieejamu lietotņu"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Netika atrasta neviena lietotne."</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ieslēgt darba profilu"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Ierakstīt vai atskaņot audio tālruņa sarunās"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Ļauj šai lietotnei ierakstīt vai atskaņot audio tālruņa sarunās, kad tā ir iestatīta kā noklusējuma tālruņa lietojumprogramma."</string>
</resources>
diff --git a/core/res/res/values-mcc219/config.xml b/core/res/res/values-mcc219/config.xml
deleted file mode 100644
index 7ae82fa..0000000
--- a/core/res/res/values-mcc219/config.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2009, 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.
-*/
--->
-
-<!-- These resources are around just to allow their values to be customized
- for different hardware and product builds. -->
-<resources>
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
- <string-array name="config_twoDigitNumberPattern">
- <item>"92"</item>
- <item>"93"</item>
- <item>"94"</item>
- <item>"95"</item>
- <item>"96"</item>
- </string-array>
-
-</resources>
diff --git a/core/res/res/values-mcc220/config.xml b/core/res/res/values-mcc220/config.xml
deleted file mode 100644
index 7ae82fa..0000000
--- a/core/res/res/values-mcc220/config.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2009, 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.
-*/
--->
-
-<!-- These resources are around just to allow their values to be customized
- for different hardware and product builds. -->
-<resources>
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
- <string-array name="config_twoDigitNumberPattern">
- <item>"92"</item>
- <item>"93"</item>
- <item>"94"</item>
- <item>"95"</item>
- <item>"96"</item>
- </string-array>
-
-</resources>
diff --git a/core/res/res/values-mcc310-mnc150/config.xml b/core/res/res/values-mcc310-mnc150/config.xml
deleted file mode 100644
index e7d1325..0000000
--- a/core/res/res/values-mcc310-mnc150/config.xml
+++ /dev/null
@@ -1,45 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2013, 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.
-*/
--->
-
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string-array translatable="false" name="config_twoDigitNumberPattern">
- <item>"0"</item>
- <item>"00"</item>
- <item>"*0"</item>
- <item>"*1"</item>
- <item>"*2"</item>
- <item>"*3"</item>
- <item>"*4"</item>
- <item>"*5"</item>
- <item>"*6"</item>
- <item>"*7"</item>
- <item>"*8"</item>
- <item>"*9"</item>
- <item>"#0"</item>
- <item>"#1"</item>
- <item>"#2"</item>
- <item>"#3"</item>
- <item>"#4"</item>
- <item>"#5"</item>
- <item>"#6"</item>
- <item>"#7"</item>
- <item>"#8"</item>
- <item>"#9"</item>
- </string-array>
-</resources>
diff --git a/core/res/res/values-mcc310-mnc410/config.xml b/core/res/res/values-mcc310-mnc410/config.xml
index 3fb3f0f..53e4193 100644
--- a/core/res/res/values-mcc310-mnc410/config.xml
+++ b/core/res/res/values-mcc310-mnc410/config.xml
@@ -23,31 +23,6 @@
<!-- Configure mobile network MTU. Carrier specific value is set here.
-->
<integer name="config_mobile_mtu">1410</integer>
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
- <string-array name="config_twoDigitNumberPattern">
- <item>"0"</item>
- <item>"00"</item>
- <item>"*0"</item>
- <item>"*1"</item>
- <item>"*2"</item>
- <item>"*3"</item>
- <item>"*4"</item>
- <item>"*5"</item>
- <item>"*6"</item>
- <item>"*7"</item>
- <item>"*8"</item>
- <item>"*9"</item>
- <item>"#0"</item>
- <item>"#1"</item>
- <item>"#2"</item>
- <item>"#3"</item>
- <item>"#4"</item>
- <item>"#5"</item>
- <item>"#6"</item>
- <item>"#7"</item>
- <item>"#8"</item>
- <item>"#9"</item>
- </string-array>
<!-- Enable 5 bar signal strength icon -->
<bool name="config_inflateSignalStrength">true</bool>
diff --git a/core/res/res/values-mcc313-mnc100/config.xml b/core/res/res/values-mcc313-mnc100/config.xml
deleted file mode 100644
index ccd03f1..0000000
--- a/core/res/res/values-mcc313-mnc100/config.xml
+++ /dev/null
@@ -1,45 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2019, 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.
-*/
--->
-
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string-array translatable="false" name="config_twoDigitNumberPattern">
- <item>"0"</item>
- <item>"00"</item>
- <item>"*0"</item>
- <item>"*1"</item>
- <item>"*2"</item>
- <item>"*3"</item>
- <item>"*4"</item>
- <item>"*5"</item>
- <item>"*6"</item>
- <item>"*7"</item>
- <item>"*8"</item>
- <item>"*9"</item>
- <item>"#0"</item>
- <item>"#1"</item>
- <item>"#2"</item>
- <item>"#3"</item>
- <item>"#4"</item>
- <item>"#5"</item>
- <item>"#6"</item>
- <item>"#7"</item>
- <item>"#8"</item>
- <item>"#9"</item>
- </string-array>
-</resources>
diff --git a/core/res/res/values-mcc334-mnc050/config.xml b/core/res/res/values-mcc334-mnc050/config.xml
index 23678f1..2e8c504 100644
--- a/core/res/res/values-mcc334-mnc050/config.xml
+++ b/core/res/res/values-mcc334-mnc050/config.xml
@@ -31,8 +31,4 @@
<item>9</item>
</integer-array>
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
- <string-array translatable="false" name="config_twoDigitNumberPattern">
- <item>"#9"</item>
- </string-array>
</resources>
diff --git a/core/res/res/values-mcc334-mnc090/config.xml b/core/res/res/values-mcc334-mnc090/config.xml
deleted file mode 100644
index 1632a42..0000000
--- a/core/res/res/values-mcc334-mnc090/config.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2017, 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 my 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.
-*/
--->
-
-<!-- These resources are around just to allow their values to be customized
- for different hardware and product builds. -->
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
-
- <string-array translatable="false" name="config_twoDigitNumberPattern">
- <item>"#9"</item>
- </string-array>
-</resources>
diff --git a/core/res/res/values-mcc704-mnc01/config.xml b/core/res/res/values-mcc704-mnc01/config.xml
deleted file mode 100644
index 10b6470..0000000
--- a/core/res/res/values-mcc704-mnc01/config.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2016, 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 my 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.
-*/
--->
-
-<resources>
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
- <string-array name="config_twoDigitNumberPattern">
- <item>"*1"</item>
- <item>"*5"</item>
- <item>"*9"</item>
- </string-array>
-</resources>
diff --git a/core/res/res/values-mcc708-mnc001/config.xml b/core/res/res/values-mcc708-mnc001/config.xml
deleted file mode 100755
index 7b7c48d..0000000
--- a/core/res/res/values-mcc708-mnc001/config.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2016, 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 my 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.
-*/
--->
-
-<!-- These resources are around just to allow their values to be customized
- for different hardware and product builds. -->
-<resources>
- <string-array translatable="false" name="config_twoDigitNumberPattern">
- <item>"*1"</item>
- <item>"*5"</item>
- </string-array>
-</resources>
diff --git a/core/res/res/values-ml/strings.xml b/core/res/res/values-ml/strings.xml
index 1513db1..8bf137f 100644
--- a/core/res/res/values-ml/strings.xml
+++ b/core/res/res/values-ml/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">ബഗ് റിപ്പോർട്ടിനായി <xliff:g id="NUMBER_1">%d</xliff:g> സെക്കൻഡിൽ സ്ക്രീൻഷോട്ട് എടുക്കുന്നു.</item>
<item quantity="one">ബഗ് റിപ്പോർട്ടിനായി <xliff:g id="NUMBER_0">%d</xliff:g> സെക്കൻഡിൽ സ്ക്രീൻഷോട്ട് എടുക്കുന്നു.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ബഗ് റിപ്പോർട്ടിന്റെ സ്ക്രീൻഷോട്ട് എടുത്തു"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ബഗ് റിപ്പോർട്ടിന്റെ സ്ക്രീൻഷോട്ട് എടുക്കാനായില്ല"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"നിശബ്ദ മോഡ്"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ശബ്ദം ഓഫാണ്"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ശബ്ദം ഓണാണ്"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"മറ്റൊരു ആപ്പിൽ ആരംഭിച്ച കോൾ തുടരാൻ ആപ്പിനെ അനുവദിക്കുന്നു."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ഫോൺ നമ്പറുകൾ റീഡുചെയ്യൽ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ഉപകരണത്തിന്റെ ഫോൺ നമ്പറുകൾ ആക്സസ് ചെയ്യാൻ ആപ്പിനെ അനുവദിക്കുന്നു."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"കാറിലെ സ്ക്രീൻ ഓണാക്കി വയ്ക്കുക"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ഉറങ്ങുന്നതിൽ നിന്ന് ടാബ്ലെറ്റിനെ തടയുക"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"നിങ്ങളുടെ Android ടിവി ഉറങ്ങുന്നതിൽ നിന്ന് തടയുക"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ഉറങ്ങുന്നതിൽ നിന്ന് ഫോണിനെ തടയുക"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"കാറിലെ സ്ക്രീൻ ഓണാക്കി വയ്ക്കാൻ ആപ്പിനെ അനുവദിക്കുന്നു."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ടാബ്ലെറ്റ് സുഷുപ്തിയിലാകുന്നതിൽ നിന്നും തടയുന്നതിന് അപ്ലിക്കേഷനെ അനുവദിക്കുന്നു."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"നിങ്ങളുടെ Android ടിവിയെ ഉറങ്ങുന്നതിൽ നിന്ന് തടയാൻ ആപ്പിനെ അനുവദിക്കുന്നു."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ഫോൺ സുഷുപ്തിയിലാകുന്നതിൽ നിന്നും തടയുന്നതിന് അപ്ലിക്കേഷനെ അനുവദിക്കുന്നു."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"മുകളിൽക്കൊടുത്തിരിക്കുന്ന ശുപാർശചെയ്ത ലെവലിലേക്ക് വോളിയം വർദ്ധിപ്പിക്കണോ?\n\nഉയർന്ന വോളിയത്തിൽ ദീർഘനേരം കേൾക്കുന്നത് നിങ്ങളുടെ ശ്രവണ ശേഷിയെ ദോഷകരമായി ബാധിക്കാം."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ഉപയോഗസഹായി കുറുക്കുവഴി ഉപയോഗിക്കണോ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"കുറുക്കുവഴി ഓണായിരിക്കുമ്പോൾ, രണ്ട് വോളിയം ബട്ടണുകളും 3 സെക്കൻഡ് നേരത്തേക്ക് അമർത്തുന്നത് ഉപയോഗസഹായി ഫീച്ചർ ആരംഭിക്കും."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"കുറുക്കുവഴികൾ തിരുത്തുക"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"റദ്ദാക്കുക"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"കുറുക്കുവഴി ഓഫാക്കുക"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> നിയന്ത്രിത ബക്കറ്റിലേക്ക് നീക്കി"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"വ്യക്തിപരമായത്"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ജോലിസ്ഥലം"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ഔദ്യോഗിക ആപ്പുകൾ ഉപയോഗിച്ച് പങ്കിടാനാവില്ല"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"വ്യക്തിപരമാക്കിയ ആപ്പുകൾ ഉപയോഗിച്ച് പങ്കിടാനാവില്ല"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"വ്യക്തിപരമാക്കിയ ആപ്പുകളുടെയും ഔദ്യോഗിക ആപ്പുകളുടെയും ഇടയിലുള്ള പങ്കിടൽ നിങ്ങളുടെ ഐടി അഡ്മിൻ ബ്ലോക്ക് ചെയ്തു"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ഔദ്യോഗിക ആപ്പുകൾ ഓണാക്കുക"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ഔദ്യോഗിക ആപ്പുകൾ, കോൺടാക്റ്റുകൾ എന്നിവ ആക്സസ് ചെയ്യാൻ ഔദ്യോഗിക ആപ്പുകൾ ഓണാക്കുക"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ആപ്പുകളൊന്നും ലഭ്യമല്ല"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ഞങ്ങൾക്ക് ആപ്പുകളൊന്നും കണ്ടെത്താൻ കഴിഞ്ഞില്ല"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ഔദ്യോഗിക പ്രൊഫൈൽ ഓണാക്കുക"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ടെലിഫോൺ കോളുകൾ ചെയ്യുമ്പോൾ റെക്കോർഡ് ചെയ്യുക അല്ലെങ്കിൽ ഓഡിയോ പ്ലേ ചെയ്യുക"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ഡിഫോൾട്ട് ഡയലർ ആപ്പായി അസെെൻ ചെയ്യുന്ന സമയത്ത്, ടെലിഫോൺ കോളുകൾ ചെയ്യുമ്പോൾ റെക്കോർഡ് ചെയ്യാൻ അല്ലെങ്കിൽ ഓഡിയോ പ്ലേ ചെയ്യാൻ ഈ ആപ്പിനെ അനുവദിക്കുന്നു."</string>
</resources>
diff --git a/core/res/res/values-mn/strings.xml b/core/res/res/values-mn/strings.xml
index b61474d..4054a3a 100644
--- a/core/res/res/values-mn/strings.xml
+++ b/core/res/res/values-mn/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Алдааны тайлангийн дэлгэцийн зургийг <xliff:g id="NUMBER_1">%d</xliff:g> секундад авна.</item>
<item quantity="one">Алдааны тайлангийн дэлгэцийн зургийг <xliff:g id="NUMBER_0">%d</xliff:g> секундад авна.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Алдааны мэдээтэй дэлгэцийн зургийг дарлаа"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Алдааны мэдээтэй дэлгэцийн зургийг дарж чадсангүй"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Дуугүй горим"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Дуу хаагдсан"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Дуу асав"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Аппад өөр аппад эхлүүлсэн дуудлагыг үргэлжлүүлэхийг зөвшөөрдөг."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"утасны дугаарыг унших"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Төхөөрөмжийн утасны дугаарт хандах зөвшөөрлийг апп-д олгоно."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"машины дэлгэцийг асаалттай байлгах"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"таблетыг унтуулахгүй байлгах"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"таны Android TВ төхөөрөмжийг идэвхгүй болохоос сэргийлэх"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"утсыг унтуулахгүй байлгах"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Аппад машины дэлгэцийг асаалттай байлгахыг зөвшөөрдөг."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Апп нь таблетыг унтахаас сэргийлэх боломжтой"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Аппад таны Android ТВ төхөөрөмжийг идэвхгүй болохоос сэргийлэхийг зөвшөөрнө."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Апп нь утсыг унтахаас сэргийлэх боломжтой"</string>
@@ -1631,6 +1631,9 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Дууг санал болгосноос чанга болгож өсгөх үү?\n\nУрт хугацаанд чанга хөгжим сонсох нь таны сонсголыг муутгаж болно."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Хүртээмжийн товчлолыг ашиглах уу?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Товчлол асаалттай үед дууны түвшний хоёр товчлуурыг хамтад нь 3 секунд дарснаар хандалтын онцлогийг эхлүүлнэ."</string>
+ <string name="accessibility_select_shortcut_menu_title" msgid="7310194076629867377">"Ашиглахыг хүсэж буй хандалтын аппаа товших"</string>
+ <string name="accessibility_edit_shortcut_menu_button_title" msgid="6096484087245145325">"Хандалтын товчлуурын тусламжтай ашиглахыг хүсэж буй аппуудаа сонгох"</string>
+ <string name="accessibility_edit_shortcut_menu_volume_title" msgid="4849108668454490699">"Дууны түвшин тохируулах түлхүүрийн товчлолын тусламжтай ашиглахыг хүсэж буй аппуудаа сонгох"</string>
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Товчлолуудыг засах"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Болих"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Товчлолыг унтраах"</string>
@@ -1853,8 +1856,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Ангилаагүй"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Та эдгээр мэдэгдлийн ач холбогдлыг тогтоосон."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Оролцсон хүмүүсээс шалтгаалан энэ нь өндөр ач холбогдолтой."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Аппын захиалгат мэдэгдэл"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g>-д <xliff:g id="ACCOUNT">%2$s</xliff:g>-тай (ийм бүртгэлтэй хэрэглэгч аль хэдийн байна) шинэ хэрэглэгч үүсгэхийг зөвшөөрөх үү ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g>-д <xliff:g id="ACCOUNT">%2$s</xliff:g>-тай шинэ хэрэглэгч үүсгэхийг зөвшөөрөх үү?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Хэл нэмэх"</string>
@@ -2028,14 +2030,19 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>-г ХЯЗГААРЛАСАН сагс руу орууллаа"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Хувийн"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Ажил"</string>
+ <string name="resolver_personal_tab_accessibility" msgid="5739524949153091224">"Хувийн харагдах байдал"</string>
+ <string name="resolver_work_tab_accessibility" msgid="4753168230363802734">"Ажлын харагдах байдал"</string>
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ажлын аппуудтай хуваалцах боломжгүй"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Хувийн аппуудтай хуваалцах боломжгүй"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Танай IT админ хувийн болон ажлын аппуудын хооронд хуваалцахыг блоклосон."</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ажлын аппуудыг асаана уу"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ажлын апп, харилцагчдад хандахын тулд ажлын аппыг асаана уу"</string>
+ <string name="resolver_cant_share_cross_profile_explanation" msgid="5556640604460901386">"Таны IT админ хувийн болон ажлын профайлуудын хооронд хуваалцахыг блоклосон"</string>
+ <string name="resolver_cant_access_work_apps" msgid="375634344111233790">"Ажлын аппуудад хандах боломжгүй байна"</string>
+ <string name="resolver_cant_access_work_apps_explanation" msgid="3958762224516867388">"Таны IT админ ажлын аппууд дахь хувийн контентыг харахыг танд зөвшөөрөхгүй байна"</string>
+ <string name="resolver_cant_access_personal_apps" msgid="1953215925406474177">"Хувийн аппуудад хандах боломжгүй байна"</string>
+ <string name="resolver_cant_access_personal_apps_explanation" msgid="1725572276741281136">"Таны IT админ хувийн аппууд дахь ажлын контентыг харахыг танд зөвшөөрөхгүй байна"</string>
+ <string name="resolver_turn_on_work_apps_share" msgid="619263911204978175">"Контентыг хуваалцахын тулд ажлын профайлыг асаана уу"</string>
+ <string name="resolver_turn_on_work_apps_view" msgid="3073389230905543680">"Контентыг харахын тулд ажлын профайлыг асаана уу"</string>
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Боломжтой апп алга байна"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Бид ямар ч апп олж чадсангүй"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ажил дээр сэлгэх"</string>
+ <string name="resolver_switch_on_work" msgid="2873009160846966379">"Асаах"</string>
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Утасны дуудлагын үеэр аудио бичих эсвэл тоглуулах"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Энэ аппыг залгагч өгөгдмөл аппликэйшн болгосон үед түүнд утасны дуудлагын үеэр аудио бичих эсвэл тоглуулахыг зөвшөөрдөг."</string>
</resources>
diff --git a/core/res/res/values-mr/strings.xml b/core/res/res/values-mr/strings.xml
index d3c31a5..94b779b 100644
--- a/core/res/res/values-mr/strings.xml
+++ b/core/res/res/values-mr/strings.xml
@@ -193,14 +193,10 @@
<string name="network_logging_notification_text" msgid="1327373071132562512">"तुमची संस्था हे डिव्हाइस व्यवस्थापित करते आणि नेटवर्क रहदारीचे निरीक्षण करू शकते. तपशीलांसाठी टॅप करा."</string>
<string name="location_changed_notification_title" msgid="4119726617105166830">"तुमच्या ॲडमिनने स्थान सेटिंग्ज बदलल्या आहेत"</string>
<string name="location_changed_notification_text" msgid="198907268219396399">"तुमची स्थान सेटिंग्ज पाहण्यासाठी टॅप करा."</string>
- <!-- no translation found for country_detector (7023275114706088854) -->
- <skip />
- <!-- no translation found for location_service (2439187616018455546) -->
- <skip />
- <!-- no translation found for sensor_notification_service (7474531979178682676) -->
- <skip />
- <!-- no translation found for twilight_service (8964898045693187224) -->
- <skip />
+ <string name="country_detector" msgid="7023275114706088854">"कंट्री डिटेक्टर"</string>
+ <string name="location_service" msgid="2439187616018455546">"स्थान सेवा"</string>
+ <string name="sensor_notification_service" msgid="7474531979178682676">"सेंसर सूचना सेवा"</string>
+ <string name="twilight_service" msgid="8964898045693187224">"ट्वायलाइट सेवा"</string>
<string name="factory_reset_warning" msgid="6858705527798047809">"तुमचे डिव्हाइस मिटविले जाईल"</string>
<string name="factory_reset_message" msgid="2657049595153992213">"प्रशासक अॅप वापरता येणार नाही. तुमचे डिव्हाइस आता साफ केले जाईल.\n\nतुम्हाला कुठलेही प्रश्न असल्यास, तुमच्या संस्थेच्या प्रशासकाशी संपर्क साधा."</string>
<string name="printing_disabled_by" msgid="3517499806528864633">"<xliff:g id="OWNER_APP">%s</xliff:g> नी प्रिंट करणे बंद केले आहे."</string>
@@ -253,10 +249,8 @@
<item quantity="other">दोष अहवालासाठी <xliff:g id="NUMBER_1">%d</xliff:g> सेकंदांमध्ये स्क्रीनशॉट घेत आहे.</item>
<item quantity="one">दोष अहवालासाठी <xliff:g id="NUMBER_0">%d</xliff:g> सेकंदामध्ये स्क्रीनशॉट घेत आहे.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"बग रिपोर्टसह घेतलेला स्क्रीनशॉट"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"बग रिपोर्टसह स्क्रीनशॉट घेता आला नाही"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"मूक मोड"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ध्वनी बंद आहे"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ध्वनी चालू आहे"</string>
@@ -458,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"दुसऱ्या ॲपमध्ये सुरू झालेल्या कॉलला पुढे सुरू ठेवण्याची ॲपला अनुमती देते."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"फोन नंबर वाचा"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ॲपला डिव्हाइसच्या फोन नंबरमध्ये प्रवेश करण्याची अनुमती देते."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"कारची स्क्रीन सुरू ठेवा"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"टॅबलेट निष्क्रिय होण्यापासून प्रतिबंधित करा"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"तुमच्या Android TV डिव्हाइसला स्लीप मोडमध्ये जाण्यापासून थांबवा"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"फोन निष्क्रिय होण्यापासून प्रतिबंधित करा"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ॲपला कारची स्क्रीन सुरू ठेवण्याची अनुमती देते."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"टॅब्लेटला निष्क्रिय होण्यापासून प्रतिबंधित करण्यासाठी अॅप ला अनुमती देते."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Android TV डिव्हाइसला स्लीप मोडमध्ये जाण्यापासून प्रतिबंधित करण्यासाठी ॲपला अनुमती देते."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"फोनला निष्क्रिय होण्यापासून प्रतिबंधित करण्यासाठी अॅप ला अनुमती देते."</string>
@@ -1635,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"शिफारस केलेल्या पातळीच्या वर आवाज वाढवायचा?\n\nउच्च आवाजात दीर्घ काळ ऐकण्याने आपल्या श्रवणशक्तीची हानी होऊ शकते."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"प्रवेशयोग्यता शॉर्टकट वापरायचा?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"शॉर्टकट सुरू असताना, दोन्ही व्हॉल्यूम बटणे तीन सेकंदांसाठी दाबून ठेवल्याने अॅक्सेसिबिलिटी वैशिष्ट्य सुरू होईल."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"शॉर्टकट संपादित करा"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"रद्द करा"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"शॉर्टकट बंद करा"</string>
@@ -2032,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> हे प्रतिबंधित बादलीमध्ये ठेवण्यात आले आहे"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"वैयक्तिक"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ऑफिस"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ऑफिस ॲप्स सोबत शेअर करू शकत नाही"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"वैयक्तिक अॅप्स सोबत शेअर करू शकत नाही"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"तुमच्या आयटी ॲडमिनने वैयक्तिक आणि ऑफिस ॲप्स दरम्यान शेअर करणे ब्लॉक केले आहे"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ऑफिस अॅप्स सुरू करा"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ऑफिस ॲप्स & संपर्क अॅक्सेस करण्यासाठी ऑफिस ॲप्स सुरू करा"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"कोणतीही अॅप्स उपलब्ध नाहीत"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"आम्हाला कोणतीही अॅप्स सापडली नाहीत"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ऑफिस प्रोफाइलवर स्विच करा"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"टेलिफोनी कॉलमध्ये ऑडिओ रेकॉर्ड करा किंवा प्ले करा"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"टेलिफोनी कॉलमध्ये ऑडिओ रेकॉर्ड करण्याची किंवा प्ले करण्यासाठी डीफॉल्ट डायलर अॅप्लिकेशन म्हणून असाइन केले असताना या ॲपला परवानगी देते."</string>
</resources>
diff --git a/core/res/res/values-ms/strings.xml b/core/res/res/values-ms/strings.xml
index 909fcc9..23606c0 100644
--- a/core/res/res/values-ms/strings.xml
+++ b/core/res/res/values-ms/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Mengambil tangkapan skrin untuk laporan pepijat dalam masa <xliff:g id="NUMBER_1">%d</xliff:g> saat.</item>
<item quantity="one">Mengambil tangkapan skrin untuk laporan pepijat dalam masa <xliff:g id="NUMBER_0">%d</xliff:g> saat.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Tangkapan skrin diambil dengan laporan pepijat"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Gagal mengambil tangkapan skrin dengan laporan pepijat"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mod senyap"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Bunyi DIMATIKAN"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Bunyi DIHIDUPKAN"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Membenarkan apl meneruskan panggilan yang dimulakan dalam apl lain."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"baca nombor telefon"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Membenarkan apl mengakses nombor telefon peranti."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"pastikan skrin kereta sentiasa hidup"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"menghalang tablet daripada tidur"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"menghalang peranti Android TV anda daripada tidur"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"halang telefon daripada tidur"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Membenarkan apl memastikan skrin kereta sentiasa hidup."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Membenarkan apl menghalang tablet daripada tidur."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Membenarkan apl menghalang peranti Android TV anda daripada tidur."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Membenarkan apl menghalang telefon daripada tidur."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Naikkan kelantangan melebihi paras yang disyokorkan?\n\nMendengar pada kelantangan yang tinggi untuk tempoh yang lama boleh merosakkan pendengaran anda."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Gunakan Pintasan Kebolehaksesan?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Apabila pintasan dihidupkan, tindakan menekan kedua-dua butang kelantangan selama 3 saat akan memulakan ciri kebolehaksesan."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edit pintasan"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Batal"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Matikan pintasan"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Tidak dikategorikan"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Anda menetapkan kepentingan pemberitahuan ini."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Mesej ini penting disebabkan orang yang terlibat."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Pemberitahuan apl tersuai"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Benarkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baharu dengan <xliff:g id="ACCOUNT">%2$s</xliff:g> (Pengguna dengan akaun ini sudah wujud) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Benarkan <xliff:g id="APP">%1$s</xliff:g> membuat Pengguna baharu dengan <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Tambahkan bahasa"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> telah diletakkan dalam baldi TERHAD"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Peribadi"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Kerja"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Tidak dapat berkongsi dengan apl kerja"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Tidak dapat berkongsi dengan apl peribadi"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Pentadbir IT anda menyekat perkongsian antara apl peribadi dan kerja"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Hidupkan apl kerja"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Hidupkan apl kerja untuk mengakses apl & kenalan kerja"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Tiada rangkaian yang tersedia"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Kami tidak menemukan sebarang apl"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Hidupkan kerja"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Rakam atau mainkan audio dalam panggilan telefoni"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Apabila ditetapkan sebagai apl pendail lalai, membenarkan apl ini merakam atau memainkan audio dalam panggilan telefoni."</string>
</resources>
diff --git a/core/res/res/values-my/strings.xml b/core/res/res/values-my/strings.xml
index 9a902c8..05dadf0 100644
--- a/core/res/res/values-my/strings.xml
+++ b/core/res/res/values-my/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other"><xliff:g id="NUMBER_1">%d</xliff:g> စက္ကန့်အတွင်း ချွတ်ယွင်းချက် အစီရင်ခံရန်အတွက် မျက်နှာပြင်ဓာတ်ပုံ ရိုက်ပါမည်။</item>
<item quantity="one"><xliff:g id="NUMBER_0">%d</xliff:g> စက္ကန့်အတွင်း ချွတ်ယွင်းချက် အစီရင်ခံရန်အတွက် မျက်နှာပြင်ဓာတ်ပုံ ရိုက်ပါမည်။</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ချွတ်ယွင်းချက်အစီရင်ခံချက်နှင့်အတူ ဖန်သားပြင်ဓာတ်ပုံရိုက်ထားသည်"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ချွတ်ယွင်းချက်အစီရင်ခံချက်နှင့်အတူ ဖန်သားပြင်ဓာတ်ပုံရိုက်၍မရခဲ့ပါ"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"အသံတိတ်စနစ်"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"အသံပိတ်ထားသည်"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"အသံဖွင့်ထားသည်"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"အခြားအက်ပ်တွင် စတင်ထားသည့် ဖုန်းခေါ်ဆိုမှုကို ဆက်လက်ပြုလုပ်ရန် ဤအက်ပ်ကို ခွင့်ပြုသည်။"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ဖုန်းနံပါတ်များကို ဖတ်ရန်"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"အက်ပ်ကို စက်ပစ္စည်း၏ ဖုန်းနံပါတ်များအား အသုံးပြုခွင့်ပေးပါ။"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ကားဖန်သားပြင်ကို ဖွင့်ထားပါ"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"တက်ပလက်အား ပိတ်ခြင်းမှ ကာကွယ်ခြင်း"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"သင်၏ Android TV စက်ပစ္စည်း နားခြင်းမရှိစေရန် ပြုလုပ်ခြင်း"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ဖုန်းအနားယူခြင်းမပြုလုပ်စေရန်"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ကားဖန်သားပြင် ဖွင့်ထားနိုင်စေရန် အက်ပ်ကို ခွင့်ပြုပေးပါ။"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"အက်ပ်အား တက်ဘလက်ကို အနားမယူနိုင်အောင် ဟန့်တားခွင့် ပြုသည်။"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"သင့် Android TV စက်ပစ္စည်း နားခြင်း မရှိစေရန်အတွက် အက်ပ်အား လုပ်ဆောင်ခွင့်ပြုသည်။"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"အက်ပ်အား ဖုန်းကို အနားမယူနိုင်အောင် ဟန့်တားခွင့် ပြုသည်။"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"အသံကို အကြံပြုထားသည့် ပမာဏထက် မြှင့်ပေးရမလား?\n\nအသံကို မြင့်သည့် အဆင့်မှာ ကြာရှည်စွာ နားထောင်ခြင်းက သင်၏ နားကို ထိခိုက်စေနိုင်သည်။"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"အများသုံးစွဲနိုင်မှု ဖြတ်လမ်းလင့်ခ်ကို အသုံးပြုလိုပါသလား။"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ဖြတ်လမ်းလင့်ခ်ကို ဖွင့်ထားစဉ် အသံထိန်းခလုတ် နှစ်ခုစလုံးကို ၃ စက္ကန့်ခန့် ဖိထားခြင်းဖြင့် အများသုံးစွဲနိုင်မှုဆိုင်ရာ ဝန်ဆောင်မှုကို ဖွင့်နိုင်သည်။"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ဖြတ်လမ်းများကို တည်းဖြတ်ရန်"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"မလုပ်တော့"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ဖြတ်လမ်းလင့်ခ်ကို ပိတ်ရန်"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"အမျိုးအစားမခွဲရသေးပါ"</string>
<string name="importance_from_user" msgid="2782756722448800447">"ဤသတိပေးချက်များ၏ အရေးပါမှုကိုသတ်မှတ်ပြီးပါပြီ။"</string>
<string name="importance_from_person" msgid="4235804979664465383">"ပါဝင်သည့်လူများကြောင့် အရေးပါပါသည်။"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"စိတ်ကြိုက်အက်ပ် အကြောင်းကြားချက်"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ဖြင့်အသုံးပြုသူအသစ်ကို <xliff:g id="APP">%1$s</xliff:g> အား ဖန်တီးခွင့်ပြုလိုပါသလား (ဤအကောင့်ဖြင့် အသုံးပြုသူ ရှိနှင့်ပြီးဖြစ်သည်) ။"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="ACCOUNT">%2$s</xliff:g> ဖြင့်အသုံးပြုသူအသစ်ကို <xliff:g id="APP">%1$s</xliff:g> အား ဖန်တီးခွင့်ပြုလိုပါသလား ။"</string>
<string name="language_selection_title" msgid="52674936078683285">"ဘာသာစကားတစ်ခု ထည့်ပါ"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ကို တားမြစ်ထားသော သိမ်းဆည်းမှုအတွင်းသို့ ထည့်ပြီးပါပြီ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ကိုယ်ပိုင်"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"အလုပ်"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"အလုပ်သုံးအက်ပ်များနှင့် မျှဝေ၍ မရပါ"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ကိုယ်ပိုင်သုံးအက်ပ်များနှင့် မျှဝေ၍ မရပါ"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"သင့်အိုင်တီ စီမံခန့်ခွဲသူက ကိုယ်ပိုင်သုံးနှင့် အလုပ်သုံးအက်ပ်များအကြား မျှဝေခြင်းကို ပိတ်ထားသည်"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"အလုပ်သုံးအက်ပ်များကို ဖွင့်ပါ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"အလုပ်သုံးအက်ပ်နှင့် အဆက်အသွယ်များကို သုံးရန် အလုပ်သုံးအက်ပ်များကို ဖွင့်ပါ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"မည်သည့်အက်ပ်မျှ မရှိပါ"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"မည်သည့်အက်ပ်ကိုမျှ မတွေ့ပါ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"အလုပ်သုံးအနေအထားကို ဖွင့်ပါ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ဖုန်းခေါ်ဆိုမှုများအတွင်း အသံဖမ်းခြင်း သို့မဟုတ် ဖွင့်ခြင်း"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ဤအက်ပ်အား မူလ dialer အပလီကေးရှင်းအဖြစ် သတ်မှတ်ထားစဉ် ဖုန်းခေါ်ဆိုမှုများအတွင်း အသံဖမ်းခြင်း သို့မဟုတ် ဖွင့်ခြင်း ပြုလုပ်ရန် ခွင့်ပြုပါ။"</string>
</resources>
diff --git a/core/res/res/values-nb/strings.xml b/core/res/res/values-nb/strings.xml
index 93afcb2..8848a3e 100644
--- a/core/res/res/values-nb/strings.xml
+++ b/core/res/res/values-nb/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Tar skjermdump for feilrapporten om <xliff:g id="NUMBER_1">%d</xliff:g> sekunder.</item>
<item quantity="one">Tar skjermdump for feilrapporten om <xliff:g id="NUMBER_0">%d</xliff:g> sekund.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"En skjermdump er tatt med feilrapporten"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Kunne ikke ta skjermdump med feilrapporten"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Stillemodus"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Lyden er av"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Lyden er på"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Lar appen fortsette et anrop som ble startet i en annen app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"les telefonnumre"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Gir appen tilgang til telefonnumrene til enheten."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"hold bilskjermen på"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"hindre nettbrettet fra å gå over til sovemodus"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"forhindre at Android TV-enheten din settes i hvilemodus"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"forhindre telefonen fra å sove"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Tillater at appen holder bilskjermen på."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Lar appen hindre nettbrettet fra å gå over i sovemodus."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Lar appen hindre Android TV-enheten fra å settes i hvilemodus."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Lar appen hindre telefonen fra å gå over i sovemodus."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Vil du øke volumet til over anbefalt nivå?\n\nHvis du hører på et høyt volum over lengre perioder, kan det skade hørselen din."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Vil du bruke tilgjengelighetssnarveien?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Når snarveien er på, starter en tilgjengelighetsfunksjon når du trykker inn begge volumknappene i tre sekunder."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Endre snarveier"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Avbryt"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Slå av snarveien"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Uten kategori"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Du angir viktigheten for disse varslene."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Dette er viktig på grunn av folkene som er involvert."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Tilpasset appvarsel"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Vil du la <xliff:g id="APP">%1$s</xliff:g> opprette en ny bruker med <xliff:g id="ACCOUNT">%2$s</xliff:g> (en bruker med denne kontoen eksisterer allerede)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Vil du la <xliff:g id="APP">%1$s</xliff:g> opprette en ny bruker med <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Legg til et språk"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> er blitt plassert i TILGANGSBEGRENSET-toppmappen"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personlig"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Jobb"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Kan ikke dele med jobbapper"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Kan ikke dele med personlige apper"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT-administratoren din har blokkert deling mellom personlige apper og jobbapper"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Slå på jobbapper"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Slå på jobbapper for å få tilgang til jobbapper og kontakter"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Ingen apper er tilgjengelige"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Vi fant ingen apper"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Slå på jobbprofilen"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Ta opp eller spill av lyd i telefonsamtaler"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Tillater at denne appen tar opp eller spiller av lyd i telefonsamtaler når den er angitt som standard ringeapp."</string>
</resources>
diff --git a/core/res/res/values-ne/strings.xml b/core/res/res/values-ne/strings.xml
index d47a8ed..a6d0dbd 100644
--- a/core/res/res/values-ne/strings.xml
+++ b/core/res/res/values-ne/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other"> बग रिपोर्टको लागि <xliff:g id="NUMBER_1">%d</xliff:g> सेकेन्डमा स्क्रिसट लिँदै।</item>
<item quantity="one"> बग रिपोर्टको लागि <xliff:g id="NUMBER_0">%d</xliff:g> सेकेन्डमा स्क्रिसट लिँदै।</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"बग रिपोर्टको स्क्रिनसट खिचियो"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"बग रिपोर्टको स्क्रिनसट खिच्न सकिएन"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"मौन मोड"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"आवाज बन्द छ"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ध्वनि खुल्ला छ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"यस अनुप्रयोगलाई अर्को अनुप्रयोगमा सुरु गरिएको कल जारी राख्ने अनुमति दिन्छ।"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"फोन नम्बरहरू पढ्ने"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"उक्त अनुप्रयोगलाई यस यन्त्रको फोन नम्बरहरूमाथि पहुँच राख्न दिनुहोस्।"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"कारको स्क्रिन सक्रिय राख्नुहोस्"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ट्याब्लेटलाई निन्द्रामा जानबाट रोक्नुहोस्"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"आफ्नो Android TV यन्त्रलाई शयन अवस्थामा जान नदिनुहोस्"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"फोनलाई निदाउनबाट रोक्नुहोस्"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"यो अनुमतिले यस अनुप्रयोगलाई कारको स्क्रिन सक्रिय राख्न दिन्छ।"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ट्याब्लेटलाई निस्क्रिय हुनबाट रोक्नको लागि अनुप्रयोगलाई अनुमति दिन्छ।"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"अनुप्रयोगलाई तपाईंको Android TV यन्त्रलाई शयन अवस्थामा जानबाट रोक्ने अनुमति दिन्छ।"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"फोनलाई निस्क्रिय हुनबाट रोक्नको लागि अनुप्रयोगलाई अनुमति दिन्छ।"</string>
@@ -1637,6 +1637,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"सिफारिस तहभन्दा आवाज ठुलो गर्नुहुन्छ?\n\nलामो समय सम्म उच्च आवाजमा सुन्दा तपाईँको सुन्ने शक्तिलाई हानी गर्न सक्छ।"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"पहुँच सम्बन्धी सर्टकट प्रयोग गर्ने हो?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"यो सर्टकट सक्रिय हुँदा, ३ सेकेन्डसम्म दुवै भोल्युम बटन थिच्नुले पहुँचसम्बन्धी कुनै सुविधा सुरु गर्ने छ।"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"सर्टकटहरू सम्पादन गर्नुहोस्"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"रद्द गर्नुहोस्"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"सर्टकटलाई निष्क्रिय पार्नुहोस्"</string>
@@ -2034,14 +2040,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> लाई प्रतिबन्धित बाल्टीमा राखियो"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"व्यक्तिगत"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"काम"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"कामसम्बन्धी अनुप्रयोगहरूसँग आदान प्रदान गर्न सकिँदैन"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"व्यक्तिगत अनुप्रयोगहरूसँग आदान प्रदान गर्न सकिँदैन"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"तपाईंका IT प्रशासकले व्यक्तिगत र कामसम्बन्धी अनुप्रयोगहरूबिच आदान प्रदान गर्ने सुविधामाथि रोक लगाउनुभयो"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"कामसम्बन्धी अनुप्रयोगहरू सक्रिय गर्नुहोस्"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"कामसम्बन्धी अनुप्रयोग र सम्पर्क ठेगानाहरूमाथि पहुँच राख्न कामसम्बन्धी अनुप्रयोगहरू सक्रिय गर्नुहोस्"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"कुनै पनि अनुप्रयोग उपलब्ध छैन"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"हामीले कुनै पनि अनुप्रयोग फेला पार्न सकेनौँ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"कार्य प्रोफाइल सक्षम पार्नुहोस्"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"टेलिफोन कल गर्दै गर्दा अडियो रेकर्ड गर्नुहोस् वा प्ले गर्नुहोस्"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"यस अनुप्रयोगलाई पूर्वनिर्धारित डायलर अनुप्रयोग निर्धारण गर्दा टेलिफोन कलको अडियो रेकर्ड गर्ने र प्ले गर्ने अनुमति दिन्छ।"</string>
</resources>
diff --git a/core/res/res/values-nl/strings.xml b/core/res/res/values-nl/strings.xml
index df2f963..c4c9bbe 100644
--- a/core/res/res/values-nl/strings.xml
+++ b/core/res/res/values-nl/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Er wordt over <xliff:g id="NUMBER_1">%d</xliff:g> seconden een screenshot gemaakt voor het bugrapport.</item>
<item quantity="one">Er wordt over <xliff:g id="NUMBER_0">%d</xliff:g> seconde een screenshot gemaakt voor het bugrapport.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Screenshot gemaakt voor bugrapport"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Kan geen screenshot maken voor bugrapport"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Stille modus"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Geluid is UIT"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Geluid is AAN"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Hiermee kan de app een gesprek voortzetten dat is gestart in een andere app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"telefoonnummers lezen"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Hiermee kan de app toegang krijgen tot de telefoonnummers van het apparaat."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"autoscherm ingeschakeld houden"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"voorkomen dat tablet overschakelt naar slaapmodus"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"voorkomen dat je Android TV overschakelt naar slaapstand"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"voorkomen dat telefoon overschakelt naar slaapmodus"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Hiermee kan de app het autoscherm ingeschakeld houden."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Hiermee kan de app voorkomen dat de tablet overschakelt naar de slaapmodus."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Hiermee kan de app voorkomen dat het Android TV-apparaat overschakelt naar de slaapstand."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Hiermee kan de app voorkomen dat de telefoon overschakelt naar de slaapmodus."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Volume verhogen tot boven het aanbevolen niveau?\n\nAls je langere tijd op hoog volume naar muziek luistert, raakt je gehoor mogelijk beschadigd."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Snelkoppeling toegankelijkheid gebruiken?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Als de snelkoppeling is ingeschakeld, kun je drie seconden op beide volumeknoppen drukken om een toegankelijkheidsfunctie te starten."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Snelkoppelingen bewerken"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Annuleren"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Sneltoets uitschakelen"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Geen categorie"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Je stelt het belang van deze meldingen in."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Dit is belangrijk vanwege de betrokken mensen."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Aangepaste app-melding"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Toestaan dat <xliff:g id="APP">%1$s</xliff:g> een nieuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> maakt (er is al een gebruiker met dit account)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Toestaan dat <xliff:g id="APP">%1$s</xliff:g> een nieuwe gebruiker met <xliff:g id="ACCOUNT">%2$s</xliff:g> maakt?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Een taal toevoegen"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> is in de bucket RESTRICTED geplaatst"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Persoonlijk"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Werk"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Kan niet delen met werk-apps"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Kan niet delen met persoonlijke apps"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Je IT-beheerder heeft delen tussen persoonlijke en werk-apps geblokkeerd"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Schakel werk-apps in"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Schakel werk-apps in om toegang tot werk-apps en -contacten te krijgen"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Geen apps beschikbaar"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"We kunnen geen apps vinden"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Werkprofiel inschakelen"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Audio opnemen of afspelen in telefoongesprekken"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Hiermee mag deze app (indien toegewezen als standaard dialer-app) audio opnemen of afspelen in telefoongesprekken."</string>
</resources>
diff --git a/core/res/res/values-or/strings.xml b/core/res/res/values-or/strings.xml
index cc5aa28..1ea50ee 100644
--- a/core/res/res/values-or/strings.xml
+++ b/core/res/res/values-or/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other"><xliff:g id="NUMBER_1">%d</xliff:g> ସେକେଣ୍ଡରେ ବଗ୍ ରିପୋର୍ଟ ପାଇଁ ସ୍କ୍ରୀନଶଟ୍ ନେଉଛି।</item>
<item quantity="one"><xliff:g id="NUMBER_0">%d</xliff:g> ସେକେଣ୍ଡରେ ବଗ୍ ରିପୋର୍ଟ ପାଇଁ ସ୍କ୍ରୀନଶଟ୍ ନେଉଛି।</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ବଗ୍ ରିପୋର୍ଟ ସହ ସ୍କ୍ରିନସଟ୍ ନିଆଯାଇଛି"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ବଗ୍ ରିପୋର୍ଟ ସହ ସ୍କ୍ରିନସଟ୍ ନେବାରେ ବିଫଳ ହୋଇଛି"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"ସାଇଲେଣ୍ଟ ମୋଡ୍"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ସାଉଣ୍ଡ ଅଫ୍ ଅଛି"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ସାଉଣ୍ଡ ଅନ୍ ଅଛି"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"ଅନ୍ୟ ଆପ୍ରେ ଆରମ୍ଭ ହୋଇଥିବା ଗୋଟିଏ କଲ୍କୁ ଜାରି ରଖିବା ପାଇଁ ଆପ୍କୁ ଅନୁମତି ଦିଅନ୍ତୁ।"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ଫୋନ୍ ନମ୍ବର ପଢ଼େ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ଏହି ଡିଭାଇସର ଫୋନ୍ ନମ୍ବର ଆକ୍ସେସ୍ କରିବାକୁ ଆପକୁ ଅନୁମତି ଦିଏ।"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"କାର ସ୍କ୍ରିନକୁ ଚାଲୁ ରଖନ୍ତୁ"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ଟାବଲେଟ୍କୁ ସ୍ଲୀପିଙ୍ଗ ମୋଡ୍କୁ ଯିବାକୁ ରୋକନ୍ତୁ"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ସ୍ଲିପିଂରୁ ଆପଣଙ୍କର Android ଟିଭି ଡିଭାଇସ୍କୁ ପ୍ରତିରୋଧ କରନ୍ତୁ"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ଫୋନକୁ ସ୍ଲୀପିଙ୍ଗ ମୋଡ୍କୁ ଯିବାକୁ ରୋକନ୍ତୁ"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"କାର ସ୍କ୍ରିନକୁ ଚାଲୁ ରଖିବା ପାଇଁ ଆପକୁ ଅନୁମତି ଦେଇଥାଏ।"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ଆପ୍କୁ, ଟାବଲେଟ୍ଟିକୁ ସ୍ଲୀପ୍ ମୋଡ୍କୁ ଯିବାରେ ପ୍ରତିରୋଧ କରିବାକୁ ଦେଇଥାଏ।"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ଏହି ଆପ୍ ଆପଣଙ୍କର Android ଟିଭି ଡିଭାଇସ୍କୁ ସ୍ଲିପ୍ ମୋଡ୍କୁ ଯିବାରେ ପ୍ରତିରୋଧ କରିବା ପାଇଁ ଅନୁମତି ଦେଇଥାଏ।"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ଆପ୍କୁ, ଫୋନ୍ଟିକୁ ସ୍ଲୀପ୍ ମୋଡ୍କୁ ଯିବାରେ ପ୍ରତିରୋଧ କରିବାକୁ ଦେଇଥାଏ।"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"ମାତ୍ରା ବଢ଼ାଇ ସୁପାରିଶ ସ୍ତର ବଢ଼ାଉଛନ୍ତି? \n\n ଲମ୍ବା ସମୟ ପର୍ଯ୍ୟନ୍ତ ଉଚ୍ଚ ଶବ୍ଦରେ ଶୁଣିଲେ ଆପଣଙ୍କ ଶ୍ରବଣ ଶକ୍ତି ଖରାପ ହୋଇପାରେ।"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ଆକ୍ସେସବିଲିଟି ଶର୍ଟକଟ୍ ବ୍ୟବହାର କରିବେ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ସର୍ଟକଟ୍ ଚାଲୁ ଥିବା ବେଳେ, ଉଭୟ ଭଲ୍ୟୁମ୍ ବଟନ୍ 3 ସେକେଣ୍ଡ ପାଇଁ ଦବାଇବା ଦ୍ୱାରା ଏକ ଆକ୍ସେସବିଲିଟି ଫିଚର୍ ଆରମ୍ଭ ହେବ।"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ସର୍ଟକଟଗୁଡ଼ିକୁ ସମ୍ପାଦନ କରନ୍ତୁ"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ବାତିଲ୍ କରନ୍ତୁ"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ଶର୍ଟକଟ୍ ବନ୍ଦ କରନ୍ତୁ"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>କୁ ପ୍ରତିବନ୍ଧିତ ବକେଟରେ ରଖାଯାଇଛି"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ବ୍ୟକ୍ତିଗତ"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"କାର୍ଯ୍ୟ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"କାର୍ଯ୍ୟସ୍ଥଳୀ ଆପଗୁଡ଼ିକ ସହ ସେୟାର୍ କରିପାରିବ ନାହିଁ"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ବ୍ୟକ୍ତିଗତ ଆପଗୁଡ଼ିକ ସହ ସେୟାର୍ କରିପାରିବ ନାହିଁ"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ଆପଣଙ୍କର IT ଆଡମିନ୍ ବ୍ୟକ୍ତିଗତ ଏବଂ କାର୍ଯ୍ୟସ୍ଥଳୀ ଆପଗୁଡ଼ିକ ମଧ୍ୟରେ ସେୟାରିଂ ବ୍ଲକ୍ କରିଛନ୍ତି"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"କାର୍ଯ୍ୟସ୍ଥଳୀ ଆପଗୁଡ଼ିକୁ ଚାଲୁ କରନ୍ତୁ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"କାର୍ଯ୍ୟସ୍ଥଳୀ ଆପ୍ ଏବଂ ଯୋଗାଯୋଗଗୁଡ଼ିକୁ ଆକ୍ସେସ୍ କରିବା ପାଇଁ କାର୍ଯ୍ୟସ୍ଥଳୀ ଆପଗୁଡ଼ିକୁ ଚାଲୁ କରନ୍ତୁ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"କୌଣସି ଆପ୍ ଉପଲବ୍ଧ ନାହିଁ"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ଆମେ କୌଣସି ଆପ୍ ପାଇଲୁ ନାହିଁ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"କାର୍ଯ୍ୟସ୍ଥଳୀ ପ୍ରୋଫାଇଲରେ ସ୍ୱିଚ୍ କରନ୍ତୁ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ଟେଲିଫୋନି କଲଗୁଡ଼ିକରେ ଅଡିଓ ରେକର୍ଡ କରନ୍ତୁ ବା ଚଲାନ୍ତୁ"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ଏହି ଆପ୍ ଡିଫଲ୍ଟ ଡାଏଲର୍ ଆପ୍ଲିକେସନ୍ ଭାବରେ ଆସାଇନ୍ ହୋଇଥିଲେ ଟେଲିଫୋନି କଲଗୁଡ଼ିକରେ ଅଡିଓ ରେକର୍ଡ କରିବା ବା ଚଲାଇବା ପାଇଁ ଅନୁମତି ଦିଅନ୍ତୁ।"</string>
</resources>
diff --git a/core/res/res/values-pa/strings.xml b/core/res/res/values-pa/strings.xml
index 6c8b5c3..8e5ae7d 100644
--- a/core/res/res/values-pa/strings.xml
+++ b/core/res/res/values-pa/strings.xml
@@ -193,14 +193,10 @@
<string name="network_logging_notification_text" msgid="1327373071132562512">"ਤੁਹਾਡਾ ਸੰਗਠਨ ਇਸ ਡੀਵਾਈਸ ਦਾ ਪ੍ਰਬੰਧਨ ਕਰਦਾ ਹੈ ਅਤੇ ਨੈੱਟਵਰਕ ਟਰੈਫਿਕ ਦੀ ਨਿਗਰਾਨੀ ਕਰ ਸਕਦਾ ਹੈ। ਵੇਰਵਿਆਂ ਲਈ ਟੈਪ ਕਰੋ।"</string>
<string name="location_changed_notification_title" msgid="4119726617105166830">"ਤੁਹਾਡੇ ਪ੍ਰਸ਼ਾਸਕ ਨੇ ਟਿਕਾਣਾ ਸੈਟਿੰਗਾਂ ਨੂੰ ਬਦਲ ਦਿੱਤਾ ਹੈ"</string>
<string name="location_changed_notification_text" msgid="198907268219396399">"ਆਪਣੀਆਂ ਟਿਕਾਣਾ ਸੈਟਿੰਗਾਂ ਨੂੰ ਦੇਖਣ ਲਈ ਟੈਪ ਕਰੋ।"</string>
- <!-- no translation found for country_detector (7023275114706088854) -->
- <skip />
- <!-- no translation found for location_service (2439187616018455546) -->
- <skip />
- <!-- no translation found for sensor_notification_service (7474531979178682676) -->
- <skip />
- <!-- no translation found for twilight_service (8964898045693187224) -->
- <skip />
+ <string name="country_detector" msgid="7023275114706088854">"ਦੇਸ਼ ਦਾ ਪਤਾ ਲਗਾਉਣ ਦੀ ਸੁਵਿਧਾ"</string>
+ <string name="location_service" msgid="2439187616018455546">"ਟਿਕਾਣਾ ਸੇਵਾ"</string>
+ <string name="sensor_notification_service" msgid="7474531979178682676">"ਸੈਂਸਰ ਸੂਚਨਾ ਸੇਵਾ"</string>
+ <string name="twilight_service" msgid="8964898045693187224">"ਟਵੀਲਾਈਟ ਸੇਵਾ"</string>
<string name="factory_reset_warning" msgid="6858705527798047809">"ਤੁਹਾਡਾ ਡੀਵਾਈਸ ਮਿਟਾਇਆ ਜਾਏਗਾ"</string>
<string name="factory_reset_message" msgid="2657049595153992213">"ਪ੍ਰਸ਼ਾਸਕ ਐਪ ਵਰਤੀ ਨਹੀਂ ਜਾ ਸਕਦੀ। ਹੁਣ ਤੁਹਾਡੇ ਡੀਵਾਈਸ ਦਾ ਡਾਟਾ ਮਿਟਾਇਆ ਜਾਵੇਗਾ।\n\nਜੇਕਰ ਤੁਹਾਡੇ ਕੋਲ ਕੋਈ ਸਵਾਲ ਹਨ, ਤਾਂ ਆਪਣੀ ਸੰਸਥਾ ਦੇ ਪ੍ਰਸ਼ਾਸਕ ਨੂੰ ਸੰਪਰਕ ਕਰੋ।"</string>
<string name="printing_disabled_by" msgid="3517499806528864633">"<xliff:g id="OWNER_APP">%s</xliff:g> ਵੱਲੋਂ ਪ੍ਰਿੰਟ ਕਰਨਾ ਬੰਦ ਕੀਤਾ ਗਿਆ।"</string>
@@ -253,10 +249,8 @@
<item quantity="one">ਬੱਗ ਰਿਪੋਰਟ ਲਈ <xliff:g id="NUMBER_1">%d</xliff:g> ਸਕਿੰਟਾਂ ਵਿੱਚ ਸਕ੍ਰੀਨਸ਼ਾਟ ਲਿਆ ਜਾ ਰਿਹਾ ਹੈ।</item>
<item quantity="other">ਬੱਗ ਰਿਪੋਰਟ ਲਈ <xliff:g id="NUMBER_1">%d</xliff:g> ਸਕਿੰਟਾਂ ਵਿੱਚ ਸਕ੍ਰੀਨਸ਼ਾਟ ਲਿਆ ਜਾ ਰਿਹਾ ਹੈ।</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ਬੱਗ ਰਿਪੋਰਟ ਦਾ ਸਕ੍ਰੀਨਸ਼ਾਟ ਲਿਆ ਗਿਆ"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ਬੱਗ ਰਿਪੋਰਟ ਦਾ ਸਕ੍ਰੀਨਸ਼ਾਟ ਲੈਣਾ ਅਸਫਲ ਰਿਹਾ"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"ਸਾਈਲੈਂਟ ਮੋਡ"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ਅਵਾਜ਼ ਬੰਦ ਹੈ"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ਅਵਾਜ਼ ਚਾਲੂ ਹੈ"</string>
@@ -458,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"ਐਪ ਨੂੰ ਉਹ ਕਾਲ ਜਾਰੀ ਰੱਖਣ ਦਿਓ ਜਿਸਨੂੰ ਹੋਰ ਐਪ ਤੋਂ ਚਾਲੂ ਕੀਤਾ ਗਿਆ ਸੀ।"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ਫ਼ੋਨ ਨੰਬਰ ਪੜ੍ਹੋ"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ਐਪ ਨੂੰ ਡੀਵਾਈਸ ਦੇ ਫ਼ੋਨ ਨੰਬਰਾਂ \'ਤੇ ਪਹੁੰਚ ਕਰਨ ਦੀ ਇਜਾਜ਼ਤ ਦਿੰਦੀ ਹੈ।"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"ਕਾਰ ਦੀ ਸਕ੍ਰੀਨ ਚਾਲੂ ਰੱਖੋ"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ਟੈਬਲੈੱਟ ਨੂੰ ਸਲੀਪ ਤੇ ਜਾਣ ਤੋਂ ਰੋਕੋ"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ਆਪਣੇ Android TV ਡੀਵਾਈਸ ਨੂੰ ਸਲੀਪ ਮੋਡ ਵਿੱਚ ਜਾਣ ਤੋਂ ਰੋਕੋੇ"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ਫ਼ੋਨ ਨੂੰ ਸਲੀਪਿੰਗ ਤੋਂ ਰੋਕੋ"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ਐਪ ਨੂੰ ਕਾਰ ਦੀ ਸਕ੍ਰੀਨ ਹਰ ਵੇਲੇ ਚਾਲੂ ਰੱਖਣ ਦਿੰਦਾ ਹੈ।"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ਐਪ ਨੂੰ ਟੈਬਲੈੱਟ ਨੂੰ ਸਲੀਪ ਤੇ ਜਾਣ ਤੋਂ ਰੋਕਣ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ।"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ਐਪ ਨੂੰ ਤੁਹਾਡੇ Android TV ਡੀਵਾਈਸ ਨੂੰ ਸਲੀਪ ਮੋਡ \'ਤੇ ਜਾਣ ਤੋਂ ਰੋਕਣ ਦਿੰਦੀ ਹੈ।"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ਐਪ ਨੂੰ ਫ਼ੋਨ ਨੂੰ ਸਲੀਪ ਤੇ ਜਾਣ ਤੋਂ ਰੋਕਣ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ।"</string>
@@ -1635,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"ਕੀ ਵੌਲਿਊਮ ਸਿਫ਼ਾਰਸ਼ ਕੀਤੇ ਪੱਧਰ ਤੋਂ ਵਧਾਉਣੀ ਹੈ?\n\nਲੰਮੇ ਸਮੇਂ ਤੱਕ ਉੱਚ ਵੌਲਿਊਮ ਤੇ ਸੁਣਨ ਨਾਲ ਤੁਹਾਡੀ ਸੁਣਨ ਸ਼ਕਤੀ ਨੂੰ ਨੁਕਸਾਨ ਪਹੁੰਚ ਸਕਦਾ ਹੈ।"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ਕੀ ਪਹੁੰਚਯੋਗਤਾ ਸ਼ਾਰਟਕੱਟ ਵਰਤਣਾ ਹੈ?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ਸ਼ਾਰਟਕੱਟ ਚਾਲੂ ਹੋਣ \'ਤੇ, ਕਿਸੇ ਪਹੁੰਚਯੋਗਤਾ ਵਿਸ਼ੇਸ਼ਤਾ ਨੂੰ ਸ਼ੁਰੂ ਕਰਨ ਲਈ ਦੋਵੇਂ ਅਵਾਜ਼ ਬਟਨਾਂ ਨੂੰ 3 ਸਕਿੰਟ ਲਈ ਦਬਾ ਕੇ ਰੱਖੋ।"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ਸ਼ਾਰਟਕੱਟਾਂ ਦਾ ਸੰਪਾਦਨ ਕਰੋ"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ਰੱਦ ਕਰੋ"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ਸ਼ਾਰਟਕੱਟ ਬੰਦ ਕਰੋ"</string>
@@ -2032,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ਨੂੰ ਪ੍ਰਤਿਬੰਧਿਤ ਖਾਨੇ ਵਿੱਚ ਪਾਇਆ ਗਿਆ ਹੈ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ਨਿੱਜੀ"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"ਕੰਮ"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ਕੰਮ ਸੰਬੰਧੀ ਐਪਾਂ ਨਾਲ ਸਾਂਝਾ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ਨਿੱਜੀ ਐਪਾਂ ਨਾਲ ਸਾਂਝਾ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ਤੁਹਾਡੇ ਆਈ.ਟੀ. ਪ੍ਰਸ਼ਾਸਕ ਨੇ ਨਿੱਜੀ ਅਤੇ ਕੰਮ ਸੰਬੰਧੀ ਐਪਾਂ ਵਿਚਕਾਰ ਸਾਂਝਾਕਰਨ ਨੂੰ ਬਲਾਕ ਕੀਤਾ ਹੈ"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ਕੰਮ ਸੰਬੰਧੀ ਐਪਾਂ ਚਾਲੂ ਕਰੋ"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ਕੰਮ ਸੰਬੰਧੀ ਐਪਾਂ ਅਤੇ ਸੰਪਰਕਾਂ ਤੱਕ ਪਹੁੰਚ ਕਰਨ ਲਈ ਕੰਮ ਸੰਬੰਧੀ ਐਪਾਂ ਨੂੰ ਚਾਲੂ ਕਰੋ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ਕੋਈ ਐਪ ਉਪਲਬਧ ਨਹੀਂ"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ਅਸੀਂ ਕੋਈ ਐਪ ਨਹੀਂ ਲੱਭ ਸਕੇ"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ਕਾਰਜ ਪ੍ਰੋਫਾਈਲ \'ਤੇ ਜਾਓ"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ਟੈਲੀਫ਼ੋਨੀ ਕਾਲਾਂ ਵਿੱਚ ਰਿਕਾਰਡ ਕਰੋ ਜਾਂ ਆਡੀਓ ਚਲਾਓ"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"ਇਹ ਇਸ ਐਪ ਨੂੰ, ਪੂਰਵ-ਨਿਰਧਾਰਤ ਡਾਇਲਰ ਐਪਲੀਕੇਸ਼ਨ ਵਜੋਂ ਜਿੰਮੇ ਲਾਏ ਜਾਣ \'ਤੇ, ਟੈਲੀਫ਼ੋਨੀ ਕਾਲਾਂ ਵਿੱਚ ਰਿਕਾਰਡ ਕਰਨ ਜਾਂ ਆਡੀਓ ਚਲਾਉਣ ਦਿੰਦਾ ਹੈ।"</string>
</resources>
diff --git a/core/res/res/values-pl/strings.xml b/core/res/res/values-pl/strings.xml
index c4246fa..91c8c70 100644
--- a/core/res/res/values-pl/strings.xml
+++ b/core/res/res/values-pl/strings.xml
@@ -255,10 +255,8 @@
<item quantity="other">Zrzut ekranu do raportu o błędzie zostanie zrobiony za <xliff:g id="NUMBER_1">%d</xliff:g> sekundy.</item>
<item quantity="one">Zrzut ekranu do raportu o błędzie zostanie zrobiony za <xliff:g id="NUMBER_0">%d</xliff:g> sekundę.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Zrobiono zrzut ekranu z raportem o błędzie"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Nie udało się zrobić zrzutu ekranu z raportem o błędzie"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Tryb cichy"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Dźwięk jest wyłączony"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Dźwięk jest włączony"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Zezwala na kontynuowanie przez aplikację połączenia rozpoczętego w innej aplikacji."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"odczytywanie numerów telefonów"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Zezwala aplikacji na dostęp do numerów telefonów na urządzeniu."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"utrzymuj włączony ekran samochodu"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"zapobieganie przechodzeniu tabletu do trybu uśpienia"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"zapobieganie uśpieniu urządzenia z Androidem TV"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"zapobieganie przejściu telefonu w stan uśpienia"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Zezwala aplikacji na utrzymywanie włączonego ekranu samochodu"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Pozwala aplikacji na zapobieganie przechodzeniu tabletu do trybu uśpienia."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Pozwala aplikacji zapobiegać przechodzeniu urządzenia z Androidem TV w tryb uśpienia."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Pozwala aplikacji na zapobieganie przechodzeniu telefonu w tryb uśpienia."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Zwiększyć głośność ponad zalecany poziom?\n\nSłuchanie głośno przez długi czas może uszkodzić Twój słuch."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Użyć skrótu do ułatwień dostępu?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Gdy skrót jest włączony, jednoczesne naciskanie przez trzy sekundy obu przycisków głośności uruchamia funkcję ułatwień dostępu."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Edytuj skróty"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Anuluj"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Wyłącz skrót"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Bez kategorii"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ustawiłeś ważność tych powiadomień."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ta wiadomość jest ważna ze względu na osoby uczestniczące w wątku."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Niestandardowe powiadomienie z aplikacji"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Zezwolić aplikacji <xliff:g id="APP">%1$s</xliff:g> na utworzenie nowego użytkownika dla konta <xliff:g id="ACCOUNT">%2$s</xliff:g> (użytkownik dla tego konta już istnieje)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Zezwolić aplikacji <xliff:g id="APP">%1$s</xliff:g> na utworzenie nowego użytkownika dla konta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dodaj język"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Umieszczono pakiet <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> w zasobniku danych RESTRICTED"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Osobiste"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Do pracy"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nie można udostępnić aplikacji do pracy"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nie można udostępnić aplikacji osobistej"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Administrator IT zablokował udostępnianie między aplikacjami osobistymi i aplikacjami do pracy"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Włącz aplikacje do pracy"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Włącz aplikacje do pracy, aby uzyskać dostęp do kontaktów i aplikacji do pracy"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Brak dostępnych aplikacji"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nie znaleźliśmy żadnych aplikacji"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Włącz profil do pracy"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Nagrywanie lub odtwarzanie dźwięku podczas połączeń telefonicznych"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Zezwala na odtwarzanie dźwięku podczas rozmów telefonicznych przez aplikację przypisaną jako domyślnie wybierającą numery."</string>
</resources>
diff --git a/core/res/res/values-pt-rBR/strings.xml b/core/res/res/values-pt-rBR/strings.xml
index dfb5bef..7bdfffa 100644
--- a/core/res/res/values-pt-rBR/strings.xml
+++ b/core/res/res/values-pt-rBR/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Capturas de tela para o relatório de bug serão feitas em <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
<item quantity="other">Capturas de tela para o relatório de bug serão feitas em <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Captura de tela com o relatório do bug concluída"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Falha ao capturar a tela com o relatório do bug"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modo silencioso"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Som DESATIVADO"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"O som está ATIVADO"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite que o app continue uma chamada que foi iniciada em outro app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ler números de telefone"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permite que o app acesse os número de telefone do dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"manter a tela do carro ativada"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"impedir modo de inatividade do tablet"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"evitar que seu dispositivo Android TV entre no modo de suspensão"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"impedir modo de inatividade do telefone"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite que o app mantenha a tela do carro ativada."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite que o app impeça a suspensão do tablet."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite que o app impeça o dispositivo Android TV de entrar no modo de suspensão."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite que o app impeça a suspensão do telefone."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Aumentar o volume acima do nível recomendado?\n\nOuvir em volume alto por longos períodos pode danificar sua audição."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Usar atalho de Acessibilidade?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Quando o atalho estiver ativado, pressione os dois botões de volume por três segundos para iniciar um recurso de acessibilidade."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editar atalhos"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancelar"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desativar atalho"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sem classificação"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Você definiu a importância dessas notificações."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Isso é importante por causa das pessoas envolvidas."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificação personalizada do app"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um usuário com essa conta)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Adicionar um idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> foi colocado no intervalo \"RESTRITO\""</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Pessoal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Trabalho"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Não é possível compartilhar com apps de trabalho"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Não é possível compartilhar com apps pessoais"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Seu administrador de TI bloqueou o compartilhamento entre apps pessoais e de trabalho"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ativar apps de trabalho"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ative os apps de trabalho para acessar apps e contatos profissionais"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nenhum app disponível"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Não foi possível encontrar nenhum app"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ativar perfil de trabalho"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Gravar ou tocar áudio em chamadas telefônicas"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permitir que esse app grave ou toque áudio em chamadas telefônicas quando for usado como aplicativo discador padrão."</string>
</resources>
diff --git a/core/res/res/values-pt-rPT/strings.xml b/core/res/res/values-pt-rPT/strings.xml
index 00c56dd..da2207e 100644
--- a/core/res/res/values-pt-rPT/strings.xml
+++ b/core/res/res/values-pt-rPT/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">A tirar uma captura de ecrã do relatório de erro dentro de <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
<item quantity="one">A tirar uma captura de ecrã do relatório de erro dentro de <xliff:g id="NUMBER_0">%d</xliff:g> segundo…</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Captura de ecrã tirada com o relatório de erro."</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Falha ao tirar captura de ecrã com o relatório de erro."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modo silencioso"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Som desativado"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"O som está ativado"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite à aplicação continuar uma chamada iniciada noutra aplicação."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ler os números de telefone"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permite à aplicação aceder aos números de telefone do dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"manter o ecrã do automóvel ligado"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"impedir que o tablet entre em inactividade"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"impedir o seu dispositivo Android TV de entrar no modo de suspensão"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"impedir modo de inactividade do telefone"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite que a app mantenha o ecrã do automóvel ligado."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite que a aplicação impeça o tablet de entrar no modo de suspensão."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite que a aplicação impeça o seu dispositivo Android TV de entrar no modo de suspensão."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite que a aplicação impeça o telemóvel de entrar em inatividade."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Aumentar o volume acima do nível recomendado?\n\nOuvir com um volume elevado durante longos períodos poderá ser prejudicial para a sua audição."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Pretende utilizar o atalho de acessibilidade?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Quando o atalho está ativado, premir ambos os botões de volume durante 3 segundos inicia uma funcionalidade de acessibilidade."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editar atalhos"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancelar"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desativar atalho"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sem categoria"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Definiu a importância destas notificações."</string>
<string name="importance_from_person" msgid="4235804979664465383">"É importante devido às pessoas envolvidas."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificação de app personalizada"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Pretende permitir que a aplicação <xliff:g id="APP">%1$s</xliff:g> crie um novo utilizador com a conta <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um utilizador com esta conta)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Pretende permitir que a aplicação <xliff:g id="APP">%1$s</xliff:g> crie um novo utilizador com a conta <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Adicionar um idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> foi colocado no contentor RESTRITO."</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Pessoal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Trabalho"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Não é possível partilhar com apps de trabalho."</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Não é possível partilhar com apps pessoais."</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"O seu administrador de TI bloqueou a partilha entre as apps de trabalho e pessoais."</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ative as apps de trabalho."</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ative as apps de trabalho para aceder às apps de trabalho e aos contactos."</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nenhuma app disponível."</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Não foi possível encontrar quaisquer apps."</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ativar perfil de trabalho"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Gravar ou reproduzir áudio em chamadas telefónicas"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permite que esta app, quando atribuída como uma aplicação de telefone predefinida, grave ou reproduza áudio em chamadas telefónicas."</string>
</resources>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index dfb5bef..7bdfffa 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Capturas de tela para o relatório de bug serão feitas em <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
<item quantity="other">Capturas de tela para o relatório de bug serão feitas em <xliff:g id="NUMBER_1">%d</xliff:g> segundos.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Captura de tela com o relatório do bug concluída"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Falha ao capturar a tela com o relatório do bug"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modo silencioso"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Som DESATIVADO"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"O som está ATIVADO"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite que o app continue uma chamada que foi iniciada em outro app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ler números de telefone"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permite que o app acesse os número de telefone do dispositivo."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"manter a tela do carro ativada"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"impedir modo de inatividade do tablet"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"evitar que seu dispositivo Android TV entre no modo de suspensão"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"impedir modo de inatividade do telefone"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite que o app mantenha a tela do carro ativada."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite que o app impeça a suspensão do tablet."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite que o app impeça o dispositivo Android TV de entrar no modo de suspensão."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite que o app impeça a suspensão do telefone."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Aumentar o volume acima do nível recomendado?\n\nOuvir em volume alto por longos períodos pode danificar sua audição."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Usar atalho de Acessibilidade?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Quando o atalho estiver ativado, pressione os dois botões de volume por três segundos para iniciar um recurso de acessibilidade."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editar atalhos"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Cancelar"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Desativar atalho"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Sem classificação"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Você definiu a importância dessas notificações."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Isso é importante por causa das pessoas envolvidas."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificação personalizada do app"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g> (já existe um usuário com essa conta)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Permitir que o app <xliff:g id="APP">%1$s</xliff:g> crie um novo usuário com <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Adicionar um idioma"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> foi colocado no intervalo \"RESTRITO\""</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Pessoal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Trabalho"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Não é possível compartilhar com apps de trabalho"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Não é possível compartilhar com apps pessoais"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Seu administrador de TI bloqueou o compartilhamento entre apps pessoais e de trabalho"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ativar apps de trabalho"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ative os apps de trabalho para acessar apps e contatos profissionais"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nenhum app disponível"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Não foi possível encontrar nenhum app"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ativar perfil de trabalho"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Gravar ou tocar áudio em chamadas telefônicas"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permitir que esse app grave ou toque áudio em chamadas telefônicas quando for usado como aplicativo discador padrão."</string>
</resources>
diff --git a/core/res/res/values-ro/strings.xml b/core/res/res/values-ro/strings.xml
index e4eaf80..e489249 100644
--- a/core/res/res/values-ro/strings.xml
+++ b/core/res/res/values-ro/strings.xml
@@ -252,10 +252,8 @@
<item quantity="other">Peste <xliff:g id="NUMBER_1">%d</xliff:g> de secunde se va realiza o captură de ecran pentru raportul de eroare.</item>
<item quantity="one">Peste <xliff:g id="NUMBER_0">%d</xliff:g> secundă se va realiza o captură de ecran pentru raportul de eroare.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"S-a realizat captura de ecran a raportului de eroare"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Nu s-a realizat captura de ecran a raportului de eroare"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mod Silențios"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Sunetul este DEZACTIVAT"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Sunetul este ACTIVAT"</string>
@@ -457,9 +455,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Permite aplicației să continue un apel care a fost inițiat dintr-o altă aplicație."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"să citească numerele de telefon"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Permite aplicației să acceseze numerele de telefon ale dispozitivului."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"menține ecranul mașinii activat"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"împiedicarea computerului tablet PC să intre în repaus"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"împiedică dispozitivul Android TV să intre în repaus"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"împiedicare intrare telefon în repaus"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Permite aplicației să mențină ecranul mașinii activat."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Permite aplicației să împiedice intrarea tabletei în stare de repaus."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Permite aplicației să împiedice intrarea dispozitivului Android TV în stare de inactivitate."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Permite aplicației să împiedice intrarea telefonului în stare de repaus."</string>
@@ -1653,6 +1653,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Ridicați volumul mai sus de nivelul recomandat?\n\nAscultarea la volum ridicat pe perioade lungi de timp vă poate afecta auzul."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Utilizați comanda rapidă pentru accesibilitate?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Atunci când comanda rapidă este activată, dacă apăsați ambele butoane de volum timp de trei secunde, veți lansa o funcție de accesibilitate."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Editați comenzile rapide"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Anulați"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Dezactivați comanda rapidă"</string>
@@ -1885,8 +1891,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Neclasificate"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Dvs. setați importanța acestor notificări."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Notificarea este importantă având în vedere persoanele implicate."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Notificare de aplicație personalizată"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Permiteți ca <xliff:g id="APP">%1$s</xliff:g> să creeze un nou utilizator folosind <xliff:g id="ACCOUNT">%2$s</xliff:g>? (există deja un utilizator cu acest cont)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Permiteți ca <xliff:g id="APP">%1$s</xliff:g> să creeze un nou utilizator folosind <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Adăugați o limbă"</string>
@@ -2062,14 +2067,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> a fost adăugat la grupul RESTRICȚIONATE"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Serviciu"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nu se poate trimite către aplicații pentru lucru"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nu se poate trimite către aplicații personale"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Administratorul IT a blocat trimiterea între aplicațiile personale și pentru lucru"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Activați aplicațiile pentru lucru"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Activați aplicațiile pentru lucru ca să le accesați pe acestea și persoanele de contact"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nicio aplicație disponibilă"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nu s-a găsit nicio aplicație"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Comutați la profilul de lucru"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Înregistrează sau redă conținut audio în apelurile telefonice"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Permite acestei aplicații, atunci când este setată ca aplicație telefon prestabilită, să înregistreze sau să redea conținut audio în apelurile telefonice."</string>
</resources>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index 7cd1633..7abf646 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -255,10 +255,8 @@
<item quantity="many">Скриншот будет сделан через <xliff:g id="NUMBER_1">%d</xliff:g> секунд</item>
<item quantity="other">Скриншот будет сделан через <xliff:g id="NUMBER_1">%d</xliff:g> секунды</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Сделан скриншот с информацией об ошибке."</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Не удалось сделать скриншот с информацией об ошибке."</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Режим без звука"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Выключить"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Включить"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Разрешает приложению продолжить вызов, начатый в другом приложении."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"чтение номеров телефонов"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Разрешает приложению доступ к телефонным номерам устройства."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"Не выключать экран автомобиля"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"Отключение спящего режима"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"запрещать переход устройства Android TV в спящий режим"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"Отключение спящего режима"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Приложение сможет держать экран автомобиля включенным."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Приложение сможет запрещать перевод планшетного ПК в спящий режим."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Приложение сможет препятствовать переводу устройства Android TV в спящий режим."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Приложение сможет запрещать перевод телефона в спящий режим."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Установить громкость выше рекомендуемого уровня?\n\nВоздействие громкого звука в течение долгого времени может привести к повреждению слуха."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Использовать быстрое включение?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Чтобы использовать функцию специальных возможностей, когда она включена, нажмите и удерживайте обе кнопки регулировки громкости в течение трех секунд."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Изменить быстрые клавиши"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Отмена"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Деактивировать быстрое включение"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Без категории"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Вы определяете важность этих уведомлений."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Важное (люди)"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Уведомление пользовательского приложения"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Разрешить приложению \"<xliff:g id="APP">%1$s</xliff:g>\" создать нового пользователя с аккаунтом <xliff:g id="ACCOUNT">%2$s</xliff:g> (пользователь с этим аккаунтом уже существует)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Разрешить приложению \"<xliff:g id="APP">%1$s</xliff:g>\" создать нового пользователя с аккаунтом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Добавьте язык"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Приложение \"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>\" помещено в категорию с ограниченным доступом."</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Личный"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Рабочий"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Нельзя обмениваться данными с рабочими приложениями"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Нельзя обмениваться данными с личными приложениями"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Обмен данными между личными и рабочими приложениями заблокирован системным администратором."</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Включите рабочие приложения"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Включите рабочие приложения, чтобы получить доступ к ним и контактам."</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Нет доступных приложений"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Приложения не найдены."</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Включить рабочий профиль"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Запись и воспроизведение телефонных разговоров"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Если это приложение используется для звонков по умолчанию, оно сможет записывать и воспроизводить телефонные разговоры."</string>
</resources>
diff --git a/core/res/res/values-si/strings.xml b/core/res/res/values-si/strings.xml
index 37db789..67f1ca1 100644
--- a/core/res/res/values-si/strings.xml
+++ b/core/res/res/values-si/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">තත්පර <xliff:g id="NUMBER_1">%d</xliff:g>කින් දෝෂ වාර්තාව සඳහා තිර රුවක් ලබා ගනිමින්</item>
<item quantity="other">තත්පර <xliff:g id="NUMBER_1">%d</xliff:g>කින් දෝෂ වාර්තාව සඳහා තිර රුවක් ලබා ගනිමින්</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"දෝෂ වාර්තාව සමගින් ගත් තිර රුව"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"දෝෂ වාර්තාව සමගින් තිර රුව ගැනීමට අසමත් විය"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"නිහඬ ආකාරය"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ශබ්දය අක්රියයි"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"හඬ ක්රියාත්මකයි"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"වෙනත් යෙදුමක ආරම්භ කරන ලද ඇමතුමක් දිගටම කරගෙන යාමට යෙදුමට ඉඩ දෙයි."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"දුරකථන අංක කියවන්න"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"උපාංගයේ දුරකථන අංක වෙත ප්රවේශයට යෙදුමට ඉඩ දෙයි."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"මෝටර් රථ තිරය ක්රියාත්මකව තබා ගන්න"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ටැබ්ලටය නින්දෙන් වැළක්වීම"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ඔබගේ Android TV උපාංගය නිදා ගැනීමෙන් වැළැක්වීම"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"දුරකථනය නින්දට යාමෙන් වළකන්න"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"යෙදුමට මෝටර් රථ තිරය ක්රියාත්මකව තබා ගැනීමට ඉඩ දෙයි."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ටැබ්ලටය නින්දට යාමෙන් වැලැක්වීමට යෙදුමට අවසර දෙන්න."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"යෙදුමට ඔබේ Android TV උපාංගය නින්දට යාමට වැළැක්වීමට ඉඩ දෙයි."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"දුරකථනය නින්දට යාමෙන් වැලැක්වීමට යෙදුමට අවසර දෙන්න."</string>
@@ -1633,6 +1633,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"නිර්දේශිතයි මට්ටමට වඩා ශබ්දය වැඩිද?\n\nදිගු කාලයක් සඳහා ඉහළ ශබ්දයක් ඇසීමෙන් ඇතැම් විට ඔබගේ ඇසීමට හානි විය හැක."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ප්රවේශ්යතා කෙටිමඟ භාවිතා කරන්නද?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"කෙටිමග ක්රියාත්මක විට, හඬ පරිමා බොත්තම් දෙකම තත්පර 3ක් තිස්සේ එබීමෙන් ප්රවේශ්යතා විශේෂාංගය ආරම්භ වනු ඇත."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"කෙටිමං සංස්කරණ කරන්න"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"අවලංගු කරන්න"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"කෙටිමඟ ක්රියාවිරහිත කරන්න"</string>
@@ -1855,8 +1861,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"වර්ගීකරණය නොකළ"</string>
<string name="importance_from_user" msgid="2782756722448800447">"ඔබ මෙම දැනුම්දීම්වල වැදගත්කම සකසා ඇත."</string>
<string name="importance_from_person" msgid="4235804979664465383">"සම්බන්ධ වූ පුද්ගලයන් නිසා මෙය වැදගත් වේ."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"අභිරුචි යෙදුම් දැනුම් දීම"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> හට <xliff:g id="ACCOUNT">%2$s</xliff:g> සමගින් නව පරිශීලකයෙකු සෑදීමට ඉඩ දෙන්නද (මෙම ගිණුම සහිත පරිශීලකයෙකු දැනටමත් සිටී) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> හට <xliff:g id="ACCOUNT">%2$s</xliff:g> සමගින් නව පරිශීලකයෙකු සෑදීමට ඉඩ දෙන්නද ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"භාෂාවක් එක් කරන්න"</string>
@@ -2030,14 +2035,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> අවහිර කළ බාල්දියට දමා ඇත"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"පුද්ගලික"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"කාර්යාල"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"කාර්යාල යෙදුම් සමග බෙදා ගැනීමට නොහැකිය"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"පෞද්ගලික යෙදුම් සමග බෙදා ගැනීමට නොහැකිය"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ඔබේ IT පරිපාලක පෞද්ගලික සහ කාර්යාල යෙදුම් අතර බෙදා ගැනීම අවහිර කළා"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"කාර්යාල යෙදුම් ක්රියාත්මක කරන්න"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"කාර්යාල යෙදුම් & සම්බන්ධතා වෙත ප්රවේශ වීමට කාර්යාල යෙදුම් ක්රියාත්මක කරන්න"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ලබා ගත හැකි යෙදුම් නැත"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"අපට කිසිදු යෙදුමක් සොයා ගැනීමට නොහැකි විය"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"කාර්යාලයට මාරු කරන්න"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ටෙලිෆොනි ඇමතුම්වලින් ඕඩියෝ පටිගත කරන්න නැතහොත් වාදනය කරන්න"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"පෙරනිමි ඩයලන යෙදුමක් ලෙස පැවරූ විට, මෙම යෙදුමට ටෙලිෆොනි ඇමතුම්වලින් ඕඩියෝ පටිගත කිරීමට හෝ වාදනය කිරීමට ඉඩ දෙයි."</string>
</resources>
diff --git a/core/res/res/values-sk/strings.xml b/core/res/res/values-sk/strings.xml
index 3be2f09..de9175d 100644
--- a/core/res/res/values-sk/strings.xml
+++ b/core/res/res/values-sk/strings.xml
@@ -255,10 +255,8 @@
<item quantity="other">Snímka obrazovky pre hlásenie chyby sa vytvorí o <xliff:g id="NUMBER_1">%d</xliff:g> sekúnd.</item>
<item quantity="one">Snímka obrazovky pre hlásenie chyby sa vytvorí o <xliff:g id="NUMBER_0">%d</xliff:g> sekundu.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Bola vytvorená snímka obrazovky s hlásením chyby"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Nepodarilo sa vytvoriť snímku obrazovky s hlásením chyby"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Tichý režim"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zvuk je VYPNUTÝ."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zvuk je zapnutý"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Umožňuje aplikácii pokračovať v hovore začatom v inej aplikácii."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"čítanie telefónnych čísel"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Umožňuje aplikácii pristupovať k telefónnym číslam zariadenia."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"zabránenie vypnutiu obrazovky auta"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"zabránenie prechodu tabletu do režimu spánku"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"zabránenie prechodu zariadenia Android TV do režimu spánku"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"deaktivovať režim spánku"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Umožňuje aplikácii zabrániť vypnutiu obrazovky auta."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Umožňuje aplikácii zabrániť prechodu tabletu do režimu spánku."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Umožňuje aplikácii zabrániť prechodu zariadenia Android TV do režimu spánku."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Umožňuje aplikácii zabrániť prechodu telefónu do režimu spánku."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Zvýšiť hlasitosť nad odporúčanú úroveň?\n\nDlhodobé počúvanie pri vysokej hlasitosti môže poškodiť váš sluch."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Použiť skratku dostupnosti?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Keď je skratka zapnutá, stlačením obidvoch tlačidiel hlasitosti na tri sekundy spustíte funkciu dostupnosti."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Upraviť skratky"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Zrušiť"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Vypnúť skratku"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nekategorizované"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Nastavili ste dôležitosť týchto upozornení."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Táto správa je dôležitá vzhľadom na osoby, ktorých sa to týka."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Vlastné upozornenie na aplikáciu"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Chcete povoliť aplikácii <xliff:g id="APP">%1$s</xliff:g> vytvoriť nového používateľa pomocou účtu <xliff:g id="ACCOUNT">%2$s</xliff:g> (používateľ s týmto účtom už existuje)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Chcete povoliť aplikácii <xliff:g id="APP">%1$s</xliff:g> vytvoriť nového používateľa pomocou účtu <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Pridať jazyk"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Balík <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> bol vložený do kontajnera OBMEDZENÉ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Osobné"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Práca"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nedá sa zdieľa s pracovnými aplikáciami"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nedá sa zdieľať s osobnými aplikáciami"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Váš správca IT zablokoval zdieľanie medzi osobnými a pracovnými aplikáciami"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Zapnite pracovné aplikácie"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ak chcete získať prístup k pracovným aplikáciám a kontaktom, zapnite pracovné aplikácie"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"K dispozícii nie sú žiadne aplikácie"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Neboli nájdené žiadne aplikácie"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Zapnúť pracovný profil"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Nahrávanie alebo prehrávanie zvuku počas telefonických hovorov"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Povoľuje tejto aplikácii, keď je priradená ako predvolená aplikácia na vytáčanie, nahrávať alebo prehrávať zvuk počas telefonických hovorov."</string>
</resources>
diff --git a/core/res/res/values-sl/strings.xml b/core/res/res/values-sl/strings.xml
index 7178601..d5ae025 100644
--- a/core/res/res/values-sl/strings.xml
+++ b/core/res/res/values-sl/strings.xml
@@ -255,10 +255,8 @@
<item quantity="few">Posnetek zaslona za poročilo o napakah bo narejen čez <xliff:g id="NUMBER_1">%d</xliff:g> s.</item>
<item quantity="other">Posnetek zaslona za poročilo o napakah bo narejen čez <xliff:g id="NUMBER_1">%d</xliff:g> s.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Posnetek zaslona s poročilom o napakah je izdelan"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Izdelava posnetka zaslona s poročilom o napakah ni uspela"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Tihi način"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zvok je IZKLOPLJEN"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zvok je VKLOPLJEN"</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Aplikaciji dovoljuje nadaljevanje klica, ki se je začel v drugi aplikaciji."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"branje telefonskih številk"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Aplikaciji dovoljuje dostop do telefonskih številk v napravi."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"Ohranjanje vklopljenega zaslona avtomobila"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"preprečitev prehoda tabličnega računalnika v stanje pripravljenosti"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"preprečevanje preklopa naprave Android TV v stanje pripravljenosti"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"preprečevanje prehoda v stanje pripravljenosti telefona"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Aplikaciji omogoča, da zaslon avtomobila ohranja vklopljen."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Omogoča, da aplikacija prepreči prehod tabličnega računalnika v stanje pripravljenosti."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Aplikaciji dovoljuje, da prepreči preklop naprave Android TV v stanje pripravljenosti."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Aplikaciji omogoča, da v telefonu prepreči prehod v stanje pripravljenosti."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Ali želite povečati glasnost nad priporočeno raven?\n\nDolgotrajno poslušanje pri veliki glasnosti lahko poškoduje sluh."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Želite uporabljati bližnjico funkcij za ljudi s posebnimi potrebami?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Ko je bližnjica vklopljena, pritisnite gumba za glasnost in ju pridržite tri sekunde, če želite zagnati funkcijo za ljudi s posebnimi potrebami."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Uredi bližnjice"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Prekliči"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Izklopi bližnjico"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Nekategorizirano"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Vi določite raven pomembnosti teh obvestil."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Pomembno zaradi udeleženih ljudi."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Obvestilo po meri iz aplikacije"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Ali aplikaciji <xliff:g id="APP">%1$s</xliff:g> dovolite, da ustvari novega uporabnika za račun <xliff:g id="ACCOUNT">%2$s</xliff:g> (uporabnik s tem računom že obstaja)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Ali aplikaciji <xliff:g id="APP">%1$s</xliff:g> dovolite, da ustvari novega uporabnika za račun <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dodajanje jezika"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Paket <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> je bil dodan v segment OMEJENO"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Osebno"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Služba"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Deljenje z delovnimi aplikacijami ni mogoče"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Deljenje z osebnimi aplikacijami ni mogoče"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Skrbnik za IT je blokiral deljenje med osebnimi in delovnimi aplikacijami"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Vklopi delovne aplikacije"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Če želite dostopati do delovnih aplikacij in stikov, vklopite delovne aplikacije"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Na voljo ni nobena aplikacija"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Aplikacij ni bilo mogoče najti"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Vklopi delovni profil"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Snemanje ali predvajanje zvoka med telefonskimi klici"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Tej aplikaciji dovoljuje snemanje ali predvajanje zvoka med telefonskimi klici, ko je nastavljena kot privzeta aplikacija za klicanje."</string>
</resources>
diff --git a/core/res/res/values-sq/strings.xml b/core/res/res/values-sq/strings.xml
index 2448521..3cb7288 100644
--- a/core/res/res/values-sq/strings.xml
+++ b/core/res/res/values-sq/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Marrja e pamjes së ekranit për raportin e defektit në kod në <xliff:g id="NUMBER_1">%d</xliff:g> sekonda.</item>
<item quantity="one">Marrja e pamjes së ekranit për raportin e defektit në kod në <xliff:g id="NUMBER_0">%d</xliff:g> sekondë.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"U shkrep pamja e ekranit me raportin e defekteve në kod"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Nuk u shkrep pamja e ekranit me raportin e defekteve në kod"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Modaliteti \"në heshtje\""</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Zëri është çaktivizuar"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Zëri është i aktivizuar"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Lejon që aplikacioni të vazhdojë një telefonatë që është nisur në një aplikacion tjetër."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"lexo numrat e telefonit"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Lejon që aplikacioni të ketë qasje te numrat e telefonit të pajisjes."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"të mbajë ekranin e makinës të aktivizuar"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"parandalo kalimin e tabletit në fjetje"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"parandalon kalimin në fjetje të pajisjes sate Android TV"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"parandalo kalimin e telefonit në fjetje"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Lejon që aplikacioni të mbajë ekranin e makinës të aktivizuar."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Lejon aplikacionin të parandalojë tabletin nga fjetja."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Lejon aplikacionin të parandalojë kalimin në fjetje të pajisjes sate Android TV."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Lejon aplikacionin të parandalojë telefonin nga fjetja."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Të ngrihet volumi mbi nivelin e rekomanduar?\n\nDëgjimi me volum të lartë për periudha të gjata mund të dëmtojë dëgjimin."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Të përdoret shkurtorja e qasshmërisë?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kur shkurtorja është e aktivizuar, shtypja e të dy butonave për 3 sekonda do të nisë një funksion qasshmërie."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Redakto shkurtoret"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Anulo"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Çaktivizo shkurtoren"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"E pakategorizuara"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ke caktuar rëndësinë e këtyre njoftimeve."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Është i rëndësishëm për shkak të personave të përfshirë."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Njoftim i personalizuar për aplikacionin"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Të lejohet <xliff:g id="APP">%1$s</xliff:g> që të krijojë një përdorues të ri me <xliff:g id="ACCOUNT">%2$s</xliff:g> (një përdorues me këtë llogari ekziston tashmë) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Të lejohet <xliff:g id="APP">%1$s</xliff:g> që të krijojë një përdorues të ri me <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Shto një gjuhë"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> është vendosur në grupin E KUFIZUAR"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Puna"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Nuk mund të ndash me aplikacionet e punës"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Nuk mund të ndash me aplikacionet personale"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Administratori yt i teknologjisë së informacionit ka bllokuar ndarjen mes aplikacioneve personale dhe atyre të punës"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Aktivizo aplikacionet e punës"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Aktivizo aplikacionet e punës për të pasur qasje tek aplikacionet dhe kontaktet e punës"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Nuk ofrohet asnjë aplikacion"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Nuk mund të gjenim asnjë aplikacion"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Kalo në profilin e punës"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Të regjistrojë ose luajë audio në telefonata"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Lejon këtë aplikacion, kur caktohet si aplikacioni i parazgjedhur i formuesit të numrave, të regjistrojë ose luajë audio në telefonata."</string>
</resources>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index 3edfdb1..c84f4a9 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -252,10 +252,8 @@
<item quantity="few">Направићемо снимак екрана ради извештаја о грешци за <xliff:g id="NUMBER_1">%d</xliff:g> секунде.</item>
<item quantity="other">Направићемо снимак екрана ради извештаја о грешци за <xliff:g id="NUMBER_1">%d</xliff:g> секунди.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Екран са извештајем о грешци је снимљен"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Снимање екрана са извештајем о грешци није успело"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Нечујни режим"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Звук је ИСКЉУЧЕН"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Звук је УКЉУЧЕН"</string>
@@ -457,9 +455,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Дозвољава апликацији да настави позив који је започет у другој апликацији."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"читање бројева телефона"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Дозвољава апликацији да приступа бројевима телефона на уређају."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"не искључуј екран у аутомобилу"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"спречавање преласка таблета у стање спавања"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"спречава Android TV уређај да пређе у стање спавања"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"спречавање преласка телефона у стање спавања"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Дозвољава апликацији да не искључује екран у аутомобилу."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Дозвољава апликацији да спречи таблет да пређе у стање спавања."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Дозвољава апликацији да спречи Android TV уређај да пређе у стање спавања."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Дозвољава апликацији да спречи телефон да пређе у стање спавања."</string>
@@ -1653,6 +1653,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Желите да појачате звук изнад препорученог нивоа?\n\nСлушање гласне музике дуже време може да вам оштети слух."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Желите ли да користите пречицу за приступачност?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Када је пречица укључена, притисните оба дугмета за јачину звука да бисте покренули функцију приступачности."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Измените пречице"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Откажи"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Искључи пречицу"</string>
@@ -1885,8 +1891,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Некатегоризовано"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ви подешавате важност ових обавештења."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Ово је важно због људи који учествују."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Прилагођено обавештење о апликацији"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Желите ли да дозволите да <xliff:g id="APP">%1$s</xliff:g> направи новог корисника са налогом <xliff:g id="ACCOUNT">%2$s</xliff:g> (корисник са тим налогом већ постоји)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Желите ли да дозволите да <xliff:g id="APP">%1$s</xliff:g> направи новог корисника са налогом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Додајте језик"</string>
@@ -2062,14 +2067,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Пакет <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> је додат у сегмент ОГРАНИЧЕНО"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Лични"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Пословни"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Не можете да делите садржај са апликацијама за посао"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Не можете да делите садржај са личним апликацијама"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ИТ администратор је блокирао дељење између личних апликација и апликација за посао"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Укључите апликације за посао"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Укључите апликације за посао да бисте приступили апликацијама и контактима за посао"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Нема доступних апликација"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Нисмо пронашли ниједну апликацију"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Укључи профил за Work"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Снимање или пуштање звука у телефонским позивима"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Омогућава овој апликацији, када је додељена као подразумевана апликација за позивање, да снима или пушта звук у телефонским позивима."</string>
</resources>
diff --git a/core/res/res/values-sv/strings.xml b/core/res/res/values-sv/strings.xml
index 73e7efc..4c07f22 100644
--- a/core/res/res/values-sv/strings.xml
+++ b/core/res/res/values-sv/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Tar en skärmdump till felrapporten om <xliff:g id="NUMBER_1">%d</xliff:g> sekunder.</item>
<item quantity="one">Tar en skärmdump till felrapporten om <xliff:g id="NUMBER_0">%d</xliff:g> sekund.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Skärmdump med felrapport har tagits"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Det gick inte att ta en skärmdump med felrapport"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Tyst läge"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Ljudet är AV"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Ljudet är PÅ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Tillåter att appen fortsätter ett samtal som har startats i en annan app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"läsa telefonnummer"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Appen beviljas åtkomst till enhetens telefonnummer."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"låta bilens skärm vara på"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"förhindra att surfplattan går in i viloläge"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"förhindra att Android TV-enheten försätts i viloläge"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"förhindra att telefonen sätts i viloläge"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Tillåter appen att låta bilens skärm vara på."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Tillåter att appen förhindrar att surfplattan går in i viloläge."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Tillåter att appen förhindrar att Android TV-enheten försätts i viloläge."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Tillåter att appen förhindrar att mobilen går in i viloläge."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Vill du höja volymen över den rekommenderade nivån?\n\nAtt lyssna med stark volym långa stunder åt gången kan skada hörseln."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Vill du använda Aktivera tillgänglighet snabbt?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"När kortkommandot har aktiverats startar du en tillgänglighetsfunktion genom att trycka ned båda volymknapparna i tre sekunder."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Redigera genvägar"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Avbryt"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Inaktivera kortkommandot"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Okategoriserad"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Du anger hur viktiga aviseringarna är."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Detta är viktigt på grund av personerna som deltar."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Anpassad appavisering"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Tillåter du att <xliff:g id="APP">%1$s</xliff:g> skapar en ny användare för <xliff:g id="ACCOUNT">%2$s</xliff:g> (det finns redan en användare med det här kontot)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Tillåter du att <xliff:g id="APP">%1$s</xliff:g> skapar en ny användare för <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Lägg till ett språk"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> har placerats i hinken RESTRICTED"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Privat"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Jobb"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Det går inte att dela med jobbappar"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Det går inte att dela med personliga appar"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"IT-administratören har blockerat delning mellan personliga och jobbappar"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Aktivera jobbappar"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Aktivera jobbappar om du vill få åtkomst till jobbrelaterade appar och kontakter"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Det finns inga tillgängliga appar"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Vi hittade inga appar"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Aktivera jobbprofil"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Spela in och spela upp ljud i telefonsamtal"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Tillåter appen att spela in och spela upp ljud i telefonsamtal när den har angetts som standardapp för uppringningsfunktionen."</string>
</resources>
diff --git a/core/res/res/values-sw/strings.xml b/core/res/res/values-sw/strings.xml
index 5ef601f..b5c07b3 100644
--- a/core/res/res/values-sw/strings.xml
+++ b/core/res/res/values-sw/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Inapiga picha ya skrini ili iripoti hitilafu baada ya sekunde <xliff:g id="NUMBER_1">%d</xliff:g>.</item>
<item quantity="one">Inapiga picha ya skrini ili iripoti hitilafu baada ya sekunde <xliff:g id="NUMBER_0">%d</xliff:g>.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Umepiga picha ya skrini ya ripoti ya hitilafu"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Imeshindwa kupiga picha ya skrini ya ripoti ya hitilafu"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Mtindo wa kimya"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Sauti Imezimwa"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Sauti imewashwa"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Huruhusu programu kuendelea na simu ambayo ilianzishwa katika programu nyingine."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"kusoma nambari za simu"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Inaruhusu programu kufikia nambari za simu zilizo kwenye kifaa."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"kuweka skrini ya gari isijizime"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"zuia kompyuta ndogo dhidi ya kulala"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"zuia kifaa chako cha Android TV kisiingie katika hali tuli"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"kuzuia simu isilale"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Huruhusu programu kuweka skrini ya gari isijizime."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Inaruhusu programu kuzuia kompyuta kibao kwenda kulala."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Huruhusu programu izuie kifaa chako cha Android TV kisiingie katika hali tuli."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Inaruhusu programu kuzuia simu isiende kulala."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Ungependa kupandisha sauti zaidi ya kiwango kinachopendekezwa?\n\nKusikiliza kwa sauti ya juu kwa muda mrefu kunaweza kuharibu uwezo wako wa kusikia."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Ungependa kutumia njia ya mkato ya ufikivu?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Unapowasha kipengele cha njia ya mkato, hatua ya kubonyeza vitufe vyote viwili vya sauti kwa sekunde tatu itafungua kipengele cha ufikivu."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Kubadilisha njia za mkato"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Ghairi"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Zima kipengele cha Njia ya Mkato"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Ambazo aina haijabainishwa"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Uliweka mipangilio ya umuhimu wa arifa hizi."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Hii ni muhimu kwa sababu ya watu waliohusika."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Arifa ya programu maalum"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Ruhusu <xliff:g id="APP">%1$s</xliff:g> iweke Mtumiaji mpya ikitumia <xliff:g id="ACCOUNT">%2$s</xliff:g> (Je, tayari kuna mtumiaji anayetumia akaunti hii)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Ungependa kuruhusu <xliff:g id="APP">%1$s</xliff:g> iweke Mtumiaji mpya ikitumia <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Ongeza lugha"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> kimewekwa katika kikundi KILICHODHIBITIWA"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Binafsi"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Kazini"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Imeshindwa kushiriki na programu za kazini"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Imeshindwa kushiriki na programu za binafsi"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Msimamizi wako wa TEHAMA amezuia kushiriki kati ya programu za binafsi na za kazini"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Washa programu za kazini"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Washa programu za kazini ili ufikie programu na anwani za kazini"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Hakuna programu zinazopatikana"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Hatujapata programu zozote"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Washa wasifu wa kazini"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Kurekodi au kucheza sauti katika simu"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Huruhusu programu hii, wakati imekabidhiwa kuwa programu chaguomsingi ya kipiga simu, kurekodi au kucheza sauti katika simu."</string>
</resources>
diff --git a/core/res/res/values-ta/strings.xml b/core/res/res/values-ta/strings.xml
index da6cf4b..8a8a327 100644
--- a/core/res/res/values-ta/strings.xml
+++ b/core/res/res/values-ta/strings.xml
@@ -193,14 +193,10 @@
<string name="network_logging_notification_text" msgid="1327373071132562512">"உங்கள் நிறுவனம் இந்தச் சாதனத்தை நிர்வகிக்கும், அத்துடன் அது நெட்வொர்க் ட்ராஃபிக்கைக் கண்காணிக்கலாம். விவரங்களுக்கு, தட்டவும்."</string>
<string name="location_changed_notification_title" msgid="4119726617105166830">"உங்கள் நிர்வாகியால் இருப்பிட அமைப்புகள் மாற்றப்பட்டன"</string>
<string name="location_changed_notification_text" msgid="198907268219396399">"உங்கள் இருப்பிட அமைப்புகளைப் பார்க்க தட்டவும்."</string>
- <!-- no translation found for country_detector (7023275114706088854) -->
- <skip />
- <!-- no translation found for location_service (2439187616018455546) -->
- <skip />
- <!-- no translation found for sensor_notification_service (7474531979178682676) -->
- <skip />
- <!-- no translation found for twilight_service (8964898045693187224) -->
- <skip />
+ <string name="country_detector" msgid="7023275114706088854">"நாட்டைக் கண்டறியும் அம்சம்"</string>
+ <string name="location_service" msgid="2439187616018455546">"இருப்பிடச் சேவை"</string>
+ <string name="sensor_notification_service" msgid="7474531979178682676">"சென்சார் அறிவிப்புச் சேவை"</string>
+ <string name="twilight_service" msgid="8964898045693187224">"Twilight சேவை"</string>
<string name="factory_reset_warning" msgid="6858705527798047809">"சாதனத் தரவு அழிக்கப்படும்"</string>
<string name="factory_reset_message" msgid="2657049595153992213">"நிர்வாகி ஆப்ஸை உபயோகிக்க முடியாது. இப்போது, உங்கள் சாதனம் ஆரம்ப நிலைக்கு மீட்டமைக்கப்படும்.\n\nஏதேனும் கேள்விகள் இருப்பின், உங்கள் நிறுவனத்தின் நிர்வாகியைத் தொடர்புகொள்ளவும்."</string>
<string name="printing_disabled_by" msgid="3517499806528864633">"பிரிண்ட் செய்வதை <xliff:g id="OWNER_APP">%s</xliff:g> தடுத்துள்ளது."</string>
@@ -458,9 +454,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"மற்றொரு பயன்பாட்டில் தொடங்கப்பட்ட அழைப்பைத் தொடருவதற்கு, ஆப்ஸை அனுமதிக்கிறது."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ஃபோன் எண்களைப் படித்தல்"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"சாதனத்தின் ஃபோன் எண்களை அணுக, ஆப்ஸை அனுமதிக்கும்."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"கார் திரையை ஆன் செய்து வைத்திருத்தல்"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"டேப்லெட் உறக்க நிலைக்குச் செல்வதைத் தடுத்தல்"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"உங்கள் Android TV உறக்க நிலைக்குச் செல்வதைத் தடுத்தல்"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"தொலைபேசி உறக்கநிலைக்குச் செல்வதைத் தடுத்தல்"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"கார் திரையை ஆன் செய்து வைத்திருப்பதற்கு இந்த ஆப்ஸை அனுமதிக்கும்."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"உறக்கநிலைக்குச் செல்லாமல் டேப்லெட்டைத் தடுக்க ஆப்ஸை அனுமதிக்கிறது."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Android TV உறக்க நிலைக்குச் செல்வதைத் தடுக்க ஆப்ஸை அனுமதிக்கும்."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"உறக்கநிலைக்குச் செல்லாமல் மொபைலைத் தடுக்க ஆப்ஸை அனுமதிக்கிறது."</string>
@@ -558,8 +556,7 @@
<string name="fingerprint_error_unable_to_process" msgid="1148553603490048742">"மீண்டும் முயற்சிக்கவும்."</string>
<string name="fingerprint_error_no_fingerprints" msgid="8671811719699072411">"கைரேகைப் பதிவுகள் எதுவும் இல்லை."</string>
<string name="fingerprint_error_hw_not_present" msgid="578914350967423382">"இந்தச் சாதனத்தில் கைரேகை சென்சார் இல்லை."</string>
- <!-- no translation found for fingerprint_error_security_update_required (7750187320640856433) -->
- <skip />
+ <string name="fingerprint_error_security_update_required" msgid="7750187320640856433">"சென்சார் தற்காலிகமாக முடக்கப்பட்டுள்ளது."</string>
<string name="fingerprint_name_template" msgid="8941662088160289778">"கைரேகை <xliff:g id="FINGERID">%d</xliff:g>"</string>
<string-array name="fingerprint_error_vendor">
</string-array>
@@ -603,8 +600,7 @@
<string name="face_error_unable_to_process" msgid="5723292697366130070">"முகத்தைச் சரிபார்க்க இயலவில்லை. மீண்டும் முயலவும்."</string>
<string name="face_error_not_enrolled" msgid="7369928733504691611">"’முகம் காட்டித் திறத்தலை’ நீங்கள் அமைக்கவில்லை."</string>
<string name="face_error_hw_not_present" msgid="1070600921591729944">"இந்த சாதனத்தில் ’முகம் காட்டித் திறத்தல்’ ஆதரிக்கப்படவில்லை."</string>
- <!-- no translation found for face_error_security_update_required (5076017208528750161) -->
- <skip />
+ <string name="face_error_security_update_required" msgid="5076017208528750161">"சென்சார் தற்காலிகமாக முடக்கப்பட்டுள்ளது."</string>
<string name="face_name_template" msgid="3877037340223318119">"முகம் <xliff:g id="FACEID">%d</xliff:g>"</string>
<string-array name="face_error_vendor">
</string-array>
@@ -1330,12 +1326,9 @@
<string name="adb_active_notification_title" msgid="408390247354560331">"USB பிழைதிருத்தம் இணைக்கப்பட்டது"</string>
<string name="adb_active_notification_message" msgid="5617264033476778211">"USB பிழைதிருத்தத்தை ஆஃப் செய்ய தட்டவும்"</string>
<string name="adb_active_notification_message" product="tv" msgid="6624498401272780855">"USB பிழைதிருத்தத்தை முடக்க, தேர்ந்தெடுக்கவும்."</string>
- <!-- no translation found for adbwifi_active_notification_title (6147343659168302473) -->
- <skip />
- <!-- no translation found for adbwifi_active_notification_message (930987922852867972) -->
- <skip />
- <!-- no translation found for adbwifi_active_notification_message (8633421848366915478) -->
- <skip />
+ <string name="adbwifi_active_notification_title" msgid="6147343659168302473">"வயர்லெஸ் பிழைதிருத்தம் இணைக்கப்பட்டது"</string>
+ <string name="adbwifi_active_notification_message" msgid="930987922852867972">"வயர்லெஸ் பிழைதிருத்தத்தை ஆஃப் செய்ய தட்டவும்"</string>
+ <string name="adbwifi_active_notification_message" product="tv" msgid="8633421848366915478">"வயர்லெஸ் பிழைதிருத்தத்தை முடக்க தேர்ந்தெடுக்கவும்."</string>
<string name="test_harness_mode_notification_title" msgid="2282785860014142511">"\'தன்னியக்க சோதனைப்\' பயன்முறை இயக்கப்பட்டது"</string>
<string name="test_harness_mode_notification_message" msgid="3039123743127958420">"’தன்னியக்க சோதனைப்\' பயன்முறையை முடக்க ஆரம்பநிலைக்கு மீட்டமைக்கவும்."</string>
<string name="console_running_notification_title" msgid="6087888939261635904">"சீரியல் கன்சோல் இயக்கப்பட்டது"</string>
@@ -1639,7 +1632,12 @@
<string name="allow_while_in_use_permission_in_fgs" msgid="4101339676785053656">"<xliff:g id="PACKAGENAME">%1$s</xliff:g> இல் இருந்து பின்னணியில் தொடங்கப்பட்ட முன்புலச் சேவைக்கு, வரவுள்ள R பதிப்புகளில் உபயோகத்தின்போது மட்டுமான அனுமதி இருக்காது. go/r-bg-fgs-restriction என்பதைப் பார்த்து பிழை அறிக்கை ஒன்றைச் சமர்ப்பிக்கவும்."</string>
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"பரிந்துரைத்த அளவை விட ஒலியை அதிகரிக்கவா?\n\nநீண்ட நேரத்திற்கு அதிகளவில் ஒலி கேட்பது கேட்கும் திறனைப் பாதிக்கலாம்."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"அணுகல்தன்மை ஷார்ட்கட்டைப் பயன்படுத்தவா?"</string>
- <!-- no translation found for accessibility_shortcut_toogle_warning (4161716521310929544) -->
+ <string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"ஷார்ட்கட் இயக்கத்தில் இருக்கும்போது ஒலியளவு பட்டன்கள் இரண்டையும் 3 வினாடிகளுக்கு அழுத்தினால் அணுகல்தன்மை அம்சம் இயக்கப்படும்."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
<skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"ஷார்ட்கட்களை மாற்று"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ரத்துசெய்"</string>
@@ -2038,24 +2036,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> என்பதை வரம்பிடப்பட்ட பக்கெட்திற்குள் சேர்க்கப்பட்டது"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"தனிப்பட்ட சுயவிவரம்"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"பணிச் சுயவிவரம்"</string>
- <!-- no translation found for resolver_cant_share_with_work_apps (7539495559434146897) -->
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
<skip />
- <!-- no translation found for resolver_cant_share_with_personal_apps (8020581735267157241) -->
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
<skip />
- <!-- no translation found for resolver_cant_share_cross_profile_explanation (3536237105241882679) -->
+ <string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"பணி ஆப்ஸுக்குப் பகிர முடியாது"</string>
+ <string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"தனிப்பட்ட ஆப்ஸுக்குப் பகிர முடியாது"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
<skip />
- <!-- no translation found for resolver_turn_on_work_apps (8987359079870455469) -->
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
<skip />
- <!-- no translation found for resolver_turn_on_work_apps_explanation (6322467455509618928) -->
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
<skip />
- <!-- no translation found for resolver_no_apps_available (7710339903040989654) -->
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
<skip />
- <!-- no translation found for resolver_no_apps_available_explanation (4662694431121196560) -->
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
<skip />
- <!-- no translation found for resolver_switch_on_work (8294542702883688533) -->
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
<skip />
- <!-- no translation found for permlab_accessCallAudio (1682957511874097664) -->
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
<skip />
- <!-- no translation found for permdesc_accessCallAudio (8448360894684277823) -->
+ <string name="resolver_no_apps_available" msgid="7710339903040989654">"ஆப்ஸ் இல்லை"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
<skip />
+ <string name="permlab_accessCallAudio" msgid="1682957511874097664">"அழைப்புகளின்போது ரெக்கார்டு செய்தல் அல்லது ஆடியோவைப் பிளே செய்தல்"</string>
+ <string name="permdesc_accessCallAudio" msgid="8448360894684277823">"இயல்பான டயலர் ஆப்ஸாக இதை அமைக்கும்போது, அழைப்புகளை ரெக்கார்டு செய்ய அல்லது ஆடியோவைப் பிளே செய்ய இதை அனுமதிக்கும்."</string>
</resources>
diff --git a/core/res/res/values-te/strings.xml b/core/res/res/values-te/strings.xml
index f6cc17e..130efbd 100644
--- a/core/res/res/values-te/strings.xml
+++ b/core/res/res/values-te/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">బగ్ నివేదిక కోసం <xliff:g id="NUMBER_1">%d</xliff:g> సెకన్లలో స్క్రీన్షాట్ తీయబోతోంది.</item>
<item quantity="one">బగ్ నివేదిక కోసం <xliff:g id="NUMBER_0">%d</xliff:g> సెకనులో స్క్రీన్షాట్ తీయబోతోంది.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"బగ్ నివేదికతో ఉన్న స్క్రీన్షాట్ తీయబడింది"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"బగ్ నివేదికతో ఉన్న స్క్రీన్షాట్ను తీయడం విఫలమైంది"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"నిశ్శబ్ద మోడ్"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ధ్వని ఆఫ్లో ఉంది"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"ధ్వని ఆన్లో ఉంది"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"మరో యాప్లో ప్రారంభించిన కాల్ని కొనసాగించడానికి యాప్ని అనుమతిస్తుంది."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"ఫోన్ నంబర్లను చదువు"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"పరికరం యొక్క ఫోన్ నంబర్లను యాక్సెస్ చేయడానికి యాప్ను అనుమతిస్తుంది."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"కార్ స్క్రీన్ను ఆన్ చేసి ఉంచండి"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"టాబ్లెట్ను నిద్రావస్థకు వెళ్లనీయకుండా నిరోధించడం"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"స్లీప్ మోడ్కి వెళ్లకుండా మీ Android TV పరికరాన్ని నివారించండి"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ఫోన్ను స్లీప్ మోడ్లోకి వెళ్లనీయకుండా నిరోధించగలగడం"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"కార్ స్క్రీన్ ఆన్ చేసి ఉంచడానికి ఈ యాప్ను అనుమతిస్తుంది."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"నిద్రావస్థకి వెళ్లకుండా టాబ్లెట్ను నిరోధించడానికి యాప్ను అనుమతిస్తుంది."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"మీ Android TV పరికరం స్లీప్ మోడ్లోకి వెళ్లకుండా నివారించడానికి యాప్ని అనుమతిస్తుంది."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"నిద్రావస్థకి వెళ్లకుండా ఫోన్ను నిరోధించడానికి యాప్ను అనుమతిస్తుంది."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"వాల్యూమ్ను సిఫార్సు చేయబడిన స్థాయి కంటే ఎక్కువగా పెంచాలా?\n\nసుదీర్ఘ వ్యవధుల పాటు అధిక వాల్యూమ్లో వినడం వలన మీ వినికిడి శక్తి దెబ్బ తినవచ్చు."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"యాక్సెస్ సామర్థ్యం షార్ట్కట్ను ఉపయోగించాలా?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"షార్ట్కట్ ఆన్ చేసి ఉన్నప్పుడు, రెండు వాల్యూమ్ బటన్లను 3 సెకన్ల పాటు నొక్కి ఉంచితే యాక్సెస్ సౌలభ్య ఫీచర్ ప్రారంభం అవుతుంది."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"షార్ట్కట్లను ఎడిట్ చేయి"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"రద్దు చేయి"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"సత్వరమార్గాన్ని ఆఫ్ చేయి"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> పరిమితం చేయబడిన బకెట్లో ఉంచబడింది"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"వ్యక్తిగతం"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"కార్యాలయం"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"వర్క్ యాప్లతో షేర్ చేయడం సాధ్యపడదు"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"వ్యక్తిగత యాప్లతో షేర్ చేయడం సాధ్యపడదు"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"వ్యక్తిగత, వర్క్ యాప్ల మధ్య షేర్ చేయడాన్ని మీ IT అడ్మిన్ బ్లాక్ చేశారు"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"వర్క్ యాప్లను ఆన్ చేయండి"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"వర్క్ యాప్లు & కాంటాక్ట్లను యాక్సెస్ చేయడానికి వర్క్ యాప్లను ఆన్ చేయండి"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"యాప్లు ఏవీ అందుబాటులో లేవు"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"మేము యాప్లు వేటినీ కనుగొనలేకపోయాము"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"కార్యాలయ ప్రొఫైల్ను ఆన్ చేయి"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"టెలిఫోనీ కాల్స్లో రికార్డ్ చేయండి లేదా ఆడియో ప్లే చేయండి"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"డిఫాల్ట్ డయలర్ యాప్గా కేటాయించినప్పుడు, టెలిఫోనీ కాల్స్లో రికార్డ్ చేయడానికి లేదా ఆడియో ప్లే చేయడానికి ఈ యాప్ను అనుమతిస్తుంది."</string>
</resources>
diff --git a/core/res/res/values-th/strings.xml b/core/res/res/values-th/strings.xml
index 90831d7..3ab4170 100644
--- a/core/res/res/values-th/strings.xml
+++ b/core/res/res/values-th/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">จะจับภาพหน้าจอสำหรับรายงานข้อบกพร่องใน <xliff:g id="NUMBER_1">%d</xliff:g> วินาที</item>
<item quantity="one">จะจับภาพหน้าจอสำหรับรายงานข้อบกพร่องใน <xliff:g id="NUMBER_0">%d</xliff:g> วินาที</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"ถ่ายภาพหน้าจอด้วยรายงานข้อบกพร่องแล้ว"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"ถ่ายภาพหน้าจอด้วยรายงานข้อบกพร่องไม่สำเร็จ"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"โหมดปิดเสียง"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"ปิดเสียงไว้"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"เปิดเสียงแล้ว"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"อนุญาตให้แอปต่อสายที่เริ่มจากแอปอื่น"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"อ่านหมายเลขโทรศัพท์"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"อนุญาตให้แอปเข้าถึงหมายเลขโทรศัพท์ของอุปกรณ์นี้"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"เปิดหน้าจอในรถไว้"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ป้องกันไม่ให้แท็บเล็ตเข้าสู่โหมดสลีป"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ป้องกันไม่ให้อุปกรณ์ Android TV เข้าสู่โหมดสลีป"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ป้องกันไม่ให้โทรศัพท์เข้าโหมดสลีป"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"อนุญาตให้แอปเปิดหน้าจอในรถไว้"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"อนุญาตให้แอปพลิเคชันป้องกันไม่ให้แท็บเล็ตเข้าสู่โหมดสลีป"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"อนุญาตให้แอปป้องกันไม่ให้อุปกรณ์ Android TV เข้าสู่โหมดสลีป"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"อนุญาตให้แอปพลิเคชันป้องกันไม่ให้โทรศัพท์เข้าสู่โหมดสลีป"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"นี่เป็นการเพิ่มระดับเสียงเกินระดับที่แนะนำ\n\nการฟังเสียงดังเป็นเวลานานอาจทำให้การได้ยินของคุณบกพร่องได้"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ใช้ทางลัดการช่วยเหลือพิเศษไหม"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"เมื่อทางลัดเปิดอยู่ การกดปุ่มปรับระดับเสียงทั้ง 2 ปุ่มนาน 3 วินาทีจะเริ่มฟีเจอร์การช่วยเหลือพิเศษ"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"แก้ไขทางลัด"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"ยกเลิก"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"ปิดทางลัด"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"ไม่จัดอยู่ในหมวดหมู่ใดๆ"</string>
<string name="importance_from_user" msgid="2782756722448800447">"คุณตั้งค่าความสำคัญของการแจ้งเตือนเหล่านี้"</string>
<string name="importance_from_person" msgid="4235804979664465383">"ข้อความนี้สำคัญเนื่องจากบุคคลที่เกี่ยวข้อง"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"การแจ้งเตือนที่กำหนดเองของแอป"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"อนุญาตให้ <xliff:g id="APP">%1$s</xliff:g> สร้างผู้ใช้ใหม่ด้วย <xliff:g id="ACCOUNT">%2$s</xliff:g> ไหม (มีผู้ใช้ที่มีบัญชีนี้อยู่แล้ว)"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"อนุญาตให้ <xliff:g id="APP">%1$s</xliff:g> สร้างผู้ใช้ใหม่ด้วย <xliff:g id="ACCOUNT">%2$s</xliff:g> ไหม"</string>
<string name="language_selection_title" msgid="52674936078683285">"เพิ่มภาษา"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"ใส่ <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ในที่เก็บข้อมูลที่ถูกจำกัดแล้ว"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ส่วนตัว"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"งาน"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"แชร์ด้วยแอปงานไม่ได้"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"แชร์ด้วยแอปส่วนตัวไม่ได้"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"ผู้ดูแลระบบไอทีบล็อกการแชร์ระหว่างแอปส่วนตัวและแอปงาน"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"เปิดแอปงาน"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"เปิดแอปงานเพื่อเข้าถึงแอปงานและรายชื่อติดต่อ"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"ไม่มีแอป"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"เราไม่พบแอปใดเลย"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"เปิดโปรไฟล์งาน"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"บันทึกหรือเปิดเสียงในสายโทรศัพท์"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"อนุญาตให้แอปนี้ (เมื่อกำหนดให้เป็นแอปโทรออกเริ่มต้น) บันทึกหรือเปิดเสียงในสายโทรศัพท์ได้"</string>
</resources>
diff --git a/core/res/res/values-tl/strings.xml b/core/res/res/values-tl/strings.xml
index d65c214..2502137 100644
--- a/core/res/res/values-tl/strings.xml
+++ b/core/res/res/values-tl/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Kukuha ng screenshot para sa ulat ng bug sa loob ng <xliff:g id="NUMBER_1">%d</xliff:g> segundo.</item>
<item quantity="other">Kukuha ng screenshot para sa ulat ng bug sa loob ng <xliff:g id="NUMBER_1">%d</xliff:g> na segundo.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Nakakuha ng screenshot kasama ng ulat ng bug"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Hindi nakakuha ng screenshot kasama ng ulat ng bug"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Silent mode"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Naka-OFF ang tunog"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Naka-ON ang sound"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Pinapayagan ang app na ipagpatuloy ang isang tawag na sinimulan sa ibang app."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"basahin ang mga numero ng telepono"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Pinapayagan ang app na i-access ang mga numero ng telepono ng device."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"panatilihing naka-on ang screen ng sasakyan"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"pigilan ang tablet mula sa pag-sleep"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"pigilang mag-sleep ang iyong Android TV device"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"pigilan ang telepono mula sa paghinto"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Pinapayagan ang app na panatilihing naka-on ang screen ng sasakyan."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Pinapayagan ang app na pigilan ang tablet mula sa pag-sleep."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Nagbibigay-daan sa app na pigilang mag-sleep ang iyong Android TV device."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Pinapayagan ang app na pigilan ang telepono mula sa pag-sleep."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Lakasan ang volume nang lagpas sa inirerekomendang antas?\n\nMaaaring mapinsala ng pakikinig sa malakas na volume sa loob ng mahahabang panahon ang iyong pandinig."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Gagamitin ang Shortcut sa Pagiging Accessible?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kapag naka-on ang shortcut, magsisimula ang isang feature ng pagiging naa-access kapag pinindot ang parehong button ng volume."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"I-edit ang mga shortcut"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Kanselahin"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"I-off ang Shortcut"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Di-nakategorya"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ikaw ang magtatakda sa kahalagahan ng mga notification na ito."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Mahalaga ito dahil sa mga taong kasangkot."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Custom na notification ng app"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Payagan ang <xliff:g id="APP">%1$s</xliff:g> na gumawa ng bagong User sa <xliff:g id="ACCOUNT">%2$s</xliff:g> (mayroon nang User sa account na ito) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Payagan ang <xliff:g id="APP">%1$s</xliff:g> na gumawa ng bagong User sa <xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Magdagdag ng wika"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Inilagay ang <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> sa PINAGHIHIGPITANG bucket"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Personal"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Trabaho"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Hindi puwedeng magbahagi sa mga app para sa trabaho"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Hindi puwedeng magbahagi sa mga personal na app"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Na-block ng iyong IT admin ang pagbabahagi sa pagitan ng mga personal na app at app para sa trabaho"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"I-on ang mga app para sa trabaho"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"I-on ang mga app para sa trabaho para ma-access ang mga app at contact para sa trabaho"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Walang available na app"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Wala kaming makitang anumang app"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"I-on ang pantrabahong profile"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Mag-record o mag-play ng audio sa mga tawag sa telephony"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Papayagan ang app na ito na mag-record o mag-play ng audio sa mga tawag sa telephony kapag naitalaga bilang default na dialer application."</string>
</resources>
diff --git a/core/res/res/values-tr/strings.xml b/core/res/res/values-tr/strings.xml
index 718df3d..245b4a1 100644
--- a/core/res/res/values-tr/strings.xml
+++ b/core/res/res/values-tr/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other"><xliff:g id="NUMBER_1">%d</xliff:g> saniye içinde hata raporu ekran görüntüsü alınıyor.</item>
<item quantity="one">Hata raporu ekran görüntüsü <xliff:g id="NUMBER_0">%d</xliff:g> saniye içinde alınacak.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Hata raporunun ekran görüntüsü alındı"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Hata raporunun ekran görüntüsü alınamadı"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Sessiz mod"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Ses KAPALI"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Ses AÇIK"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Uygulamanın, başka bir uygulamada başlatılan çağrıya devam etmesine izin verir."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"telefon numaralarını oku"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Uygulamaya, cihazınızın telefon numaralarına erişme izni verir."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"arabanın ekranını açık tutma"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"tabletin uykuya geçmesini önle"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV cihazınızın uyku moduna geçmesini önleme"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"telefonun uykuya geçmesini önleme"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Uygulamaya, arabanın ekranını açık tutmaya izin verir."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Uygulamaya, tabletin uykuya geçmesini önleme izni verir."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Uygulamaya, Android TV cihazınızın uyku moduna geçmesini önleme izni verir."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Uygulamaya, telefonun uykuya geçmesini önleme izni verir."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Ses seviyesi önerilen düzeyin üzerine yükseltilsin mi?\n\nUzun süre yüksek ses seviyesinde dinlemek işitme duyunuza zarar verebilir."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Erişilebilirlik Kısayolu Kullanılsın mı?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Kısayol açıkken ses düğmelerinin ikisini birden 3 saniyeliğine basılı tutmanız bir erişilebilirlik özelliğini başlatır."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Kısayolları düzenle"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"İptal"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Kısayolu Kapat"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Kategorize edilmemiş"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Bu bildirimlerin önem derecesini ayarladınız."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Bu, dahil olan kişiler nedeniyle önemlidir."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Özel uygulama bildirimi"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> uygulamasının <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabına sahip yeni bir Kullanıcı eklemesine izin verilsin mi (bu hesaba sahip bir kullanıcı zaten var)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> uygulamasının <xliff:g id="ACCOUNT">%2$s</xliff:g> hesabına sahip yeni bir Kullanıcı eklemesine izin verilsin mi?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Dil ekleyin"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> KISITLANMIŞ gruba yerleştirildi"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Kişisel"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"İş"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"İş uygulamalarıyla paylaşılamıyor"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Kişisel uygulamalarla paylaşılamıyor"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"BT yöneticiniz kişisel uygulamalar ile iş uygulamaları arasında paylaşımı engelledi"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"İş uygulamalarını açın"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"İş uygulamalarına ve kişilere erişmek için iş uygulamalarını açın"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Kullanılabilir uygulama yok"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Herhangi bir uygulama bulamadık"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"İş profilini aç"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Telefon aramalarında sesi kaydet veya çal"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Varsayılan çevirici uygulaması olarak atandığında bu uygulamanın telefon aramalarında sesi kaydetmesine veya çalmasına izin verir."</string>
</resources>
diff --git a/core/res/res/values-uk/strings.xml b/core/res/res/values-uk/strings.xml
index e36c900..b1a954a 100644
--- a/core/res/res/values-uk/strings.xml
+++ b/core/res/res/values-uk/strings.xml
@@ -255,10 +255,8 @@
<item quantity="many">Знімок екрана для звіту про помилки буде зроблено через <xliff:g id="NUMBER_1">%d</xliff:g> секунд.</item>
<item quantity="other">Знімок екрана для звіту про помилки буде зроблено через <xliff:g id="NUMBER_1">%d</xliff:g> секунди.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Знімок екрана зі звітом про помилку зроблено"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Не вдалося зробити знімок екрана зі звітом про помилку"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Беззвуч. режим"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Звук ВИМК."</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Звук УВІМК."</string>
@@ -460,9 +458,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Додаток може продовжувати виклик, початий в іншому додатку."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"переглядати номери телефону"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Надає додаткам доступ до номерів телефону на пристрої."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"залишати екран автомобіля ввімкненим"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"не доп.перехід пристр.в реж.сну"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"не допускати перехід пристрою Android TV в режим сну"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"Вимкнення режиму сну"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Дозволяє додатку залишати екран автомобіля ввімкненим."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Дозволяє програмі не допускати перехід планшетного ПК у режим сну."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Дозволяє додатку не допускати перехід пристрою Android TV в режим сну."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Дозволяє програмі не допускати перехід телефону в режим сну."</string>
@@ -1675,6 +1675,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Збільшити гучність понад рекомендований рівень?\n\nЯкщо слухати надто гучну музику тривалий час, можна пошкодити слух."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Використовувати швидке ввімкнення?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Якщо цей засіб увімкнено, ви можете активувати спеціальні можливості, утримуючи обидві кнопки гучності протягом трьох секунд."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Редагувати засоби"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Скасувати"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Вимкнути ярлик"</string>
@@ -1917,8 +1923,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Без категорії"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Ви вказуєте пріоритет цих сповіщень."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Важливе з огляду на учасників."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Користувацьке сповіщення додатка"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Дозволити додатку <xliff:g id="APP">%1$s</xliff:g> створити нового користувача з обліковим записом <xliff:g id="ACCOUNT">%2$s</xliff:g> (користувач із таким обліковим записом уже існує)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Дозволити додатку <xliff:g id="APP">%1$s</xliff:g> створити нового користувача з обліковим записом <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Додати мову"</string>
@@ -2096,14 +2101,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Пакет \"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>\" додано в сегмент з обмеженнями"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Особисте"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Робоче"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Не можна надсилати дані робочим додаткам"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Не можна надсилати дані особистим додаткам"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Ваш ІТ-адміністратор заблокував обмін даними між особистими й робочими додатками"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Увімкніть робочі додатки"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Щоб отримати доступ до робочих додатків і контактів, увімкніть ці додатки"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Немає доступних додатків"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Немає додатків"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Увімкнути робочий профіль"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Записувати й відтворювати звук під час викликів"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Дозволяє цьому додатку записувати й відтворювати звук під час викликів, коли його вибрано додатком для дзвінків за умовчанням."</string>
</resources>
diff --git a/core/res/res/values-ur/strings.xml b/core/res/res/values-ur/strings.xml
index 10eb4ce..31ff6cf 100644
--- a/core/res/res/values-ur/strings.xml
+++ b/core/res/res/values-ur/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">بگ رپورٹ کیلئے <xliff:g id="NUMBER_1">%d</xliff:g> سیکنڈز میں اسکرین شاٹ لیا جائے گا۔</item>
<item quantity="one">بگ رپورٹ کیلئے <xliff:g id="NUMBER_0">%d</xliff:g> سیکنڈ میں اسکرین شاٹ لیا جائے گا۔</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"بگ رپورٹ کے ساتھ لیا گیا اسکرین شاٹ"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"بگ رپورٹ کے ساتھ اسکرین شاٹ لینے میں ناکام"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"خاموش وضع"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"آواز آف ہے"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"آواز آن ہے"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"ایپ کو دوسری ایپ میں شروع کردہ کال کو جاری رکھنے کی اجازت ملتی ہے۔"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"فون نمبرز پڑھیں"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"ایپ کو آلہ کے فون نمبرز تک رسائی کرنے دیتا ہے۔"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"کار کی اسکرین آن رکھیں"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ٹیبلیٹ کو سلیپ وضع میں جانے سے روکیں"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"اپنے Android TV کو سلیپ وضع میں جانے سے روکیں"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"فون کو سلیپ وضع میں جانے سے روکیں"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"ایپ کو کار کی اسکرین آن رکھنے کی اجازت دیتا ہے۔"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"ایپ کو ٹیبلیٹ کو سلیپ وضع میں جانے سے روکنے کی اجازت دیتا ہے"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"ایپ کو آپ کے Android TV آلہ کو سلیپ وضع میں جانے سے روکنے کی اجازت دیتا ہے۔"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"ایپ کو فون کو سلیپ وضع میں جانے سے روکنے کی اجازت دیتا ہے"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"والیوم کو تجویز کردہ سطح سے زیادہ کریں؟\n\nزیادہ وقت تک اونچی آواز میں سننے سے آپ کی سماعت کو نقصان پہنچ سکتا ہے۔"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"ایکسیسبیلٹی شارٹ کٹ استعمال کریں؟"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"شارٹ کٹ آن ہونے پر، 3 سیکنڈ تک دونوں والیوم بٹنز کو دبانے سے ایک ایکسیسبیلٹی خصوصیت شروع ہو جائے گی۔"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"شارٹ کٹس میں ترمیم کریں"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"منسوخ کریں"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"شارٹ کٹ آف کریں"</string>
@@ -2028,14 +2034,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> کو پابند کردہ بکٹ میں رکھ دیا گیا ہے"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"ذاتی"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"دفتر"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"ورک ایپس کے ساتھ اشتراک نہیں کر سکتے"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"ذاتی ایپس کے ساتھ اشتراک نہیں کر سکتے"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"آپ کے IT منتظم نے ذاتی اور ورک ایپس کے درمیان اشتراک کرنے کو مسدود کر دیا"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"ورک ایپس آن کریں"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"ورک ایپس اور رابطوں تک رسائی حاصل کرنے کے لیے ورک ایپس آن کریں"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"کوئی ایپ دستیاب نہیں"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"ہمیں کوئی ایپ نہیں مل سکی"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"ورک کا سوئچ آن کریں"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"ٹیلیفون کالز میں آڈیو ریکارڈ کریں یا چلائیں"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"اس ایپ کو، جب ڈیفالٹ ڈائلر ایپلیکیشن کے بطور تفویض کیا جاتا ہے، تو ٹیلیفون کالز میں آڈیو ریکارڈ کرنے یا چلانے کی اجازت دیتا ہے۔"</string>
</resources>
diff --git a/core/res/res/values-uz/strings.xml b/core/res/res/values-uz/strings.xml
index 526d88b..7365dfd 100644
--- a/core/res/res/values-uz/strings.xml
+++ b/core/res/res/values-uz/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Xatoliklar hisoboti uchun skrinshot <xliff:g id="NUMBER_1">%d</xliff:g> soniyadan so‘ng olinadi.</item>
<item quantity="one">Xatoliklar hisoboti uchun skrinshot <xliff:g id="NUMBER_0">%d</xliff:g> soniyadan so‘ng olinadi.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Xatoliklar hisoboti bilan skrinshot olindi"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Xatoliklar hisoboti bilan skrinshot olinmadi"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Ovozsiz rejim"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Tovush o‘chirilgan"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"YONIQ"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Ilovaga boshqa ilovada boshlangan chaqiruvni davom ettirish imkon beradi"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"telefon raqamlarini o‘qish"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Ilovaga qurilmaning telefon raqamlaridan foydalanishiga ruxsat beradi."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"avtomobil ekranini yoniq holatda saqlab turish"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"planshetni uyquga ketishiga yo‘l qo‘ymaslik"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"Android TV qurilmasining uyqu rejimiga kirishining oldini olish"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"telefonni uxlashiga yo‘l qo‘ymaslik"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Ilova avtomobil ekranini yoniq holatda saqlaydi."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Ilova planshetning uyqu rejimiga o‘tib qolishining oldini olishi mumkin."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Ilovaga Android TV qurilmangizning uyqu rejimiga oʻtishining oldini olish huquqini beradi."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Ilova telefonning uyqu rejimiga o‘tib qolishining oldini olishi mumkin."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Tovush balandligi tavsiya etilgan darajadan ham yuqori qilinsinmi?\n\nUzoq vaqt davomida baland ovozda tinglash eshitish qobiliyatingizga salbiy ta’sir ko‘rsatishi mumkin."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Tezkor ishga tushirishdan foydalanilsinmi?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Maxsus imkoniyatlar funksiyasidan foydalanish uchun u yoniqligida ikkala tovush tugmasini 3 soniya bosib turing."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Tezkor tugmalarni tahrirlash"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Bekor qilish"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Tezkor ishga tushirishni o‘chirib qo‘yish"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Turkumlanmagan"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Siz ushbu bildirishnomalarning muhimligini belgilagansiz."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Bu odamlar siz uchun muhim."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Maxsus ilova bildirishnomasi"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"<xliff:g id="APP">%1$s</xliff:g> ilovasiga <xliff:g id="ACCOUNT">%2$s</xliff:g> hisobi bilan yangi foydalanuvchi yaratishiga ruxsat berilsinmi (bunday hisobdagi foydalanuvchi allaqachon mavjud) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"<xliff:g id="APP">%1$s</xliff:g> ilovasiga <xliff:g id="ACCOUNT">%2$s</xliff:g> hisobi bilan yangi foydalanuvchi yaratishiga ruxsat berilsinmi ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Til qoʻshish"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> cheklangan turkumga joylandi"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Shaxsiy"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Ish"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ishga oid ilovalarga ulashilmaydi"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Shaxsiy ilovalarga ulashilmaydi"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Shaxsiy va ishga oid ilovalararo axborot ulashish AT administratori tomonidan taqiqlangan"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Ishga oid ilovalarni yoqish"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Ishga oid ilova va kontaktlarni ochish uchun ishga oid ilovalarni yoqing"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Mos ilova topilmadi"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Hech qanday ilova topilmadi"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Ish rejimini yoqish"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Telefondagi suhbatlarni yozib olish va ularni ijro qilish"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Bu ilova chaqiruvlar uchun asosiy ilova sifatida tayinlanganda u telefon chaqiruvlarida suhbatlarni yozib olish va shu audiolarni ijro etish imkonini beradi."</string>
</resources>
diff --git a/core/res/res/values-vi/strings.xml b/core/res/res/values-vi/strings.xml
index 4f67627..bce8e37 100644
--- a/core/res/res/values-vi/strings.xml
+++ b/core/res/res/values-vi/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">Sẽ chụp ảnh màn hình để báo cáo lỗi sau <xliff:g id="NUMBER_1">%d</xliff:g> giây.</item>
<item quantity="one">Sẽ chụp ảnh màn hình để báo cáo lỗi sau <xliff:g id="NUMBER_0">%d</xliff:g> giây.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Đã chụp được ảnh màn hình báo cáo lỗi"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Không chụp được ảnh màn hình báo cáo lỗi"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Chế độ im lặng"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Âm thanh TẮT"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Âm thanh BẬT"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Cho phép ứng dụng tiếp tục cuộc gọi được bắt đầu trong một ứng dụng khác."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"đọc số điện thoại"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Cho phép ứng dụng truy cập số điện thoại của thiết bị."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"duy trì trạng thái bật của màn hình ô tô"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"ngăn máy tính bảng chuyển sang chế độ ngủ"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"ngăn thiết bị Android TV chuyển sang chế độ ngủ"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"ngăn điện thoại chuyển sang chế độ ngủ"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Cho phép ứng dụng này duy trì trạng thái bật của màn hình ô tô."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Cho phép ứng dụng ngăn máy tính bảng chuyển sang chế độ ngủ."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Cho phép ứng dụng ngăn thiết bị Android TV chuyển sang chế độ ngủ."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Cho phép ứng dụng ngăn điện thoại chuyển sang chế độ ngủ."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Bạn tăng âm lượng lên quá mức khuyên dùng?\n\nViệc nghe ở mức âm lượng cao trong thời gian dài có thể gây tổn thương thính giác của bạn."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Sử dụng phím tắt Hỗ trợ tiếp cận?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Khi phím tắt này đang bật, thao tác nhấn cả hai nút âm lượng trong 3 giây sẽ mở tính năng hỗ trợ tiếp cận."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Chỉnh sửa phím tắt"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Hủy"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Tắt phím tắt"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Chưa được phân loại"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Bạn đặt tầm quan trọng của các thông báo này."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Thông báo này quan trọng vì những người có liên quan."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Thông báo tùy chỉnh cho ứng dụng"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Cho phép <xliff:g id="APP">%1$s</xliff:g> tạo người dùng mới bằng <xliff:g id="ACCOUNT">%2$s</xliff:g> (đã tồn tại người dùng có tài khoản này)?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Cho phép <xliff:g id="APP">%1$s</xliff:g> tạo người dùng mới bằng <xliff:g id="ACCOUNT">%2$s</xliff:g>?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Thêm ngôn ngữ"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"Đã đưa <xliff:g id="PACKAGE_NAME">%1$s</xliff:g> vào bộ chứa BỊ HẠN CHẾ"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Cá nhân"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Cơ quan"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Không thể chia sẻ với các ứng dụng công việc"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Không thể chia sẻ với các ứng dụng cá nhân"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Quản trị viên CNTT của bạn đã chặn hoạt động chia sẻ giữa các ứng dụng cá nhân và công việc"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Bật các ứng dụng công việc"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Bật ứng dụng công việc để truy cập vào phần những người liên hệ và ứng dụng công việc"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Không có ứng dụng nào"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Chúng tôi không tìm thấy bất kỳ ứng dụng nào"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Bật hồ sơ công việc"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Ghi âm hoặc phát âm thanh trong cuộc gọi điện thoại"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Cho phép ứng dụng này ghi âm hoặc phát âm thanh trong cuộc gọi điện thoại khi được chỉ định làm ứng dụng trình quay số mặc định."</string>
</resources>
diff --git a/core/res/res/values-zh-rCN/strings.xml b/core/res/res/values-zh-rCN/strings.xml
index 5ac1f0a..b24a89e 100644
--- a/core/res/res/values-zh-rCN/strings.xml
+++ b/core/res/res/values-zh-rCN/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">系统将在 <xliff:g id="NUMBER_1">%d</xliff:g> 秒后对错误报告进行截屏。</item>
<item quantity="one">系统将在 <xliff:g id="NUMBER_0">%d</xliff:g> 秒后对错误报告进行截屏。</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"已截取错误报告的屏幕截图"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"无法截取错误报告的屏幕截图"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"静音模式"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"声音已关闭"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"声音已开启"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"允许该应用继续进行在其他应用中发起的通话。"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"读取电话号码"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"允许该应用访问设备上的电话号码。"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"使车载显示屏保持开启状态"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"阻止平板电脑进入休眠状态"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"阻止 Android TV 设备进入休眠状态"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"防止手机休眠"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"允许该应用使车载显示屏保持开启状态。"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"允许应用阻止平板电脑进入休眠状态。"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"允许应用阻止 Android TV 设备进入休眠状态。"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"允许应用阻止手机进入休眠状态。"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"要将音量调高到建议的音量以上吗?\n\n长时间保持高音量可能会损伤听力。"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"要使用无障碍快捷方式吗?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"启用这项快捷方式后,同时按下两个音量按钮 3 秒钟即可启动无障碍功能。"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"修改快捷方式"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"取消"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"关闭快捷方式"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"未分类"</string>
<string name="importance_from_user" msgid="2782756722448800447">"这些通知的重要程度由您来设置。"</string>
<string name="importance_from_person" msgid="4235804979664465383">"这条通知涉及特定的人,因此被归为重要通知。"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"自定义应用通知"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g>(目前已有用户使用此帐号)创建新用户吗?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"允许<xliff:g id="APP">%1$s</xliff:g>使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 创建新用户吗?"</string>
<string name="language_selection_title" msgid="52674936078683285">"添加语言"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> 已被放入受限存储分区"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"个人"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"工作"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"无法与工作应用共享数据"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"无法与个人应用共享数据"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"您的 IT 管理员已禁止在个人应用和工作应用之间共享数据"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"打开工作应用"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"打开工作应用以访问工作应用和联系人"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"没有可用的应用"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"系统找不到任何应用"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"打开工作资料"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"录制或播放电话通话音频"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"允许此应用在被指定为默认拨号器应用时录制或播放电话通话音频。"</string>
</resources>
diff --git a/core/res/res/values-zh-rHK/strings.xml b/core/res/res/values-zh-rHK/strings.xml
index 44de6bf..b0331bf 100644
--- a/core/res/res/values-zh-rHK/strings.xml
+++ b/core/res/res/values-zh-rHK/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">系統將在 <xliff:g id="NUMBER_1">%d</xliff:g> 秒後擷取錯誤報告的螢幕畫面。</item>
<item quantity="one">系統將在 <xliff:g id="NUMBER_0">%d</xliff:g> 秒後擷取錯誤報告的螢幕畫面。</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"已為錯誤報告擷取螢幕截圖"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"無法為錯誤報告擷取螢幕截圖"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"靜音模式"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"關閉音效"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"音效已開啟"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"允許應用程式繼續進行在其他應用程式中開始的通話。"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"讀取電話號碼"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"允許應用程式存取裝置上的電話號碼。"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"保持汽車螢幕開啟"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"防止平板電腦進入休眠狀態"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"防止 Android TV 裝置進入休眠狀態"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"防止手機進入休眠狀態"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"允許應用程式保持汽車螢幕開啟。"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"允許應用程式防止平板電腦進入休眠狀態。"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"允許應用程式防止 Android TV 裝置進入休眠狀態。"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"允許應用程式防止手機進入休眠狀態。"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"要調高音量 (比建議的音量更大聲) 嗎?\n\n長時間聆聽高分貝音量可能會導致您的聽力受損。"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"要使用無障礙功能快速鍵嗎?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"啟用快速鍵後,同時按住音量按鈕 3 秒便可啟用無障礙功能。"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"編輯捷徑"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"取消"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"關閉快速鍵"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"未分類"</string>
<string name="importance_from_user" msgid="2782756722448800447">"您可以設定這些通知的重要性。"</string>
<string name="importance_from_person" msgid="4235804979664465383">"列為重要的原因:涉及的人。"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"自訂應用程式通知"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"要允許 <xliff:g id="APP">%1$s</xliff:g> 使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者 (此帳戶目前已有此使用者) 嗎?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"要允許 <xliff:g id="APP">%1$s</xliff:g> 使用 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎?"</string>
<string name="language_selection_title" msgid="52674936078683285">"新增語言"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> 已納入受限制的儲存區"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"個人"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"公司"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"無法與工作應用程式分享"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"無法與個人應用程式分享"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"您的 IT 管理員已封鎖個人和工作應用程式之間的分享功能"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"開啟工作應用程式"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"開啟工作應用程式以存取工作應用程式和聯絡人"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"沒有可用的應用程式"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"系統找不到任何應用程式"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"開啟工作設定檔"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"在電話通話中錄音或播放音訊"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"如將此應用程式指定為預設撥號器應用程式,則允許應用程式在電話通話中錄音或播放音訊。"</string>
</resources>
diff --git a/core/res/res/values-zh-rTW/strings.xml b/core/res/res/values-zh-rTW/strings.xml
index 9e1b0d4..fe5fe1a 100644
--- a/core/res/res/values-zh-rTW/strings.xml
+++ b/core/res/res/values-zh-rTW/strings.xml
@@ -249,10 +249,8 @@
<item quantity="other">系統將在 <xliff:g id="NUMBER_1">%d</xliff:g> 秒後擷取錯誤報告的螢幕畫面。</item>
<item quantity="one">系統將在 <xliff:g id="NUMBER_0">%d</xliff:g> 秒後擷取錯誤報告的螢幕畫面。</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"已拍攝錯誤報告的螢幕截圖"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"無法拍攝錯誤報告的螢幕截圖"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"靜音模式"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"音效已關閉"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"音效已開啟"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"允許應用程式繼續進行在其他應用程式中發起的通話。"</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"讀取電話號碼"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"允許應用程式存取裝置上的電話號碼資料。"</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"讓車輛螢幕保持開啟"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"防止平板電腦進入休眠狀態"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"防止 Android TV 裝置進入休眠狀態"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"防止手機進入待命狀態"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"允許應用程式讓車輛螢幕保持開啟。"</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"允許應用程式防止平板電腦進入休眠狀態。"</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"允許應用程式防止 Android TV 裝置進入休眠狀態。"</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"允許應用程式防止手機進入休眠狀態。"</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"要調高音量,比建議的音量更大聲嗎?\n\n長時間聆聽高分貝音量可能會使你的聽力受損。"</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"要使用無障礙捷徑嗎?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"啟用捷徑功能,只要同時按下兩個音量按鈕 3 秒,就能啟動無障礙功能。"</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"編輯捷徑"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"取消"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"停用捷徑"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"未分類"</string>
<string name="importance_from_user" msgid="2782756722448800447">"這些通知的重要性由你決定。"</string>
<string name="importance_from_person" msgid="4235804979664465383">"這則通知涉及特定人士,因此被歸為重要通知。"</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"自訂應用程式通知"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"要允許「<xliff:g id="APP">%1$s</xliff:g>」替 <xliff:g id="ACCOUNT">%2$s</xliff:g> (這個帳戶目前已有使用者) 建立新使用者嗎?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"要允許「<xliff:g id="APP">%1$s</xliff:g>」替 <xliff:g id="ACCOUNT">%2$s</xliff:g> 建立新使用者嗎?"</string>
<string name="language_selection_title" msgid="52674936078683285">"新增語言"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"已將「<xliff:g id="PACKAGE_NAME">%1$s</xliff:g>」移入受限制的值區"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"個人"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"工作"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"無法與工作應用程式分享"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"無法與個人應用程式分享"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"你的 IT 管理員已封鎖個人和工作應用程式之間的分享功能"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"開啟工作應用程式"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"開啟工作應用程式即可存取工作應用程式和聯絡人"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"沒有可用的應用程式"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"系統找不到任何應用程式"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"啟用工作資料夾"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"在通話期間錄製或播放音訊"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"將這個應用程式指派為預設撥號應用程式時,允許應用程式在通話期間錄製或播放音訊。"</string>
</resources>
diff --git a/core/res/res/values-zu/strings.xml b/core/res/res/values-zu/strings.xml
index f29ac2f..148272d 100644
--- a/core/res/res/values-zu/strings.xml
+++ b/core/res/res/values-zu/strings.xml
@@ -249,10 +249,8 @@
<item quantity="one">Ithathela umbiko wesiphazamisi isithombe-skrini kumasekhondi angu-<xliff:g id="NUMBER_1">%d</xliff:g>.</item>
<item quantity="other">Ithathela umbiko wesiphazamisi isithombe-skrini kumasekhondi angu-<xliff:g id="NUMBER_1">%d</xliff:g>.</item>
</plurals>
- <!-- no translation found for bugreport_screenshot_success_toast (7986095104151473745) -->
- <skip />
- <!-- no translation found for bugreport_screenshot_failure_toast (6736320861311294294) -->
- <skip />
+ <string name="bugreport_screenshot_success_toast" msgid="7986095104151473745">"Isithombe-skrini sithathwe nombiko wesiphazamisi"</string>
+ <string name="bugreport_screenshot_failure_toast" msgid="6736320861311294294">"Yehlulekile ukuthatha isithombe-skrini nombiko wesiphazamisi"</string>
<string name="global_action_toggle_silent_mode" msgid="8464352592860372188">"Imodi ethulile"</string>
<string name="global_action_silent_mode_on_status" msgid="2371892537738632013">"Umsindo UVALIWE"</string>
<string name="global_action_silent_mode_off_status" msgid="6608006545950920042">"Umsindo UVULIWE"</string>
@@ -454,9 +452,11 @@
<string name="permdesc_acceptHandovers" msgid="7129026180128626870">"Ivumela uhlelo lokusebenza ukuze luqhube ikholi eqalwe kolunye uhlelo lokusebenza."</string>
<string name="permlab_readPhoneNumbers" msgid="5668704794723365628">"funda izinombolo zefoni"</string>
<string name="permdesc_readPhoneNumbers" msgid="7368652482818338871">"Ivumela uhlelo lokusebenza ukufinyelela izinombolo zefoni zedivayisi."</string>
+ <string name="permlab_wakeLock" product="automotive" msgid="1904736682319375676">"gcina isikrini semoto sivuliwe"</string>
<string name="permlab_wakeLock" product="tablet" msgid="1527660973931694000">"gwema ithebhulethi ukuba ingalali"</string>
<string name="permlab_wakeLock" product="tv" msgid="2856941418123343518">"gwema idivayisi yakho ye-Android TV ukuthi ingalali"</string>
<string name="permlab_wakeLock" product="default" msgid="569409726861695115">"gwema ifoni ukuba ingalali"</string>
+ <string name="permdesc_wakeLock" product="automotive" msgid="5995045369683254571">"Ivumela uhlelo lokusebenza ukuthi lugcine isikrini semoto sivuliwe."</string>
<string name="permdesc_wakeLock" product="tablet" msgid="2441742939101526277">"Ivumela uhlelo lokusebenza ukuthi linqande ithebulethi yakho ukuthi ilale."</string>
<string name="permdesc_wakeLock" product="tv" msgid="2329298966735118796">"Ivumela uhlelo lokusebenza ukugwema idivayisi yakho ye-Android TV ukuthi ingalali."</string>
<string name="permdesc_wakeLock" product="default" msgid="3689523792074007163">"Ivumela uhlelo lokusebenza ukuthi inqande ucingo ukuthi lulale."</string>
@@ -1631,6 +1631,12 @@
<string name="safe_media_volume_warning" product="default" msgid="3751676824423049994">"Khuphukisa ivolumu ngaphezu kweleveli enconyiwe?\n\nUkulalela ngevolumu ephezulu izikhathi ezide kungahle kulimaze ukuzwa kwakho."</string>
<string name="accessibility_shortcut_warning_dialog_title" msgid="4017995837692622933">"Sebenzisa isinqamuleli sokufinyelela?"</string>
<string name="accessibility_shortcut_toogle_warning" msgid="4161716521310929544">"Uma isinqamuleli sivuliwe, ukucindezela zombili izinkinobho zevolumu amasekhondi angu-3 kuzoqalisa isici sokufinyelela."</string>
+ <!-- no translation found for accessibility_select_shortcut_menu_title (7310194076629867377) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_button_title (6096484087245145325) -->
+ <skip />
+ <!-- no translation found for accessibility_edit_shortcut_menu_volume_title (4849108668454490699) -->
+ <skip />
<string name="edit_accessibility_shortcut_menu_button" msgid="8885752738733772935">"Hlela izinqamuleli"</string>
<string name="cancel_accessibility_shortcut_menu_button" msgid="1817413122335452474">"Khansela"</string>
<string name="disable_accessibility_shortcut" msgid="5806091378745232383">"Vala isinqamuleli"</string>
@@ -1853,8 +1859,7 @@
<string name="default_notification_channel_label" msgid="3697928973567217330">"Akufakwanga esigabeni"</string>
<string name="importance_from_user" msgid="2782756722448800447">"Usethe ukubaluleka kwalezi zaziso."</string>
<string name="importance_from_person" msgid="4235804979664465383">"Lokhu kubalulekile ngenxa yabantu ababandakanyekayo."</string>
- <!-- no translation found for notification_history_title_placeholder (7748630986182249599) -->
- <skip />
+ <string name="notification_history_title_placeholder" msgid="7748630986182249599">"Isaziso sohlelo lokusebenza olungokwezifiso"</string>
<string name="user_creation_account_exists" msgid="2239146360099708035">"Vumela i-<xliff:g id="APP">%1$s</xliff:g> ukuthi idale umsebenzisi omusha nge-<xliff:g id="ACCOUNT">%2$s</xliff:g> (Umsebenzisi onale akhawunti usevele ukhona) ?"</string>
<string name="user_creation_adding" msgid="7305185499667958364">"Vumela i-<xliff:g id="APP">%1$s</xliff:g> ukuthi idale umsebenzisi omusha nge-<xliff:g id="ACCOUNT">%2$s</xliff:g> ?"</string>
<string name="language_selection_title" msgid="52674936078683285">"Engeza ulwimi"</string>
@@ -2028,14 +2033,29 @@
<string name="as_app_forced_to_restricted_bucket" msgid="8233871289353898964">"I-<xliff:g id="PACKAGE_NAME">%1$s</xliff:g> ifakwe kubhakede LOKUKHAWULELWE"</string>
<string name="resolver_personal_tab" msgid="2051260504014442073">"Okomuntu siqu"</string>
<string name="resolver_work_tab" msgid="2690019516263167035">"Umsebenzi"</string>
+ <!-- no translation found for resolver_personal_tab_accessibility (5739524949153091224) -->
+ <skip />
+ <!-- no translation found for resolver_work_tab_accessibility (4753168230363802734) -->
+ <skip />
<string name="resolver_cant_share_with_work_apps" msgid="7539495559434146897">"Ayikwazi ukwabelana ngezinhlelo zokusebenza zomsebenzi"</string>
<string name="resolver_cant_share_with_personal_apps" msgid="8020581735267157241">"Ayikwazi ukwabelana ngezinhlelo zokusebenza zomuntu siqu"</string>
- <string name="resolver_cant_share_cross_profile_explanation" msgid="3536237105241882679">"Umphathi wakho we-IT uvimbe ukwabelana phakathi kwezinhlelo zokusebenza zomuntu siqu nezomsebenzi"</string>
- <string name="resolver_turn_on_work_apps" msgid="8987359079870455469">"Vula izinhlelo zokusebenza zomsebenzi"</string>
- <string name="resolver_turn_on_work_apps_explanation" msgid="6322467455509618928">"Vula izinhlelo zokusebenza zomsebenzi ukuze ufinyelele kuzinhlelo zokusebenza zomsebenzi noxhumana nabo"</string>
+ <!-- no translation found for resolver_cant_share_cross_profile_explanation (5556640604460901386) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps (375634344111233790) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_work_apps_explanation (3958762224516867388) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps (1953215925406474177) -->
+ <skip />
+ <!-- no translation found for resolver_cant_access_personal_apps_explanation (1725572276741281136) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_share (619263911204978175) -->
+ <skip />
+ <!-- no translation found for resolver_turn_on_work_apps_view (3073389230905543680) -->
+ <skip />
<string name="resolver_no_apps_available" msgid="7710339903040989654">"Azikho izinhlelo zokusebenza ezitholakalayo"</string>
- <string name="resolver_no_apps_available_explanation" msgid="4662694431121196560">"Asikwazanga ukuthola izinhlelo zokusebenza"</string>
- <string name="resolver_switch_on_work" msgid="8294542702883688533">"Shintshela emsebenzini"</string>
+ <!-- no translation found for resolver_switch_on_work (2873009160846966379) -->
+ <skip />
<string name="permlab_accessCallAudio" msgid="1682957511874097664">"Rekhoda noma dlala umsindo kumakholi ocingo"</string>
<string name="permdesc_accessCallAudio" msgid="8448360894684277823">"Ivumela lolu hlelo lokusebenza, uma lunikezwe njengohlelo lokusebenza oluzenzakalelayo lokudayela, ukuze kurekhodwe noma kudlalwe umsindo kumakholi ocingo."</string>
</resources>
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 08dca62..f3ca5ac 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -1541,6 +1541,28 @@
<flag name="microphone" value="0x80" />
</attr>
+ <!-- Enable sampled memory bug detection in this process.
+ When enabled, a very small, random subset of native
+ memory allocations are protected with guard pages, providing an
+ ASan-like error report in case of a memory corruption bug.
+
+ GWP-ASan is a recursive acronym. It stands for “GWP-ASan Will Provide Allocation SANity”.
+ See the <a href="http://llvm.org/docs/GwpAsan.html">LLVM documentation</a>
+ for more information about this feature.
+
+ <p>This tag can be applied to any tag that allows
+ {@link android.R.styleable#AndroidManifestProcess process} tag:
+ {@link android.R.styleable#AndroidManifestApplication application} tag (to supply
+ a default setting for all application components), or with the
+ {@link android.R.styleable#AndroidManifestProvider provider},
+ {@link android.R.styleable#AndroidManifestService service},
+ {@link android.R.styleable#AndroidManifestReceiver receiver},
+ {@link android.R.styleable#AndroidManifestActivity activity} tag.
+ When multiple components run in the same process,
+ the first component to start determines the behavior of the entire process.
+
+ The default value is {@code false}. -->
+ <attr name="enableGwpAsan" format="boolean" />
<!-- The <code>manifest</code> tag is the root of an
<code>AndroidManifest.xml</code> file,
@@ -1552,7 +1574,7 @@
<code>com.google.app.<em>appname</em></code>
<p>Inside of the manifest tag, may appear the following tags
- in any order: {@link #AndroidManifestFeature feature},
+ in any order: {@link #AndroidManifestAttribution attribution},
{@link #AndroidManifestPermission permission},
{@link #AndroidManifestPermissionGroup permission-group},
{@link #AndroidManifestPermissionTree permission-tree},
@@ -1806,31 +1828,51 @@
The default value is {@code true}. -->
<attr name="allowNativeHeapPointerTagging" format="boolean" />
+
+ <attr name="enableGwpAsan" />
+
+ <!-- If {@code true} allow requesting that its permissions don't get automatically
+ revoked when the app is unused for an extended amount of time.
+
+ The default value is {@code false}. -->
+ <attr name="requestDontAutoRevokePermissions" format="boolean" />
+
+ <!-- If {@code true} its permissions shouldn't get automatically
+ revoked when the app is unused for an extended amount of time.
+
+ This implies {@code requestDontAutoRevokePermissions=true}
+
+ The default value is {@code false}. -->
+ <attr name="allowDontAutoRevokePermissions" format="boolean" />
</declare-styleable>
- <!-- The <code>feature</code> tag declares a feature. A feature is a logical part of an app.
- E.g. photo sharing app might include a direct messaging component. To tag certain code as
- belonging to a feature, use a context created via
- {@link android.content.Context#createFeatureContext(String)} for any interaction with the
+ <!-- An attribution is a logical part of an app and is identified by a tag.
+ E.g. a photo sharing app might include a direct messaging component. To tag certain code as
+ belonging to an attribution, use a context created via
+ {@link android.content.Context#createAttributionContext(String)} for any interaction with the
system.
<p>This appears as a child tag of the root {@link #AndroidManifest manifest} tag.
- <p>In case this feature inherits from another feature, this tag can contain one or multiple
- {@link #AndroidManifestFeatureInheritFrom inherit-from} tags. -->
- <declare-styleable name="AndroidManifestFeature" parent="AndroidManifest">
- <!-- Required identifier for a feature. Can be passed to
- {@link android.content.Context#createFeatureContext} to create a context for this feature
- -->
+ <p>In case this attribution inherits from another attribution, this tag can contain one or
+ multiple {@link #AndroidManifestAttributionInheritFrom inherit-from} tags. -->
+ <declare-styleable name="AndroidManifestAttribution" parent="AndroidManifest">
+ <!-- TODO moltmann: Remove -->
<attr name="featureId" format="string" />
- <!-- Required user visible label for a feature. -->
+ <!-- Required identifier for a attribution. Can be passed to
+ {@link android.content.Context#createAttributionContext} to create a context tagged with
+ this attribution
+ -->
+ <attr name="tag" format="string" />
+ <!-- Required user visible label for a attribution. -->
<attr name="label" format="string" />
</declare-styleable>
<!-- Declares previously declared features this feature inherits from. -->
- <declare-styleable name="AndroidManifestFeatureInheritFrom" parent="AndroidManifestFeature">
- <!-- Identifier of the feature this feature inherits from -->
- <attr name="featureId" format="string" />
+ <declare-styleable name="AndroidManifestAttributionInheritFrom"
+ parent="AndroidManifestAttribution">
+ <!-- Identifier of the attribution this attribution inherits from -->
+ <attr name="tag" format="string" />
</declare-styleable>
<!-- The <code>permission</code> tag declares a security permission that can be
@@ -2266,9 +2308,9 @@
a newer platform that supports more screens. -->
<attr name="resizeable" format="boolean" />
<!-- Indicates whether the application can accommodate any screen
- density. Older applications are assumed to not be able to,
- new ones able to. You can explicitly supply your abilities
- here. -->
+ density. This is assumed true if targetSdkVersion is 4 or higher.
+ @deprecated Should always be true by default and not overridden.
+ -->
<attr name="anyDensity" format="boolean" />
</declare-styleable>
@@ -2312,6 +2354,7 @@
<declare-styleable name="AndroidManifestProcess" parent="AndroidManifestProcesses">
<!-- Required name of the process that is allowed -->
<attr name="process" />
+ <attr name="enableGwpAsan" />
</declare-styleable>
<!-- The <code>deny-permission</code> tag specifies that a permission is to be denied
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 0b6e65fe..6060d9a 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2024,7 +2024,10 @@
a keyboard is present. -->
<bool name="config_showMenuShortcutsWhenKeyboardPresent">false</bool>
- <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD -->
+ <!-- Do not translate. Defines the slots is Two Digit Number for dialing normally not USSD.
+
+ Note: This config is deprecated, please use carrier config which is
+ CarrierConfigManager.KEY_MMI_TWO_DIGIT_NUMBER_PATTERN_STRING_ARRAY instead. -->
<string-array name="config_twoDigitNumberPattern" translatable="false">
</string-array>
@@ -4415,4 +4418,11 @@
<!-- Package name of custom session policy provider class used by MediaSessionService. -->
<string name="config_customSessionPolicyProvider"></string>
+
+ <!-- The max scale for the wallpaper when it's zoomed in -->
+ <item name="config_wallpaperMaxScale" format="float" type="dimen">1.15</item>
+
+ <!-- Package name that will receive an explicit manifest broadcast for
+ android.os.action.POWER_SAVE_MODE_CHANGED. -->
+ <string name="config_powerSaveModeChangedListenerPackage" translatable="false"></string>
</resources>
diff --git a/core/res/res/values/dimens.xml b/core/res/res/values/dimens.xml
index 9118617..15ef09c 100644
--- a/core/res/res/values/dimens.xml
+++ b/core/res/res/values/dimens.xml
@@ -682,7 +682,31 @@
<!-- The size of the right icon image when on low ram -->
<dimen name="notification_right_icon_size_low_ram">@dimen/notification_right_icon_size</dimen>
- <dimen name="messaging_avatar_size">52dp</dimen>
+ <dimen name="messaging_avatar_size">@dimen/notification_right_icon_size</dimen>
+ <dimen name="conversation_avatar_size">52dp</dimen>
+ <!-- Start of the content in the conversation template -->
+ <dimen name="conversation_content_start">80dp</dimen>
+ <!-- Size of the expand button when expanded -->
+ <dimen name="conversation_expand_button_expanded_size">80dp</dimen>
+ <!-- Top margin of the expand button for conversations when expanded -->
+ <dimen name="conversation_expand_button_top_margin_expanded">18dp</dimen>
+ <!-- Side margins of the conversation badge in relation to the conversation icon -->
+ <dimen name="conversation_badge_side_margin">36dp</dimen>
+ <!-- size of the notification icon when badged in a conversation -->
+ <dimen name="conversation_icon_size_badged">15dp</dimen>
+ <!-- size of the notification icon when centered in a conversation -->
+ <dimen name="conversation_icon_size_centered">20dp</dimen>
+ <!-- margin on the top when the icon is centered for group conversations -->
+ <dimen name="conversation_icon_margin_top_centered">5dp</dimen>
+
+ <!-- The padding of the conversation header when expanded. This is calculated from the expand button size + notification_content_margin_end -->
+ <dimen name="conversation_header_expanded_padding_end">38dp</dimen>
+
+ <!-- margin at the end of messaging group icons when not conversations -->
+ <dimen name="messaging_layout_margin_end">12dp</dimen>
+
+ <!-- Padding between text and sender when singleline -->
+ <dimen name="messaging_group_singleline_sender_padding_end">4dp</dimen>
<dimen name="messaging_group_sending_progress_size">24dp</dimen>
@@ -776,7 +800,6 @@
<dimen name="resolver_empty_state_height_with_tabs">268dp</dimen>
<dimen name="resolver_max_collapsed_height">192dp</dimen>
<dimen name="resolver_max_collapsed_height_with_tabs">248dp</dimen>
- <dimen name="resolver_tab_divider_bottom_padding">8dp</dimen>
<dimen name="chooser_action_button_icon_size">18dp</dimen>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 39e8197..cf68aff 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -3004,6 +3004,7 @@
<public name="animatedImageDrawable"/>
<public name="htmlDescription"/>
<public name="preferMinimalPostProcessing"/>
+ <!-- @removed -->
<public name="featureId" />
<public name="supportsInlineSuggestions" />
<public name="crossProfile" />
@@ -3013,8 +3014,11 @@
<!-- @hide @SystemApi -->
<public name="minExtensionVersion" />
<public name="allowNativeHeapPointerTagging" />
+ <public name="requestDontAutoRevokePermissions" />
+ <public name="allowDontAutoRevokePermissions" />
<public name="preserveLegacyExternalStorage" />
<public name="mimeGroup" />
+ <public name="enableGwpAsan" />
</public-group>
<public-group type="drawable" first-id="0x010800b5">
@@ -3040,8 +3044,6 @@
<public name="config_defaultCallScreening" />
<!-- @hide @SystemApi @TestApi -->
<public name="config_systemGallery" />
- <!-- @hide @SystemApi -->
- <public name="low_memory" />
</public-group>
<public-group type="bool" first-id="0x01110005">
@@ -3069,12 +3071,6 @@
<public-group type="array" first-id="0x01070006">
<!-- @hide @SystemApi -->
<public name="simColors" />
- <!-- @hide @SystemApi -->
- <public name="config_restrictedPreinstalledCarrierApps" />
- <!-- @hide @SystemApi -->
- <public name="config_sms_enabled_single_shift_tables" />
- <!-- @hide @SystemApi -->
- <public name="config_sms_enabled_locking_shift_tables" />
</public-group>
<public-group type="string" first-id="0x0104002c">
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 2356b17..f101f59 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1166,6 +1166,11 @@
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
<string name="permdesc_systemCamera">This privileged | system app can take pictures and record videos using a system camera at any time. Requires the android.permission.CAMERA permission to be held by the app as well</string>
+ <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
+ <string name="permlab_cameraOpenCloseListener">Allow an application or service to receive callbacks about camera devices being opened or closed.</string>
+ <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR_LIMIT=NONE] -->
+ <string name="permdesc_cameraOpenCloseListener">This signature app can receive callbacks when any camera device is being opened (by what application package) or closed.</string>
+
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_vibrate">control vibration</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
@@ -1212,6 +1217,14 @@
device. This includes information such as call numbers for calls and the state of the
calls.</string>
+ <!-- Title of an application permission. When granted the app is exempt from audio record
+ restrictions.
+ [CHAR LIMIT=NONE]-->
+ <string name="permlab_exemptFromAudioRecordRestrictions">exempt from audio record restrictions</string>
+ <!-- Description of an application permission. When granted the app is exempt from audio record
+ restrictions. [CHAR LIMIT=NONE]-->
+ <string name="permdesc_exemptFromAudioRecordRestrictions">Exempt the app from restrictions to record audio.</string>
+
<!-- Title of an application permission. When granted the user is giving access to a third
party app to continue a call which originated in another app. For example, the user
could be in a voice call over their carrier's mobile network, and a third party video
@@ -3402,8 +3415,6 @@
<!-- A notification is shown when connected network without internet due to private dns validation failed. This is the notification's message. [CHAR LIMIT=NONE] -->
<string name="private_dns_broken_detailed">Private DNS server cannot be accessed</string>
- <!-- A notification is shown after the user logs in to a captive portal network, to indicate that the network should now have internet connectivity. This is the message of notification. [CHAR LIMIT=50] -->
- <string name="captive_portal_logged_in_detailed">Connected</string>
<!-- A notification is shown when the user connects to a network that doesn't have access to some services (e.g. Push notifications may not work). This is the notification's title. [CHAR LIMIT=50] -->
<string name="network_partial_connectivity"><xliff:g id="network_ssid" example="GoogleGuest">%1$s</xliff:g> has limited connectivity</string>
@@ -4403,27 +4414,72 @@
accessibility feature.
</string>
+ <!-- Title for a warning about security implications of enabling an accessibility
+ service. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_enable_service_title">Allow
+ <xliff:g id="service" example="TalkBack">%1$s</xliff:g> to have full control of your
+ device?</string>
+
+ <!-- Warning that the device data will not be encrypted with password or PIN if
+ enabling an accessibility service and there is a secure lock setup. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_enable_service_encryption_warning">If you turn on
+ <xliff:g id="service" example="TalkBack">%1$s</xliff:g>, your device won’t use your screen
+ lock to enhance data encryption.
+ </string>
+
+ <!-- Warning description that explains that it's appropriate for accessibility
+ services to have full control to help users with accessibility needs. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_service_warning_description">Full control is appropriate for apps
+ that help you with accessibility needs, but not for most apps.
+ </string>
+
+ <!-- Title for the screen control in accessibility dialog. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_service_screen_control_title">View and control screen</string>
+
+ <!-- Description for the screen control in accessibility dialog. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_service_screen_control_description">It can read all content on the
+ screen and display content over other apps.
+ </string>
+
+ <!-- Title for the action perform in accessibility dialog. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_service_action_perform_title">View and perform actions</string>
+
+ <!-- Description for the action perform in accessibility dialog. [CHAR LIMIT=NONE] -->
+ <string name="accessibility_service_action_perform_description">It can track your interactions
+ with an app or a hardware sensor, and interact with apps on your behalf.
+ </string>
+
+ <!-- String for the allow button in accessibility permission dialog. [CHAR LIMIT=10] -->
+ <string name="accessibility_dialog_button_allow">Allow</string>
+ <!-- String for the deny button in accessibility permission dialog. [CHAR LIMIT=10] -->
+ <string name="accessibility_dialog_button_deny">Deny</string>
+
<!-- Title for accessibility select shortcut menu dialog. [CHAR LIMIT=100] -->
- <string name="accessibility_select_shortcut_menu_title">Tap the accessibility app you want to use</string>
+ <string name="accessibility_select_shortcut_menu_title">Tap a feature to start using it:</string>
<!-- Title for accessibility edit shortcut selection menu dialog, and dialog is triggered
from accessibility button. [CHAR LIMIT=100] -->
- <string name="accessibility_edit_shortcut_menu_button_title">Choose apps you want to use with
+ <string name="accessibility_edit_shortcut_menu_button_title">Choose apps to use with the
accessibility button
</string>
<!-- Title for accessibility edit shortcut selection menu dialog, and dialog is triggered
from volume key shortcut. [CHAR LIMIT=100] -->
- <string name="accessibility_edit_shortcut_menu_volume_title">Choose apps you want to use with
+ <string name="accessibility_edit_shortcut_menu_volume_title">Choose apps to use with the
volume key shortcut
</string>
+ <!-- Text for showing the warning to user when uncheck the legacy app item in the accessibility
+ shortcut menu, user can aware the service to be disabled. [CHAR LIMIT=100] -->
+ <string name="accessibility_uncheck_legacy_item_warning">
+ <xliff:g id="service_name" example="TalkBack">%s</xliff:g> has been turned off</string>
+
<!-- Text in button that edit the accessibility shortcut menu, user can delete
any service item in the menu list. [CHAR LIMIT=100] -->
<string name="edit_accessibility_shortcut_menu_button">Edit shortcuts</string>
- <!-- Text in button that cancel the accessibility shortcut menu changed status. [CHAR LIMIT=100] -->
- <string name="cancel_accessibility_shortcut_menu_button">Cancel</string>
+ <!-- Text in button that complete the accessibility shortcut menu changed status. [CHAR LIMIT=100] -->
+ <string name="done_accessibility_shortcut_menu_button">Done</string>
<!-- Text in button that turns off the accessibility shortcut -->
<string name="disable_accessibility_shortcut">Turn off Shortcut</string>
@@ -5384,27 +5440,46 @@
<string name="as_app_forced_to_restricted_bucket">
<xliff:g id="package_name" example="com.android.example">%1$s</xliff:g> has been put into the RESTRICTED bucket</string>
+ <!-- The way a conversation name is displayed when single line. The text will be displayed to the end of this text with some spacing -->
+ <string name="conversation_single_line_name_display"><xliff:g id="sender_name" example="Sara">%1$s</xliff:g>:</string>
+
+ <!-- Conversation Title fallback if the there is no name provided in a 1:1 conversation [CHAR LIMIT=40]-->
+ <string name="conversation_title_fallback_one_to_one">Conversation</string>
+
+ <!-- Conversation Title fallback if the there is no name provided in a group chat conversation [CHAR LIMIT=40]-->
+ <string name="conversation_title_fallback_group_chat">Group Conversation</string>
+
<!-- ResolverActivity - profile tabs -->
- <!-- Label for the perosnal tab of the share sheet and intent resolver [CHAR LIMIT=NONE] -->
+ <!-- Label of a tab on a screen. A user can tap this tap to switch to the 'Personal' view (that shows their personal content) if they have a work profile on their device. [CHAR LIMIT=NONE] -->
<string name="resolver_personal_tab">Personal</string>
- <!-- Label for the work tab of the share sheet and intent resolver [CHAR LIMIT=NONE] -->
+ <!-- Label of a tab on a screen. A user can tap this tab to switch to the 'Work' view (that shows their work content) if they have a work profile on their device. [CHAR LIMIT=NONE] -->
<string name="resolver_work_tab">Work</string>
- <!-- Label to indicate that the user cannot share with work apps [CHAR LIMIT=NONE] -->
+ <!-- Accessibility label for the personal tab button. [CHAR LIMIT=NONE] -->
+ <string name="resolver_personal_tab_accessibility">Personal view</string>
+ <!-- Accessibility label for the work tab button. [CHAR LIMIT=NONE] -->
+ <string name="resolver_work_tab_accessibility">Work view</string>
+ <!-- Title of a screen. This text lets the user know that their IT admin doesn't allow them to share personal content with work apps. [CHAR LIMIT=NONE] -->
<string name="resolver_cant_share_with_work_apps">Can\u2019t share with work apps</string>
- <!-- Label to indicate that the user cannot share with personal apps [CHAR LIMIT=NONE] -->
+ <!-- Title of a screen. This text lets the user know that their IT admin doesn't allow them to share work content with personal apps. [CHAR LIMIT=NONE] -->
<string name="resolver_cant_share_with_personal_apps">Can\u2019t share with personal apps</string>
- <!-- Label to explain to the user that sharing between personal and work apps is not enabled by the IT admin [CHAR LIMIT=NONE] -->
- <string name="resolver_cant_share_cross_profile_explanation">Your IT admin blocked sharing between personal and work apps</string>
- <!-- Label to indicate that the user has to turn on work apps in order to access work data [CHAR LIMIT=NONE] -->
- <string name="resolver_turn_on_work_apps">Turn on work apps</string>
- <!-- Label to explain that the user has to turn on work apps in order to access work data [CHAR LIMIT=NONE] -->
- <string name="resolver_turn_on_work_apps_explanation">Turn on work apps to access work apps & contacts</string>
- <!-- Label to indicate that no apps are resolved [CHAR LIMIT=NONE] -->
+ <!-- Error message. This text is explaining that the user's IT admin doesn't allow sharing between personal and work apps. [CHAR LIMIT=NONE] -->
+ <string name="resolver_cant_share_cross_profile_explanation">Your IT admin blocked sharing between personal and work profiles</string>
+ <!-- Title of an error screen. This error message lets the user know that their IT admin blocked access to work apps, and the personal content that they're trying to view in a work app, such as Chrome, isn't allowed. [CHAR LIMIT=NONE] -->
+ <string name="resolver_cant_access_work_apps">Can\u2019t access work apps</string>
+ <!-- Error message. This message lets the user know that their IT admin blocked access to work apps, and the personal content that they're trying to view in a work app, such as Chrome, isn't allowed. [CHAR LIMIT=NONE] -->
+ <string name="resolver_cant_access_work_apps_explanation">Your IT admin doesn\u2019t let you view personal content in work apps</string>
+ <!-- Title of an error screen. This error message lets the user know that their IT admin blocked access to personal apps, and the work content that they're trying to view in a personal app, such as Chrome, isn't allowed. [CHAR LIMIT=NONE] -->
+ <string name="resolver_cant_access_personal_apps">Can\u2019t access personal apps</string>
+ <!-- Error message. This message lets the user know that their IT admin blocked access to personal apps, and the work content that they're trying to view in a personal app, such as Chrome, isn't allowed. [CHAR LIMIT=NONE] -->
+ <string name="resolver_cant_access_personal_apps_explanation">Your IT admin doesn\u2019t let you view work content in personal apps</string>
+ <!-- Error message. This text lets the user know that they need to turn on work apps in order to share content. There's also a button a user can tap to turn on the apps. [CHAR LIMIT=NONE] -->
+ <string name="resolver_turn_on_work_apps_share">Turn on work profile to share content</string>
+ <!-- Error message. This text lets the user know that they need to turn on work apps in order to view content. There's also a button a user can tap to turn on the apps. [CHAR LIMIT=NONE] -->
+ <string name="resolver_turn_on_work_apps_view">Turn on work profile to view content</string>
+ <!-- Error message. This text lets the user know that work apps aren't available on the device. [CHAR LIMIT=NONE] -->
<string name="resolver_no_apps_available">No apps available</string>
- <!-- Label to explain that no apps are resolved [CHAR LIMIT=NONE] -->
- <string name="resolver_no_apps_available_explanation">We couldn\u2019t find any apps</string>
- <!-- Button which switches on the disabled work profile [CHAR LIMIT=NONE] -->
- <string name="resolver_switch_on_work">Switch on work</string>
+ <!-- Button text. This button turns on a user's work profile so they can access their work apps and data. [CHAR LIMIT=NONE] -->
+ <string name="resolver_switch_on_work">Turn on</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. [CHAR LIMIT=NONE] -->
<string name="permlab_accessCallAudio">Record or play audio in telephony calls</string>
diff --git a/core/res/res/values/styles_device_defaults.xml b/core/res/res/values/styles_device_defaults.xml
index 966f495..64768cf 100644
--- a/core/res/res/values/styles_device_defaults.xml
+++ b/core/res/res/values/styles_device_defaults.xml
@@ -146,7 +146,7 @@
<item name="textAppearance">@style/TextAppearance.DeviceDefault.Notification</item>
</style>
<style name="Widget.DeviceDefault.Notification.MessagingName" parent="Widget.Material.Notification.MessagingName">
- <item name="textAppearance">@style/TextAppearance.DeviceDefault.Notification.MessagingName</item>
+ <item name="textAppearance">@style/TextAppearance.DeviceDefault.Notification.Title</item>
</style>
<style name="Widget.DeviceDefault.PreferenceFrameLayout" parent="Widget.Material.PreferenceFrameLayout"/>
<style name="Widget.DeviceDefault.ProgressBar.Inverse" parent="Widget.Material.ProgressBar.Inverse"/>
@@ -290,9 +290,6 @@
<style name="TextAppearance.DeviceDefault.Notification.Title" parent="TextAppearance.Material.Notification.Title">
<item name="fontFamily">@string/config_headlineFontFamilyMedium</item>
</style>
- <style name="TextAppearance.DeviceDefault.Notification.MessagingName" parent="TextAppearance.DeviceDefault.Notification.Title">
- <item name="textSize">16sp</item>
- </style>
<style name="TextAppearance.DeviceDefault.Notification.Reply" parent="TextAppearance.Material.Notification.Reply">
<item name="fontFamily">@string/config_bodyFontFamily</item>
</style>
diff --git a/core/res/res/values/styles_material.xml b/core/res/res/values/styles_material.xml
index 63ac0e6..2415837 100644
--- a/core/res/res/values/styles_material.xml
+++ b/core/res/res/values/styles_material.xml
@@ -504,7 +504,7 @@
<style name="Widget.Material.Notification.MessagingText" parent="Widget.Material.Notification.Text">
<item name="layout_width">wrap_content</item>
<item name="layout_height">wrap_content</item>
- <item name="ellipsize">end</item>z
+ <item name="ellipsize">end</item>
</style>
<style name="Widget.Material.Notification.MessagingName" parent="Widget.Material.Light.TextView">
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index c1d8168..4c0dd8d 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -688,7 +688,6 @@
<java-symbol type="string" name="capability_title_canControlMagnification" />
<java-symbol type="string" name="capability_desc_canPerformGestures" />
<java-symbol type="string" name="capability_title_canPerformGestures" />
- <java-symbol type="string" name="captive_portal_logged_in_detailed" />
<java-symbol type="string" name="capital_off" />
<java-symbol type="string" name="capital_on" />
<java-symbol type="string" name="cfTemplateForwarded" />
@@ -3240,24 +3239,31 @@
<java-symbol type="string" name="accessibility_select_shortcut_menu_title" />
<java-symbol type="string" name="accessibility_edit_shortcut_menu_button_title" />
<java-symbol type="string" name="accessibility_edit_shortcut_menu_volume_title" />
+ <java-symbol type="string" name="accessibility_uncheck_legacy_item_warning" />
+
+ <java-symbol type="layout" name="accessibility_enable_service_encryption_warning" />
+ <java-symbol type="id" name="accessibility_permissionDialog_icon" />
+ <java-symbol type="id" name="accessibility_permissionDialog_title" />
+ <java-symbol type="id" name="accessibility_encryption_warning" />
+ <java-symbol type="id" name="accessibility_permission_enable_allow_button" />
+ <java-symbol type="id" name="accessibility_permission_enable_deny_button" />
+ <java-symbol type="string" name="accessibility_enable_service_title" />
+ <java-symbol type="string" name="accessibility_enable_service_encryption_warning" />
<!-- Accessibility Button -->
<java-symbol type="layout" name="accessibility_button_chooser_item" />
+ <java-symbol type="id" name="accessibility_button_target_checkbox" />
<java-symbol type="id" name="accessibility_button_target_icon" />
<java-symbol type="id" name="accessibility_button_target_label" />
- <java-symbol type="id" name="accessibility_button_target_item_container" />
- <java-symbol type="id" name="accessibility_button_target_view_item" />
<java-symbol type="id" name="accessibility_button_target_switch_item" />
<java-symbol type="string" name="accessibility_magnification_chooser_text" />
<java-symbol type="string" name="edit_accessibility_shortcut_menu_button" />
- <java-symbol type="string" name="cancel_accessibility_shortcut_menu_button" />
+ <java-symbol type="string" name="done_accessibility_shortcut_menu_button" />
<java-symbol type="drawable" name="ic_accessibility_color_inversion" />
<java-symbol type="drawable" name="ic_accessibility_color_correction" />
<java-symbol type="drawable" name="ic_accessibility_magnification" />
- <java-symbol type="drawable" name="ic_delete_item" />
-
<!-- com.android.internal.widget.RecyclerView -->
<java-symbol type="id" name="item_touch_helper_previous_elevation"/>
<java-symbol type="dimen" name="item_touch_helper_max_drag_scroll_per_frame"/>
@@ -3609,6 +3615,7 @@
<java-symbol type="bool" name="config_batterySaverStickyBehaviourDisabled" />
<java-symbol type="integer" name="config_dynamicPowerSavingsDefaultDisableThreshold" />
<java-symbol type="string" name="config_batterySaverScheduleProvider" />
+ <java-symbol type="string" name="config_powerSaveModeChangedListenerPackage" />
<!-- For car devices -->
<java-symbol type="string" name="car_loading_profile" />
@@ -3870,11 +3877,41 @@
<java-symbol type="array" name="config_defaultImperceptibleKillingExemptionPkgs" />
<java-symbol type="array" name="config_defaultImperceptibleKillingExemptionProcStates" />
+ <java-symbol type="string" name="conversation_single_line_name_display" />
+ <java-symbol type="string" name="conversation_title_fallback_one_to_one" />
+ <java-symbol type="string" name="conversation_title_fallback_group_chat" />
+ <java-symbol type="id" name="conversation_icon" />
+ <java-symbol type="id" name="conversation_icon_badge" />
+ <java-symbol type="id" name="expand_button_container" />
+ <java-symbol type="id" name="messaging_group_content_container" />
+ <java-symbol type="id" name="expand_button_and_content_container" />
+ <java-symbol type="id" name="conversation_header" />
+ <java-symbol type="id" name="conversation_face_pile_bottom_background" />
+ <java-symbol type="id" name="conversation_face_pile_bottom" />
+ <java-symbol type="id" name="conversation_face_pile_top" />
+ <java-symbol type="id" name="conversation_face_pile" />
+ <java-symbol type="id" name="conversation_text" />
+ <java-symbol type="id" name="message_icon_container" />
+ <java-symbol type="dimen" name="conversation_expand_button_top_margin_expanded" />
+ <java-symbol type="dimen" name="conversation_expand_button_expanded_size" />
+ <java-symbol type="dimen" name="messaging_group_singleline_sender_padding_end" />
+ <java-symbol type="dimen" name="conversation_badge_side_margin" />
+ <java-symbol type="dimen" name="conversation_icon_size_badged" />
+ <java-symbol type="dimen" name="conversation_icon_size_centered" />
+ <java-symbol type="dimen" name="conversation_icon_margin_top_centered" />
+ <java-symbol type="dimen" name="conversation_content_start" />
+ <java-symbol type="dimen" name="messaging_layout_margin_end" />
+ <java-symbol type="dimen" name="conversation_header_expanded_padding_end" />
+ <java-symbol type="layout" name="notification_template_material_conversation" />
+ <java-symbol type="layout" name="conversation_face_pile_layout" />
+
<!-- Intent resolver and share sheet -->
<java-symbol type="color" name="resolver_tabs_active_color" />
<java-symbol type="color" name="resolver_tabs_inactive_color" />
<java-symbol type="string" name="resolver_personal_tab" />
+ <java-symbol type="string" name="resolver_personal_tab_accessibility" />
<java-symbol type="string" name="resolver_work_tab" />
+ <java-symbol type="string" name="resolver_work_tab_accessibility" />
<java-symbol type="id" name="stub" />
<java-symbol type="id" name="resolver_empty_state" />
<java-symbol type="id" name="resolver_empty_state_icon" />
@@ -3886,11 +3923,13 @@
<java-symbol type="string" name="resolver_cant_share_with_work_apps" />
<java-symbol type="string" name="resolver_cant_share_with_personal_apps" />
<java-symbol type="string" name="resolver_cant_share_cross_profile_explanation" />
- <java-symbol type="string" name="resolver_turn_on_work_apps" />
- <java-symbol type="string" name="resolver_turn_on_work_apps_explanation" />
+ <java-symbol type="string" name="resolver_cant_access_work_apps" />
+ <java-symbol type="string" name="resolver_cant_access_work_apps_explanation" />
+ <java-symbol type="string" name="resolver_cant_access_personal_apps" />
+ <java-symbol type="string" name="resolver_cant_access_personal_apps_explanation" />
+ <java-symbol type="string" name="resolver_turn_on_work_apps_view" />
+ <java-symbol type="string" name="resolver_turn_on_work_apps_share" />
<java-symbol type="string" name="resolver_no_apps_available" />
- <java-symbol type="string" name="resolver_no_apps_available_explanation" />
- <java-symbol type="string" name="resolver_no_apps_available_explanation" />
<java-symbol type="string" name="resolver_switch_on_work" />
<java-symbol type="drawable" name="ic_work_apps_off" />
<java-symbol type="drawable" name="ic_sharing_disabled" />
@@ -3899,7 +3938,6 @@
<java-symbol type="dimen" name="resolver_empty_state_height_with_tabs" />
<java-symbol type="dimen" name="resolver_max_collapsed_height_with_tabs" />
<java-symbol type="bool" name="sharesheet_show_content_preview" />
- <java-symbol type="dimen" name="resolver_tab_divider_bottom_padding" />
<!-- Toast message for background started foreground service while-in-use permission restriction feature -->
<java-symbol type="string" name="allow_while_in_use_permission_in_fgs" />
@@ -3917,4 +3955,6 @@
<java-symbol type="string" name="config_customMediaKeyDispatcher" />
<java-symbol type="string" name="config_customSessionPolicyProvider" />
+ <!-- The max scale for the wallpaper when it's zoomed in -->
+ <java-symbol type="dimen" name="config_wallpaperMaxScale"/>
</resources>
diff --git a/core/tests/coretests/src/android/app/NotificationHistoryTest.java b/core/tests/coretests/src/android/app/NotificationHistoryTest.java
index 0443d3a..c951091 100644
--- a/core/tests/coretests/src/android/app/NotificationHistoryTest.java
+++ b/core/tests/coretests/src/android/app/NotificationHistoryTest.java
@@ -351,5 +351,7 @@
HistoricalNotification postParcelNotification = parceledHistory.getNextNotification();
assertThat(postParcelNotification).isEqualTo(expectedEntries.get(i));
}
+ assertThat(parceledHistory.hasNextNotification()).isFalse();
+ assertThat(parceledHistory.getNextNotification()).isNull();
}
}
diff --git a/core/tests/coretests/src/android/content/AbstractCrossUserContentResolverTest.java b/core/tests/coretests/src/android/content/AbstractCrossUserContentResolverTest.java
index c307e64..328429c 100644
--- a/core/tests/coretests/src/android/content/AbstractCrossUserContentResolverTest.java
+++ b/core/tests/coretests/src/android/content/AbstractCrossUserContentResolverTest.java
@@ -39,6 +39,7 @@
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -194,8 +195,8 @@
}
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
- if (mExpectedUri.equals(uri) && mExpectedUserId == userId) {
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags, int userId) {
+ if (uris.contains(mExpectedUri) && mExpectedUserId == userId) {
mLatch.countDown();
}
}
diff --git a/core/tests/coretests/src/android/content/ApexContextTest.java b/core/tests/coretests/src/android/content/ApexEnvironmentTest.java
similarity index 75%
rename from core/tests/coretests/src/android/content/ApexContextTest.java
rename to core/tests/coretests/src/android/content/ApexEnvironmentTest.java
index d15c64d..438c5ae 100644
--- a/core/tests/coretests/src/android/content/ApexContextTest.java
+++ b/core/tests/coretests/src/android/content/ApexEnvironmentTest.java
@@ -28,20 +28,21 @@
@SmallTest
@RunWith(AndroidJUnit4.class)
-public class ApexContextTest {
+public class ApexEnvironmentTest {
@Test
public void dataDirectoryPathsAreAsExpected() {
- ApexContext apexContext = ApexContext.getApexContext("my.apex");
+ ApexEnvironment apexEnvironment = ApexEnvironment.getApexEnvironment("my.apex");
assertEquals("/data/misc/apexdata/my.apex",
- apexContext.getDeviceProtectedDataDir().getAbsolutePath());
+ apexEnvironment.getDeviceProtectedDataDir().getAbsolutePath());
assertEquals("/data/misc_de/5/apexdata/my.apex",
- apexContext.getDeviceProtectedDataDirForUser(UserHandle.of(5)).getAbsolutePath());
+ apexEnvironment
+ .getDeviceProtectedDataDirForUser(UserHandle.of(5)).getAbsolutePath());
assertEquals("/data/misc_ce/16/apexdata/my.apex",
- apexContext.getCredentialProtectedDataDirForUser(
+ apexEnvironment.getCredentialProtectedDataDirForUser(
UserHandle.of(16)).getAbsolutePath());
}
}
diff --git a/core/tests/coretests/src/android/os/EnvironmentTest.java b/core/tests/coretests/src/android/os/EnvironmentTest.java
index d98ceaf..c0325ca 100644
--- a/core/tests/coretests/src/android/os/EnvironmentTest.java
+++ b/core/tests/coretests/src/android/os/EnvironmentTest.java
@@ -23,7 +23,10 @@
import static android.os.Environment.classifyExternalStorageDirectory;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import android.app.AppOpsManager;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
@@ -40,10 +43,33 @@
public class EnvironmentTest {
private File dir;
- private Context getContext() {
+ private static Context getContext() {
return InstrumentationRegistry.getContext();
}
+ /**
+ * Sets {@code mode} for the given {@code ops} and the given {@code uid}.
+ *
+ * <p>This method drops shell permission identity.
+ */
+ private static void setAppOpsModeForUid(int uid, int mode, String... ops) {
+ if (ops == null) {
+ return;
+ }
+ InstrumentationRegistry.getInstrumentation()
+ .getUiAutomation()
+ .adoptShellPermissionIdentity();
+ try {
+ for (String op : ops) {
+ getContext().getSystemService(AppOpsManager.class).setUidMode(op, uid, mode);
+ }
+ } finally {
+ InstrumentationRegistry.getInstrumentation()
+ .getUiAutomation()
+ .dropShellPermissionIdentity();
+ }
+ }
+
@Before
public void setUp() throws Exception {
dir = getContext().getDir("testing", Context.MODE_PRIVATE);
@@ -101,4 +127,17 @@
Environment.buildPath(dir, "Taxes.pdf").createNewFile();
assertEquals(HAS_OTHER, classifyExternalStorageDirectory(dir));
}
+
+ @Test
+ public void testIsExternalStorageManager() throws Exception {
+ assertFalse(Environment.isExternalStorageManager());
+ try {
+ setAppOpsModeForUid(Process.myUid(), AppOpsManager.MODE_ALLOWED,
+ AppOpsManager.OPSTR_MANAGE_EXTERNAL_STORAGE);
+ assertTrue(Environment.isExternalStorageManager());
+ } finally {
+ setAppOpsModeForUid(Process.myUid(), AppOpsManager.MODE_DEFAULT,
+ AppOpsManager.OPSTR_MANAGE_EXTERNAL_STORAGE);
+ }
+ }
}
diff --git a/core/tests/coretests/src/android/service/controls/actions/ControlActionTest.java b/core/tests/coretests/src/android/service/controls/actions/ControlActionTest.java
index 10a7b76..d8088b7 100644
--- a/core/tests/coretests/src/android/service/controls/actions/ControlActionTest.java
+++ b/core/tests/coretests/src/android/service/controls/actions/ControlActionTest.java
@@ -56,16 +56,6 @@
}
@Test
- public void testUnparcelingCorrectClass_multiFloat() {
- ControlAction toParcel = new MultiFloatAction(TEST_ID, new float[] {0f, 1f});
-
- ControlAction fromParcel = parcelAndUnparcel(toParcel);
-
- assertEquals(ControlAction.TYPE_MULTI_FLOAT, fromParcel.getActionType());
- assertTrue(fromParcel instanceof MultiFloatAction);
- }
-
- @Test
public void testUnparcelingCorrectClass_mode() {
ControlAction toParcel = new ModeAction(TEST_ID, 1);
diff --git a/core/tests/coretests/src/android/service/controls/templates/ControlTemplateTest.java b/core/tests/coretests/src/android/service/controls/templates/ControlTemplateTest.java
index 292ac09..87dc1b7 100644
--- a/core/tests/coretests/src/android/service/controls/templates/ControlTemplateTest.java
+++ b/core/tests/coretests/src/android/service/controls/templates/ControlTemplateTest.java
@@ -103,16 +103,6 @@
}
@Test
- public void testUnparcelingCorrectClass_thumbnail() {
- ControlTemplate toParcel = new ThumbnailTemplate(TEST_ID, mIcon, TEST_ACTION_DESCRIPTION);
-
- ControlTemplate fromParcel = parcelAndUnparcel(toParcel);
-
- assertEquals(ControlTemplate.TYPE_THUMBNAIL, fromParcel.getTemplateType());
- assertTrue(fromParcel instanceof ThumbnailTemplate);
- }
-
- @Test
public void testUnparcelingCorrectClass_toggleRange() {
ControlTemplate toParcel = new ToggleRangeTemplate(TEST_ID, mControlButton,
new RangeTemplate(TEST_ID, 0, 2, 1, 1, "%f"));
diff --git a/core/tests/coretests/src/android/util/apk/SourceStampVerifierTest.java b/core/tests/coretests/src/android/util/apk/SourceStampVerifierTest.java
index 44f6407..37b2817 100644
--- a/core/tests/coretests/src/android/util/apk/SourceStampVerifierTest.java
+++ b/core/tests/coretests/src/android/util/apk/SourceStampVerifierTest.java
@@ -37,6 +37,8 @@
import java.io.InputStream;
import java.nio.file.Files;
import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@@ -129,6 +131,48 @@
assertNull(result.getCertificate());
}
+ @Test
+ public void testSourceStamp_multiApk_validStamps() throws Exception {
+ File testApk1 = getApk("SourceStampVerifierTest/valid-stamp.apk");
+ File testApk2 = getApk("SourceStampVerifierTest/valid-stamp.apk");
+ ZipFile apkZipFile = new ZipFile(testApk1);
+ ZipEntry stampCertZipEntry = apkZipFile.getEntry("stamp-cert-sha256");
+ int size = (int) stampCertZipEntry.getSize();
+ byte[] expectedStampCertHash = new byte[size];
+ try (InputStream inputStream = apkZipFile.getInputStream(stampCertZipEntry)) {
+ inputStream.read(expectedStampCertHash);
+ }
+ List<String> apkFiles = new ArrayList<>();
+ apkFiles.add(testApk1.getAbsolutePath());
+ apkFiles.add(testApk2.getAbsolutePath());
+
+ SourceStampVerificationResult result =
+ SourceStampVerifier.verify(apkFiles);
+
+ assertTrue(result.isPresent());
+ assertTrue(result.isVerified());
+ assertNotNull(result.getCertificate());
+ byte[] actualStampCertHash =
+ MessageDigest.getInstance("SHA-256").digest(result.getCertificate().getEncoded());
+ assertArrayEquals(expectedStampCertHash, actualStampCertHash);
+ }
+
+ @Test
+ public void testSourceStamp_multiApk_invalidStamps() throws Exception {
+ File testApk1 = getApk("SourceStampVerifierTest/valid-stamp.apk");
+ File testApk2 = getApk("SourceStampVerifierTest/stamp-apk-hash-mismatch.apk");
+ List<String> apkFiles = new ArrayList<>();
+ apkFiles.add(testApk1.getAbsolutePath());
+ apkFiles.add(testApk2.getAbsolutePath());
+
+ SourceStampVerificationResult result =
+ SourceStampVerifier.verify(apkFiles);
+
+ assertTrue(result.isPresent());
+ assertFalse(result.isVerified());
+ assertNull(result.getCertificate());
+ }
+
private File getApk(String apkPath) throws IOException {
File testApk = File.createTempFile("SourceStampApk", ".apk");
try (InputStream inputStream = mContext.getAssets().open(apkPath)) {
diff --git a/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java b/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
index 50cd5a3..fe25e79 100644
--- a/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
+++ b/core/tests/coretests/src/android/view/InsetsAnimationControlImplTest.java
@@ -123,7 +123,7 @@
mController = new InsetsAnimationControlImpl(controls,
new Rect(0, 0, 500, 500), mInsetsState, mMockListener, systemBars(),
mMockController, 10 /* durationMs */, new LinearInterpolator(),
- false /* fade */, LAYOUT_INSETS_DURING_ANIMATION_SHOWN, 0 /* animationType */);
+ false /* fade */, 0 /* animationType */);
}
@Test
@@ -182,7 +182,7 @@
@Test
public void testCancelled() {
- mController.onCancelled();
+ mController.cancel();
try {
mController.setInsetsAndAlpha(Insets.NONE, 1f /*alpha */, 0f /* fraction */);
fail("Expected exception to be thrown");
diff --git a/core/tests/coretests/src/android/view/InsetsControllerTest.java b/core/tests/coretests/src/android/view/InsetsControllerTest.java
index 7737b1a..42ab2e7 100644
--- a/core/tests/coretests/src/android/view/InsetsControllerTest.java
+++ b/core/tests/coretests/src/android/view/InsetsControllerTest.java
@@ -31,6 +31,7 @@
import static org.junit.Assert.assertEquals;
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.mockito.ArgumentMatchers.any;
@@ -47,29 +48,32 @@
import android.graphics.Rect;
import android.os.CancellationSignal;
import android.platform.test.annotations.Presubmit;
+import android.view.InsetsState.InternalInsetsType;
import android.view.SurfaceControl.Transaction;
import android.view.WindowInsets.Type;
+import android.view.WindowInsetsController.OnControllableInsetsChangedListener;
import android.view.WindowManager.BadTokenException;
import android.view.WindowManager.LayoutParams;
import android.view.animation.LinearInterpolator;
import android.view.test.InsetsModeSession;
import android.widget.TextView;
-import com.android.server.testutils.OffsettableClock;
-import com.android.server.testutils.TestHandler;
-
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
+import com.android.server.testutils.OffsettableClock;
+import com.android.server.testutils.TestHandler;
+
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
import java.util.concurrent.CountDownLatch;
-import java.util.function.Supplier;
/**
* Tests for {@link InsetsController}.
@@ -166,33 +170,35 @@
@Test
public void testControlsChanged() {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
- mController.onControlsChanged(new InsetsSourceControl[] { control });
- assertEquals(mLeash,
- mController.getSourceConsumer(ITYPE_STATUS_BAR).getControl().getLeash());
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
+ assertNotNull(mController.getSourceConsumer(ITYPE_STATUS_BAR).getControl().getLeash());
+ mController.addOnControllableInsetsChangedListener(
+ ((controller, typeMask) -> assertEquals(statusBars(), typeMask)));
}
@Test
public void testControlsRevoked() {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
- mController.onControlsChanged(new InsetsSourceControl[] { control });
+ OnControllableInsetsChangedListener listener
+ = mock(OnControllableInsetsChangedListener.class);
+ mController.addOnControllableInsetsChangedListener(listener);
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
mController.onControlsChanged(new InsetsSourceControl[0]);
assertNull(mController.getSourceConsumer(ITYPE_STATUS_BAR).getControl());
+ InOrder inOrder = Mockito.inOrder(listener);
+ inOrder.verify(listener).onControllableInsetsChanged(eq(mController), eq(0));
+ inOrder.verify(listener).onControllableInsetsChanged(eq(mController), eq(statusBars()));
+ inOrder.verify(listener).onControllableInsetsChanged(eq(mController), eq(0));
}
@Test
public void testControlsRevoked_duringAnim() {
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
- mController.onControlsChanged(new InsetsSourceControl[] { control });
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
WindowInsetsAnimationControlListener mockListener =
mock(WindowInsetsAnimationControlListener.class);
mController.controlWindowInsetsAnimation(statusBars(), 10 /* durationMs */,
- new LinearInterpolator(), mockListener);
+ new LinearInterpolator(), new CancellationSignal(), mockListener);
// Ready gets deferred until next predraw
mViewRoot.getView().getViewTreeObserver().dispatchOnPreDraw();
@@ -206,10 +212,15 @@
public void testFrameDoesntMatchDisplay() {
mController.onFrameChanged(new Rect(0, 0, 100, 100));
mController.getState().setDisplayFrame(new Rect(0, 0, 200, 200));
+ InsetsSourceControl control =
+ new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
+ mController.onControlsChanged(new InsetsSourceControl[] { control });
WindowInsetsAnimationControlListener controlListener =
mock(WindowInsetsAnimationControlListener.class);
mController.controlWindowInsetsAnimation(0, 0 /* durationMs */, new LinearInterpolator(),
- controlListener);
+ new CancellationSignal(), controlListener);
+ mController.addOnControllableInsetsChangedListener(
+ (controller, typeMask) -> assertEquals(0, typeMask));
verify(controlListener).onCancelled();
verify(controlListener, never()).onReady(any(), anyInt());
}
@@ -245,11 +256,8 @@
@Test
public void testApplyImeVisibility() {
- final InsetsSourceControl ime = new InsetsSourceControl(ITYPE_IME, mLeash, new Point());
-
- InsetsSourceControl[] controls = new InsetsSourceControl[3];
- controls[0] = ime;
- mController.onControlsChanged(controls);
+ InsetsSourceControl ime = createControl(ITYPE_IME);
+ mController.onControlsChanged(new InsetsSourceControl[] { ime });
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
mController.getSourceConsumer(ITYPE_IME).onWindowFocusGained();
mController.applyImeVisibility(true);
@@ -412,9 +420,7 @@
@Test
public void testRestoreStartsAnimation() {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
- mController.onControlsChanged(new InsetsSourceControl[]{control});
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
mController.hide(Type.statusBars());
@@ -431,7 +437,7 @@
assertTrue(mController.getState().getSource(ITYPE_STATUS_BAR).isVisible());
// Gaining control
- mController.onControlsChanged(new InsetsSourceControl[]{control});
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
assertEquals(ANIMATION_TYPE_HIDE, mController.getAnimationType(ITYPE_STATUS_BAR));
mController.cancelExistingAnimation();
assertFalse(mController.getSourceConsumer(ITYPE_STATUS_BAR).isRequestedVisible());
@@ -442,8 +448,6 @@
@Test
public void testStartImeAnimationAfterGettingControl() {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_IME, mLeash, new Point());
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
@@ -454,7 +458,7 @@
mController.show(ime(), true /* fromIme */);
// Gaining control shortly after
- mController.onControlsChanged(new InsetsSourceControl[]{control});
+ mController.onControlsChanged(createSingletonControl(ITYPE_IME));
assertEquals(ANIMATION_TYPE_SHOW, mController.getAnimationType(ITYPE_IME));
mController.cancelExistingAnimation();
@@ -466,16 +470,13 @@
@Test
public void testStartImeAnimationAfterGettingControl_imeLater() {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_IME, mLeash, new Point());
-
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
mController.show(ime());
assertFalse(mController.getState().getSource(ITYPE_IME).isVisible());
// Gaining control shortly after
- mController.onControlsChanged(new InsetsSourceControl[]{control});
+ mController.onControlsChanged(createSingletonControl(ITYPE_IME));
// Pretend IME is calling
mController.show(ime(), true /* fromIme */);
@@ -490,15 +491,13 @@
@Test
public void testAnimationEndState_controller() throws Exception {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
- mController.onControlsChanged(new InsetsSourceControl[] { control });
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener mockListener =
mock(WindowInsetsAnimationControlListener.class);
mController.controlWindowInsetsAnimation(statusBars(), 0 /* durationMs */,
- new LinearInterpolator(), mockListener);
+ new LinearInterpolator(), new CancellationSignal(), mockListener);
ArgumentCaptor<WindowInsetsAnimationController> controllerCaptor =
ArgumentCaptor.forClass(WindowInsetsAnimationController.class);
@@ -518,16 +517,15 @@
@Test
public void testCancellation_afterGainingControl() throws Exception {
- InsetsSourceControl control =
- new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash, new Point());
- mController.onControlsChanged(new InsetsSourceControl[] { control });
+ mController.onControlsChanged(createSingletonControl(ITYPE_STATUS_BAR));
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener mockListener =
mock(WindowInsetsAnimationControlListener.class);
- CancellationSignal cancellationSignal = mController.controlWindowInsetsAnimation(
+ CancellationSignal cancellationSignal = new CancellationSignal();
+ mController.controlWindowInsetsAnimation(
statusBars(), 0 /* durationMs */,
- new LinearInterpolator(), mockListener);
+ new LinearInterpolator(), cancellationSignal, mockListener);
// Ready gets deferred until next predraw
mViewRoot.getView().getViewTreeObserver().dispatchOnPreDraw();
@@ -550,7 +548,8 @@
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener listener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(), listener);
+ mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(),
+ null /* cancellationSignal */, listener);
// Ready gets deferred until next predraw
mViewRoot.getView().getViewTreeObserver().dispatchOnPreDraw();
@@ -574,7 +573,8 @@
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener listener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(), listener);
+ mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(),
+ null /* cancellationSignal */, listener);
// Ready gets deferred until next predraw
mViewRoot.getView().getViewTreeObserver().dispatchOnPreDraw();
@@ -594,7 +594,8 @@
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener listener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(), listener);
+ mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(),
+ null /* cancellationSignal */, listener);
// Ready gets deferred until next predraw
mViewRoot.getView().getViewTreeObserver().dispatchOnPreDraw();
@@ -615,8 +616,10 @@
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
WindowInsetsAnimationControlListener listener =
mock(WindowInsetsAnimationControlListener.class);
- mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(), listener)
- .cancel();
+ CancellationSignal cancellationSignal = new CancellationSignal();
+ mController.controlWindowInsetsAnimation(ime(), 0, new LinearInterpolator(),
+ cancellationSignal, listener);
+ cancellationSignal.cancel();
verify(listener).onCancelled();
@@ -638,12 +641,23 @@
latch.await();
}
+ private InsetsSourceControl createControl(@InternalInsetsType int type) {
+
+ // Simulate binder behavior by copying SurfaceControl. Otherwise, InsetsController will
+ // attempt to release mLeash directly.
+ SurfaceControl copy = new SurfaceControl();
+ copy.copyFrom(mLeash);
+ return new InsetsSourceControl(type, copy, new Point());
+ }
+
+ private InsetsSourceControl[] createSingletonControl(@InternalInsetsType int type) {
+ return new InsetsSourceControl[] { createControl(type) };
+ }
+
private InsetsSourceControl[] prepareControls() {
- final InsetsSourceControl navBar = new InsetsSourceControl(ITYPE_NAVIGATION_BAR, mLeash,
- new Point());
- final InsetsSourceControl statusBar = new InsetsSourceControl(ITYPE_STATUS_BAR, mLeash,
- new Point());
- final InsetsSourceControl ime = new InsetsSourceControl(ITYPE_IME, mLeash, new Point());
+ final InsetsSourceControl navBar = createControl(ITYPE_NAVIGATION_BAR);
+ final InsetsSourceControl statusBar = createControl(ITYPE_STATUS_BAR);
+ final InsetsSourceControl ime = createControl(ITYPE_IME);
InsetsSourceControl[] controls = new InsetsSourceControl[3];
controls[0] = navBar;
diff --git a/core/tests/coretests/src/android/view/PendingInsetsControllerTest.java b/core/tests/coretests/src/android/view/PendingInsetsControllerTest.java
index 9787b77..33f859e 100644
--- a/core/tests/coretests/src/android/view/PendingInsetsControllerTest.java
+++ b/core/tests/coretests/src/android/view/PendingInsetsControllerTest.java
@@ -20,25 +20,28 @@
import static android.view.WindowInsets.Type.systemBars;
import static android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS;
import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
+
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import android.os.CancellationSignal;
import android.platform.test.annotations.Presubmit;
+import android.view.WindowInsetsController.OnControllableInsetsChangedListener;
import android.view.animation.LinearInterpolator;
+import androidx.test.runner.AndroidJUnit4;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import androidx.test.runner.AndroidJUnit4;
-
/**
* Tests for {@link PendingInsetsControllerTest}.
*
@@ -93,10 +96,11 @@
public void testControl() {
WindowInsetsAnimationControlListener listener =
mock(WindowInsetsAnimationControlListener.class);
- CancellationSignal signal = mPendingInsetsController.controlWindowInsetsAnimation(
- systemBars(), 0, new LinearInterpolator(), listener);
+ CancellationSignal cancellationSignal = new CancellationSignal();
+ mPendingInsetsController.controlWindowInsetsAnimation(
+ systemBars(), 0, new LinearInterpolator(), cancellationSignal, listener);
verify(listener).onCancelled();
- assertTrue(signal.isCanceled());
+ assertFalse(cancellationSignal.isCanceled());
}
@Test
@@ -104,10 +108,11 @@
WindowInsetsAnimationControlListener listener =
mock(WindowInsetsAnimationControlListener.class);
mPendingInsetsController.replayAndAttach(mReplayedController);
- mPendingInsetsController.controlWindowInsetsAnimation(
- systemBars(), 0L, new LinearInterpolator(), listener);
+ CancellationSignal cancellationSignal = new CancellationSignal();
+ mPendingInsetsController.controlWindowInsetsAnimation(systemBars(), 0L,
+ new LinearInterpolator(), cancellationSignal, listener);
verify(mReplayedController).controlWindowInsetsAnimation(eq(systemBars()), eq(0L), any(),
- eq(listener));
+ eq(cancellationSignal), eq(listener));
}
@Test
@@ -163,11 +168,43 @@
}
@Test
+ public void testAddOnControllableInsetsChangedListener() {
+ OnControllableInsetsChangedListener listener =
+ mock(OnControllableInsetsChangedListener.class);
+ mPendingInsetsController.addOnControllableInsetsChangedListener(listener);
+ mPendingInsetsController.replayAndAttach(mReplayedController);
+ verify(mReplayedController).addOnControllableInsetsChangedListener(eq(listener));
+ verify(listener).onControllableInsetsChanged(eq(mPendingInsetsController), eq(0));
+ }
+
+ @Test
+ public void testAddRemoveControllableInsetsChangedListener() {
+ OnControllableInsetsChangedListener listener =
+ mock(OnControllableInsetsChangedListener.class);
+ mPendingInsetsController.addOnControllableInsetsChangedListener(listener);
+ mPendingInsetsController.removeOnControllableInsetsChangedListener(listener);
+ mPendingInsetsController.replayAndAttach(mReplayedController);
+ verify(mReplayedController, never()).addOnControllableInsetsChangedListener(any());
+ verify(listener).onControllableInsetsChanged(eq(mPendingInsetsController), eq(0));
+ }
+
+ @Test
+ public void testAddOnControllableInsetsChangedListener_direct() {
+ mPendingInsetsController.replayAndAttach(mReplayedController);
+ OnControllableInsetsChangedListener listener =
+ mock(OnControllableInsetsChangedListener.class);
+ mPendingInsetsController.addOnControllableInsetsChangedListener(listener);
+ verify(mReplayedController).addOnControllableInsetsChangedListener(eq(listener));
+ }
+
+ @Test
public void testReplayTwice() {
mPendingInsetsController.show(systemBars());
mPendingInsetsController.setSystemBarsBehavior(BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
mPendingInsetsController.setSystemBarsAppearance(APPEARANCE_LIGHT_STATUS_BARS,
APPEARANCE_LIGHT_STATUS_BARS);
+ mPendingInsetsController.addOnControllableInsetsChangedListener(
+ (controller, typeMask) -> {});
mPendingInsetsController.replayAndAttach(mReplayedController);
InsetsController secondController = mock(InsetsController.class);
mPendingInsetsController.replayAndAttach(secondController);
diff --git a/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java b/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
index 02a88fc..5ea0718 100644
--- a/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
+++ b/core/tests/coretests/src/android/view/contentcapture/ContentCaptureSessionTest.java
@@ -20,6 +20,7 @@
import static org.testng.Assert.assertThrows;
+import android.graphics.Insets;
import android.view.View;
import android.view.ViewStructure;
import android.view.autofill.AutofillId;
@@ -172,6 +173,11 @@
}
@Override
+ void internalNotifyViewInsetsChanged(Insets viewInsets) {
+ throw new UnsupportedOperationException("should not have been called");
+ }
+
+ @Override
public void updateContentCaptureContext(ContentCaptureContext context) {
throw new UnsupportedOperationException("should not have been called");
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/ActionsModelParamsSupplierTest.java b/core/tests/coretests/src/android/view/textclassifier/ActionsModelParamsSupplierTest.java
deleted file mode 100644
index 8744997..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/ActionsModelParamsSupplierTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.Locale;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class ActionsModelParamsSupplierTest {
-
- @Test
- public void getSerializedPreconditions_validActionsModelParams() {
- ModelFileManager.ModelFile modelFile = new ModelFileManager.ModelFile(
- new File("/model/file"),
- 200 /* version */,
- Collections.singletonList(Locale.forLanguageTag("en")),
- "en",
- false);
- byte[] serializedPreconditions = new byte[]{0x12, 0x24, 0x36};
- ActionsModelParamsSupplier.ActionsModelParams params =
- new ActionsModelParamsSupplier.ActionsModelParams(
- 200 /* version */,
- "en",
- serializedPreconditions);
-
- byte[] actual = params.getSerializedPreconditions(modelFile);
-
- assertThat(actual).isEqualTo(serializedPreconditions);
- }
-
- @Test
- public void getSerializedPreconditions_invalidVersion() {
- ModelFileManager.ModelFile modelFile = new ModelFileManager.ModelFile(
- new File("/model/file"),
- 201 /* version */,
- Collections.singletonList(Locale.forLanguageTag("en")),
- "en",
- false);
- byte[] serializedPreconditions = new byte[]{0x12, 0x24, 0x36};
- ActionsModelParamsSupplier.ActionsModelParams params =
- new ActionsModelParamsSupplier.ActionsModelParams(
- 200 /* version */,
- "en",
- serializedPreconditions);
-
- byte[] actual = params.getSerializedPreconditions(modelFile);
-
- assertThat(actual).isNull();
- }
-
- @Test
- public void getSerializedPreconditions_invalidLocales() {
- final String LANGUAGE_TAG = "zh";
- ModelFileManager.ModelFile modelFile = new ModelFileManager.ModelFile(
- new File("/model/file"),
- 200 /* version */,
- Collections.singletonList(Locale.forLanguageTag(LANGUAGE_TAG)),
- LANGUAGE_TAG,
- false);
- byte[] serializedPreconditions = new byte[]{0x12, 0x24, 0x36};
- ActionsModelParamsSupplier.ActionsModelParams params =
- new ActionsModelParamsSupplier.ActionsModelParams(
- 200 /* version */,
- "en",
- serializedPreconditions);
-
- byte[] actual = params.getSerializedPreconditions(modelFile);
-
- assertThat(actual).isNull();
- }
-
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java b/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
deleted file mode 100644
index ec7e83f..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier;
-
-import static android.view.textclassifier.ConversationActions.Message.PERSON_USER_OTHERS;
-import static android.view.textclassifier.ConversationActions.Message.PERSON_USER_SELF;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.app.PendingIntent;
-import android.app.Person;
-import android.app.RemoteAction;
-import android.content.ComponentName;
-import android.content.Intent;
-import android.graphics.drawable.Icon;
-import android.net.Uri;
-import android.os.Bundle;
-import android.view.textclassifier.intent.LabeledIntent;
-import android.view.textclassifier.intent.TemplateIntentFactory;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.google.android.textclassifier.ActionsSuggestionsModel;
-import com.google.android.textclassifier.RemoteActionTemplate;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.time.Instant;
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.function.Function;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class ActionsSuggestionsHelperTest {
- private static final String LOCALE_TAG = Locale.US.toLanguageTag();
- private static final Function<CharSequence, String> LANGUAGE_DETECTOR =
- charSequence -> LOCALE_TAG;
-
- @Test
- public void testToNativeMessages_emptyInput() {
- ActionsSuggestionsModel.ConversationMessage[] conversationMessages =
- ActionsSuggestionsHelper.toNativeMessages(
- Collections.emptyList(), LANGUAGE_DETECTOR);
-
- assertThat(conversationMessages).isEmpty();
- }
-
- @Test
- public void testToNativeMessages_noTextMessages() {
- ConversationActions.Message messageWithoutText =
- new ConversationActions.Message.Builder(PERSON_USER_OTHERS).build();
-
- ActionsSuggestionsModel.ConversationMessage[] conversationMessages =
- ActionsSuggestionsHelper.toNativeMessages(
- Collections.singletonList(messageWithoutText), LANGUAGE_DETECTOR);
-
- assertThat(conversationMessages).isEmpty();
- }
-
- @Test
- public void testToNativeMessages_userIdEncoding() {
- Person userA = new Person.Builder().setName("userA").build();
- Person userB = new Person.Builder().setName("userB").build();
-
- ConversationActions.Message firstMessage =
- new ConversationActions.Message.Builder(userB)
- .setText("first")
- .build();
- ConversationActions.Message secondMessage =
- new ConversationActions.Message.Builder(userA)
- .setText("second")
- .build();
- ConversationActions.Message thirdMessage =
- new ConversationActions.Message.Builder(PERSON_USER_SELF)
- .setText("third")
- .build();
- ConversationActions.Message fourthMessage =
- new ConversationActions.Message.Builder(userA)
- .setText("fourth")
- .build();
-
- ActionsSuggestionsModel.ConversationMessage[] conversationMessages =
- ActionsSuggestionsHelper.toNativeMessages(
- Arrays.asList(firstMessage, secondMessage, thirdMessage, fourthMessage),
- LANGUAGE_DETECTOR);
-
- assertThat(conversationMessages).hasLength(4);
- assertNativeMessage(conversationMessages[0], firstMessage.getText(), 2, 0);
- assertNativeMessage(conversationMessages[1], secondMessage.getText(), 1, 0);
- assertNativeMessage(conversationMessages[2], thirdMessage.getText(), 0, 0);
- assertNativeMessage(conversationMessages[3], fourthMessage.getText(), 1, 0);
- }
-
- @Test
- public void testToNativeMessages_referenceTime() {
- ConversationActions.Message firstMessage =
- new ConversationActions.Message.Builder(PERSON_USER_OTHERS)
- .setText("first")
- .setReferenceTime(createZonedDateTimeFromMsUtc(1000))
- .build();
- ConversationActions.Message secondMessage =
- new ConversationActions.Message.Builder(PERSON_USER_OTHERS)
- .setText("second")
- .build();
- ConversationActions.Message thirdMessage =
- new ConversationActions.Message.Builder(PERSON_USER_OTHERS)
- .setText("third")
- .setReferenceTime(createZonedDateTimeFromMsUtc(2000))
- .build();
-
- ActionsSuggestionsModel.ConversationMessage[] conversationMessages =
- ActionsSuggestionsHelper.toNativeMessages(
- Arrays.asList(firstMessage, secondMessage, thirdMessage),
- LANGUAGE_DETECTOR);
-
- assertThat(conversationMessages).hasLength(3);
- assertNativeMessage(conversationMessages[0], firstMessage.getText(), 1, 1000);
- assertNativeMessage(conversationMessages[1], secondMessage.getText(), 1, 0);
- assertNativeMessage(conversationMessages[2], thirdMessage.getText(), 1, 2000);
- }
-
- @Test
- public void testDeduplicateActions() {
- Bundle phoneExtras = new Bundle();
- Intent phoneIntent = new Intent();
- phoneIntent.setComponent(new ComponentName("phone", "intent"));
- ExtrasUtils.putActionIntent(phoneExtras, phoneIntent);
-
- Bundle anotherPhoneExtras = new Bundle();
- Intent anotherPhoneIntent = new Intent();
- anotherPhoneIntent.setComponent(new ComponentName("phone", "another.intent"));
- ExtrasUtils.putActionIntent(anotherPhoneExtras, anotherPhoneIntent);
-
- Bundle urlExtras = new Bundle();
- Intent urlIntent = new Intent();
- urlIntent.setComponent(new ComponentName("url", "intent"));
- ExtrasUtils.putActionIntent(urlExtras, urlIntent);
-
- PendingIntent pendingIntent = PendingIntent.getActivity(
- InstrumentationRegistry.getTargetContext(),
- 0,
- phoneIntent,
- 0);
- Icon icon = Icon.createWithData(new byte[0], 0, 0);
- ConversationAction action =
- new ConversationAction.Builder(ConversationAction.TYPE_CALL_PHONE)
- .setAction(new RemoteAction(icon, "label", "1", pendingIntent))
- .setExtras(phoneExtras)
- .build();
- ConversationAction actionWithSameLabel =
- new ConversationAction.Builder(ConversationAction.TYPE_CALL_PHONE)
- .setAction(new RemoteAction(
- icon, "label", "2", pendingIntent))
- .setExtras(phoneExtras)
- .build();
- ConversationAction actionWithSamePackageButDifferentClass =
- new ConversationAction.Builder(ConversationAction.TYPE_CALL_PHONE)
- .setAction(new RemoteAction(
- icon, "label", "3", pendingIntent))
- .setExtras(anotherPhoneExtras)
- .build();
- ConversationAction actionWithDifferentLabel =
- new ConversationAction.Builder(ConversationAction.TYPE_CALL_PHONE)
- .setAction(new RemoteAction(
- icon, "another_label", "4", pendingIntent))
- .setExtras(phoneExtras)
- .build();
- ConversationAction actionWithDifferentPackage =
- new ConversationAction.Builder(ConversationAction.TYPE_OPEN_URL)
- .setAction(new RemoteAction(icon, "label", "5", pendingIntent))
- .setExtras(urlExtras)
- .build();
- ConversationAction actionWithoutRemoteAction =
- new ConversationAction.Builder(ConversationAction.TYPE_CREATE_REMINDER)
- .build();
-
- List<ConversationAction> conversationActions =
- ActionsSuggestionsHelper.removeActionsWithDuplicates(
- Arrays.asList(action, actionWithSameLabel,
- actionWithSamePackageButDifferentClass, actionWithDifferentLabel,
- actionWithDifferentPackage, actionWithoutRemoteAction));
-
- assertThat(conversationActions).hasSize(3);
- assertThat(conversationActions.get(0).getAction().getContentDescription()).isEqualTo("4");
- assertThat(conversationActions.get(1).getAction().getContentDescription()).isEqualTo("5");
- assertThat(conversationActions.get(2).getAction()).isNull();
- }
-
- @Test
- public void testDeduplicateActions_nullComponent() {
- Bundle phoneExtras = new Bundle();
- Intent phoneIntent = new Intent(Intent.ACTION_DIAL);
- ExtrasUtils.putActionIntent(phoneExtras, phoneIntent);
- PendingIntent pendingIntent = PendingIntent.getActivity(
- InstrumentationRegistry.getTargetContext(),
- 0,
- phoneIntent,
- 0);
- Icon icon = Icon.createWithData(new byte[0], 0, 0);
- ConversationAction action =
- new ConversationAction.Builder(ConversationAction.TYPE_CALL_PHONE)
- .setAction(new RemoteAction(icon, "label", "1", pendingIntent))
- .setExtras(phoneExtras)
- .build();
- ConversationAction actionWithSameLabel =
- new ConversationAction.Builder(ConversationAction.TYPE_CALL_PHONE)
- .setAction(new RemoteAction(
- icon, "label", "2", pendingIntent))
- .setExtras(phoneExtras)
- .build();
-
- List<ConversationAction> conversationActions =
- ActionsSuggestionsHelper.removeActionsWithDuplicates(
- Arrays.asList(action, actionWithSameLabel));
-
- assertThat(conversationActions).isEmpty();
- }
-
- @Test
- public void createLabeledIntentResult_null() {
- ActionsSuggestionsModel.ActionSuggestion nativeSuggestion =
- new ActionsSuggestionsModel.ActionSuggestion(
- "text",
- ConversationAction.TYPE_OPEN_URL,
- 1.0f,
- null,
- null,
- null
- );
-
- LabeledIntent.Result labeledIntentResult =
- ActionsSuggestionsHelper.createLabeledIntentResult(
- InstrumentationRegistry.getTargetContext(),
- new TemplateIntentFactory(),
- nativeSuggestion);
-
- assertThat(labeledIntentResult).isNull();
- }
-
- @Test
- public void createLabeledIntentResult_emptyList() {
- ActionsSuggestionsModel.ActionSuggestion nativeSuggestion =
- new ActionsSuggestionsModel.ActionSuggestion(
- "text",
- ConversationAction.TYPE_OPEN_URL,
- 1.0f,
- null,
- null,
- new RemoteActionTemplate[0]
- );
-
- LabeledIntent.Result labeledIntentResult =
- ActionsSuggestionsHelper.createLabeledIntentResult(
- InstrumentationRegistry.getTargetContext(),
- new TemplateIntentFactory(),
- nativeSuggestion);
-
- assertThat(labeledIntentResult).isNull();
- }
-
- @Test
- public void createLabeledIntentResult() {
- ActionsSuggestionsModel.ActionSuggestion nativeSuggestion =
- new ActionsSuggestionsModel.ActionSuggestion(
- "text",
- ConversationAction.TYPE_OPEN_URL,
- 1.0f,
- null,
- null,
- new RemoteActionTemplate[]{
- new RemoteActionTemplate(
- "title",
- null,
- "description",
- null,
- Intent.ACTION_VIEW,
- Uri.parse("http://www.android.com").toString(),
- null,
- 0,
- null,
- null,
- null,
- 0)});
-
- LabeledIntent.Result labeledIntentResult =
- ActionsSuggestionsHelper.createLabeledIntentResult(
- InstrumentationRegistry.getTargetContext(),
- new TemplateIntentFactory(),
- nativeSuggestion);
-
- assertThat(labeledIntentResult.remoteAction.getTitle()).isEqualTo("title");
- assertThat(labeledIntentResult.resolvedIntent.getAction()).isEqualTo(Intent.ACTION_VIEW);
- }
-
- private ZonedDateTime createZonedDateTimeFromMsUtc(long msUtc) {
- return ZonedDateTime.ofInstant(Instant.ofEpochMilli(msUtc), ZoneId.of("UTC"));
- }
-
- private static void assertNativeMessage(
- ActionsSuggestionsModel.ConversationMessage nativeMessage,
- CharSequence text,
- int userId,
- long referenceTimeInMsUtc) {
- assertThat(nativeMessage.getText()).isEqualTo(text.toString());
- assertThat(nativeMessage.getUserId()).isEqualTo(userId);
- assertThat(nativeMessage.getDetectedTextLanguageTags()).isEqualTo(LOCALE_TAG);
- assertThat(nativeMessage.getReferenceTimeMsUtc()).isEqualTo(referenceTimeInMsUtc);
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/ModelFileManagerTest.java b/core/tests/coretests/src/android/view/textclassifier/ModelFileManagerTest.java
deleted file mode 100644
index 79e1406..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/ModelFileManagerTest.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.Mockito.when;
-
-import android.os.LocaleList;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class ModelFileManagerTest {
- private static final Locale DEFAULT_LOCALE = Locale.forLanguageTag("en-US");
- @Mock
- private Supplier<List<ModelFileManager.ModelFile>> mModelFileSupplier;
- private ModelFileManager.ModelFileSupplierImpl mModelFileSupplierImpl;
- private ModelFileManager mModelFileManager;
- private File mRootTestDir;
- private File mFactoryModelDir;
- private File mUpdatedModelFile;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- mModelFileManager = new ModelFileManager(mModelFileSupplier);
- mRootTestDir = InstrumentationRegistry.getContext().getCacheDir();
- mFactoryModelDir = new File(mRootTestDir, "factory");
- mUpdatedModelFile = new File(mRootTestDir, "updated.model");
-
- mModelFileSupplierImpl =
- new ModelFileManager.ModelFileSupplierImpl(
- mFactoryModelDir,
- "test\\d.model",
- mUpdatedModelFile,
- fd -> 1,
- fd -> ModelFileManager.ModelFile.LANGUAGE_INDEPENDENT
- );
-
- mRootTestDir.mkdirs();
- mFactoryModelDir.mkdirs();
-
- Locale.setDefault(DEFAULT_LOCALE);
- }
-
- @After
- public void removeTestDir() {
- recursiveDelete(mRootTestDir);
- }
-
- @Test
- public void get() {
- ModelFileManager.ModelFile modelFile =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1, Collections.emptyList(), "", true);
- when(mModelFileSupplier.get()).thenReturn(Collections.singletonList(modelFile));
-
- List<ModelFileManager.ModelFile> modelFiles = mModelFileManager.listModelFiles();
-
- assertThat(modelFiles).hasSize(1);
- assertThat(modelFiles.get(0)).isEqualTo(modelFile);
- }
-
- @Test
- public void findBestModel_versionCode() {
- ModelFileManager.ModelFile olderModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.emptyList(), "", true);
-
- ModelFileManager.ModelFile newerModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 2,
- Collections.emptyList(), "", true);
- when(mModelFileSupplier.get())
- .thenReturn(Arrays.asList(olderModelFile, newerModelFile));
-
- ModelFileManager.ModelFile bestModelFile =
- mModelFileManager.findBestModelFile(LocaleList.getEmptyLocaleList());
-
- assertThat(bestModelFile).isEqualTo(newerModelFile);
- }
-
- @Test
- public void findBestModel_languageDependentModelIsPreferred() {
- Locale locale = Locale.forLanguageTag("ja");
- ModelFileManager.ModelFile languageIndependentModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.emptyList(), "", true);
-
- ModelFileManager.ModelFile languageDependentModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 1,
- Collections.singletonList(locale), locale.toLanguageTag(), false);
- when(mModelFileSupplier.get())
- .thenReturn(
- Arrays.asList(languageIndependentModelFile, languageDependentModelFile));
-
- ModelFileManager.ModelFile bestModelFile =
- mModelFileManager.findBestModelFile(
- LocaleList.forLanguageTags(locale.toLanguageTag()));
- assertThat(bestModelFile).isEqualTo(languageDependentModelFile);
- }
-
- @Test
- public void findBestModel_noMatchedLanguageModel() {
- Locale locale = Locale.forLanguageTag("ja");
- ModelFileManager.ModelFile languageIndependentModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.emptyList(), "", true);
-
- ModelFileManager.ModelFile languageDependentModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 1,
- Collections.singletonList(locale), locale.toLanguageTag(), false);
-
- when(mModelFileSupplier.get())
- .thenReturn(
- Arrays.asList(languageIndependentModelFile, languageDependentModelFile));
-
- ModelFileManager.ModelFile bestModelFile =
- mModelFileManager.findBestModelFile(
- LocaleList.forLanguageTags("zh-hk"));
- assertThat(bestModelFile).isEqualTo(languageIndependentModelFile);
- }
-
- @Test
- public void findBestModel_noMatchedLanguageModel_defaultLocaleModelExists() {
- ModelFileManager.ModelFile languageIndependentModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.emptyList(), "", true);
-
- ModelFileManager.ModelFile languageDependentModelFile =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 1,
- Collections.singletonList(
- DEFAULT_LOCALE), DEFAULT_LOCALE.toLanguageTag(), false);
-
- when(mModelFileSupplier.get())
- .thenReturn(
- Arrays.asList(languageIndependentModelFile, languageDependentModelFile));
-
- ModelFileManager.ModelFile bestModelFile =
- mModelFileManager.findBestModelFile(
- LocaleList.forLanguageTags("zh-hk"));
- assertThat(bestModelFile).isEqualTo(languageIndependentModelFile);
- }
-
- @Test
- public void findBestModel_languageIsMoreImportantThanVersion() {
- ModelFileManager.ModelFile matchButOlderModel =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("fr")), "fr", false);
-
- ModelFileManager.ModelFile mismatchButNewerModel =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 2,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- when(mModelFileSupplier.get())
- .thenReturn(
- Arrays.asList(matchButOlderModel, mismatchButNewerModel));
-
- ModelFileManager.ModelFile bestModelFile =
- mModelFileManager.findBestModelFile(
- LocaleList.forLanguageTags("fr"));
- assertThat(bestModelFile).isEqualTo(matchButOlderModel);
- }
-
- @Test
- public void findBestModel_languageIsMoreImportantThanVersion_bestModelComesFirst() {
- ModelFileManager.ModelFile matchLocaleModel =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- ModelFileManager.ModelFile languageIndependentModel =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 2,
- Collections.emptyList(), "", true);
- when(mModelFileSupplier.get())
- .thenReturn(
- Arrays.asList(matchLocaleModel, languageIndependentModel));
-
- ModelFileManager.ModelFile bestModelFile =
- mModelFileManager.findBestModelFile(
- LocaleList.forLanguageTags("ja"));
-
- assertThat(bestModelFile).isEqualTo(matchLocaleModel);
- }
-
- @Test
- public void modelFileEquals() {
- ModelFileManager.ModelFile modelA =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- ModelFileManager.ModelFile modelB =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- assertThat(modelA).isEqualTo(modelB);
- }
-
- @Test
- public void modelFile_different() {
- ModelFileManager.ModelFile modelA =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- ModelFileManager.ModelFile modelB =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- assertThat(modelA).isNotEqualTo(modelB);
- }
-
-
- @Test
- public void modelFile_getPath() {
- ModelFileManager.ModelFile modelA =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- assertThat(modelA.getPath()).isEqualTo("/path/a");
- }
-
- @Test
- public void modelFile_getName() {
- ModelFileManager.ModelFile modelA =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- assertThat(modelA.getName()).isEqualTo("a");
- }
-
- @Test
- public void modelFile_isPreferredTo_languageDependentIsBetter() {
- ModelFileManager.ModelFile modelA =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 1,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- ModelFileManager.ModelFile modelB =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 2,
- Collections.emptyList(), "", true);
-
- assertThat(modelA.isPreferredTo(modelB)).isTrue();
- }
-
- @Test
- public void modelFile_isPreferredTo_version() {
- ModelFileManager.ModelFile modelA =
- new ModelFileManager.ModelFile(
- new File("/path/a"), 2,
- Collections.singletonList(Locale.forLanguageTag("ja")), "ja", false);
-
- ModelFileManager.ModelFile modelB =
- new ModelFileManager.ModelFile(
- new File("/path/b"), 1,
- Collections.emptyList(), "", false);
-
- assertThat(modelA.isPreferredTo(modelB)).isTrue();
- }
-
- @Test
- public void testFileSupplierImpl_updatedFileOnly() throws IOException {
- mUpdatedModelFile.createNewFile();
- File model1 = new File(mFactoryModelDir, "test1.model");
- model1.createNewFile();
- File model2 = new File(mFactoryModelDir, "test2.model");
- model2.createNewFile();
- new File(mFactoryModelDir, "not_match_regex.model").createNewFile();
-
- List<ModelFileManager.ModelFile> modelFiles = mModelFileSupplierImpl.get();
- List<String> modelFilePaths =
- modelFiles
- .stream()
- .map(modelFile -> modelFile.getPath())
- .collect(Collectors.toList());
-
- assertThat(modelFiles).hasSize(3);
- assertThat(modelFilePaths).containsExactly(
- mUpdatedModelFile.getAbsolutePath(),
- model1.getAbsolutePath(),
- model2.getAbsolutePath());
- }
-
- @Test
- public void testFileSupplierImpl_empty() {
- mFactoryModelDir.delete();
- List<ModelFileManager.ModelFile> modelFiles = mModelFileSupplierImpl.get();
-
- assertThat(modelFiles).hasSize(0);
- }
-
- private static void recursiveDelete(File f) {
- if (f.isDirectory()) {
- for (File innerFile : f.listFiles()) {
- recursiveDelete(innerFile);
- }
- }
- f.delete();
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/SystemTextClassifierMetadataTest.java b/core/tests/coretests/src/android/view/textclassifier/SystemTextClassifierMetadataTest.java
new file mode 100644
index 0000000..e4cfc53
--- /dev/null
+++ b/core/tests/coretests/src/android/view/textclassifier/SystemTextClassifierMetadataTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2020 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.view.textclassifier;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+
+import android.os.Parcel;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class SystemTextClassifierMetadataTest {
+
+ @Test
+ public void testInvalidPackageNameThrowsException() {
+ assertThrows(NullPointerException.class,
+ () -> new SystemTextClassifierMetadata(/* packageName= */ null, /* userId= */
+ 1, /* useDefaultTextClassifier= */ false));
+ }
+
+ @Test
+ public void testParcel() {
+ SystemTextClassifierMetadata sysTcMetadata = new SystemTextClassifierMetadata(
+ "package", /* userId= */ 1, /* useDefaultTextClassifier= */ false);
+
+ Parcel p = Parcel.obtain();
+ sysTcMetadata.writeToParcel(p, 0);
+ p.setDataPosition(0);
+
+ SystemTextClassifierMetadata targetSysTcMetadata =
+ SystemTextClassifierMetadata.CREATOR.createFromParcel(p);
+
+ assertThat(targetSysTcMetadata.getUserId()).isEqualTo(sysTcMetadata.getUserId());
+ assertThat(targetSysTcMetadata.getCallingPackageName()).isEqualTo(
+ sysTcMetadata.getCallingPackageName());
+ assertThat(targetSysTcMetadata.useDefaultTextClassifier()).isEqualTo(
+ sysTcMetadata.useDefaultTextClassifier());
+ }
+}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java
index 82fa73f..2f21b7f 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassificationConstantsTest.java
@@ -16,7 +16,6 @@
package android.view.textclassifier;
-import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import android.provider.DeviceConfig;
@@ -24,8 +23,6 @@
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-import com.google.common.primitives.Floats;
-
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -57,17 +54,17 @@
public void testLoadFromDeviceConfig_IntValue() throws Exception {
// Saves config original value.
final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH);
+ TextClassificationConstants.GENERATE_LINKS_MAX_TEXT_LENGTH);
final TextClassificationConstants constants = new TextClassificationConstants();
try {
// Sets and checks different value.
- setDeviceConfig(TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH, "8");
- assertWithMessage(TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH)
- .that(constants.getSuggestSelectionMaxRangeLength()).isEqualTo(8);
+ setDeviceConfig(TextClassificationConstants.GENERATE_LINKS_MAX_TEXT_LENGTH, "8");
+ assertWithMessage(TextClassificationConstants.GENERATE_LINKS_MAX_TEXT_LENGTH)
+ .that(constants.getGenerateLinksMaxTextLength()).isEqualTo(8);
} finally {
// Restores config original value.
- setDeviceConfig(TextClassificationConstants.SUGGEST_SELECTION_MAX_RANGE_LENGTH,
+ setDeviceConfig(TextClassificationConstants.GENERATE_LINKS_MAX_TEXT_LENGTH,
originalValue);
}
}
@@ -94,61 +91,6 @@
}
}
- @Test
- public void testLoadFromDeviceConfig_FloatValue() throws Exception {
- // Saves config original value.
- final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE);
-
- final TextClassificationConstants constants = new TextClassificationConstants();
- try {
- // Sets and checks different value.
- setDeviceConfig(TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE, "2");
- assertWithMessage(TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE)
- .that(constants.getLangIdThresholdOverride()).isWithin(EPSILON).of(2f);
- } finally {
- // Restores config original value.
- setDeviceConfig(TextClassificationConstants.LANG_ID_THRESHOLD_OVERRIDE, originalValue);
- }
- }
-
- @Test
- public void testLoadFromDeviceConfig_StringList() throws Exception {
- // Saves config original value.
- final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- TextClassificationConstants.ENTITY_LIST_DEFAULT);
-
- final TextClassificationConstants constants = new TextClassificationConstants();
- try {
- // Sets and checks different value.
- setDeviceConfig(TextClassificationConstants.ENTITY_LIST_DEFAULT, "email:url");
- assertWithMessage(TextClassificationConstants.ENTITY_LIST_DEFAULT)
- .that(constants.getEntityListDefault())
- .containsExactly("email", "url");
- } finally {
- // Restores config original value.
- setDeviceConfig(TextClassificationConstants.ENTITY_LIST_DEFAULT, originalValue);
- }
- }
-
- @Test
- public void testLoadFromDeviceConfig_FloatList() throws Exception {
- // Saves config original value.
- final String originalValue = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
- TextClassificationConstants.LANG_ID_CONTEXT_SETTINGS);
-
- final TextClassificationConstants constants = new TextClassificationConstants();
- try {
- // Sets and checks different value.
- setDeviceConfig(TextClassificationConstants.LANG_ID_CONTEXT_SETTINGS, "30:0.5:0.3");
- assertThat(Floats.asList(constants.getLangIdContextSettings())).containsExactly(30f,
- 0.5f, 0.3f).inOrder();
- } finally {
- // Restores config original value.
- setDeviceConfig(TextClassificationConstants.LANG_ID_CONTEXT_SETTINGS, originalValue);
- }
- }
-
private void setDeviceConfig(String key, String value) {
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key,
value, /* makeDefault */ false);
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java
index 1ca4649..628252d 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassificationManagerTest.java
@@ -16,19 +16,15 @@
package android.view.textclassifier;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+
import static org.mockito.Mockito.mock;
import android.content.Context;
-import android.content.Intent;
-import android.os.LocaleList;
-import androidx.test.InstrumentationRegistry;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
@@ -38,14 +34,12 @@
@RunWith(AndroidJUnit4.class)
public class TextClassificationManagerTest {
- private static final LocaleList LOCALES = LocaleList.forLanguageTags("en-US");
-
private Context mContext;
private TextClassificationManager mTcm;
@Before
public void setup() {
- mContext = InstrumentationRegistry.getTargetContext();
+ mContext = ApplicationProvider.getApplicationContext();
mTcm = mContext.getSystemService(TextClassificationManager.class);
}
@@ -53,45 +47,17 @@
public void testSetTextClassifier() {
TextClassifier classifier = mock(TextClassifier.class);
mTcm.setTextClassifier(classifier);
- assertEquals(classifier, mTcm.getTextClassifier());
+ assertThat(mTcm.getTextClassifier()).isEqualTo(classifier);
}
@Test
public void testGetLocalTextClassifier() {
- assertTrue(mTcm.getTextClassifier(TextClassifier.LOCAL) instanceof TextClassifierImpl);
+ assertThat(mTcm.getTextClassifier(TextClassifier.LOCAL)).isSameAs(TextClassifier.NO_OP);
}
@Test
public void testGetSystemTextClassifier() {
- assertTrue(mTcm.getTextClassifier(TextClassifier.SYSTEM) instanceof SystemTextClassifier);
- }
-
- @Test
- public void testCannotResolveIntent() {
- Context fakeContext = new FakeContextBuilder()
- .setAllIntentComponent(FakeContextBuilder.DEFAULT_COMPONENT)
- .setIntentComponent(Intent.ACTION_INSERT_OR_EDIT, null)
- .build();
-
- TextClassifier fallback = TextClassifier.NO_OP;
- TextClassifier classifier = new TextClassifierImpl(
- fakeContext, new TextClassificationConstants(), fallback);
-
- String text = "Contact me at +12122537077";
- String classifiedText = "+12122537077";
- int startIndex = text.indexOf(classifiedText);
- int endIndex = startIndex + classifiedText.length();
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification result = classifier.classifyText(request);
- TextClassification fallbackResult = fallback.classifyText(request);
-
- // classifier should not totally fail in which case it returns a fallback result.
- // It should skip the failing intent and return a result for non-failing intents.
- assertFalse(result.getActions().isEmpty());
- assertNotSame(result, fallbackResult);
+ assertThat(mTcm.getTextClassifier(TextClassifier.SYSTEM))
+ .isInstanceOf(SystemTextClassifier.class);
}
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java
index d544029..39ededa 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextClassificationTest.java
@@ -17,6 +17,7 @@
package android.view.textclassifier;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -199,7 +200,9 @@
.setReferenceTime(referenceTime)
.setExtras(BUNDLE)
.build();
- reference.setCallingPackageName(packageName);
+ final SystemTextClassifierMetadata systemTcMetadata =
+ new SystemTextClassifierMetadata(packageName, 1, false);
+ reference.setSystemTextClassifierMetadata(systemTcMetadata);
// Parcel and unparcel.
final Parcel parcel = Parcel.obtain();
@@ -216,5 +219,11 @@
assertEquals(referenceTime, result.getReferenceTime());
assertEquals(BUNDLE_VALUE, result.getExtras().getString(BUNDLE_KEY));
assertEquals(packageName, result.getCallingPackageName());
+ final SystemTextClassifierMetadata resultSystemTcMetadata =
+ result.getSystemTextClassifierMetadata();
+ assertNotNull(resultSystemTcMetadata);
+ assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+ assertEquals(1, resultSystemTcMetadata.getUserId());
+ assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
}
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java b/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
deleted file mode 100644
index 372a478..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/TextClassifierTest.java
+++ /dev/null
@@ -1,719 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier;
-
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import android.app.RemoteAction;
-import android.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.LocaleList;
-import android.service.textclassifier.TextClassifierService;
-import android.text.Spannable;
-import android.text.SpannableString;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-
-import com.google.common.truth.Truth;
-
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Testing {@link TextClassifierTest} APIs on local and system textclassifier.
- * <p>
- * Tests are skipped if such a textclassifier does not exist.
- */
-@SmallTest
-@RunWith(Parameterized.class)
-public class TextClassifierTest {
- private static final String LOCAL = "local";
- private static final String SESSION = "session";
- private static final String DEFAULT = "default";
-
- // TODO: Add SYSTEM, which tests TextClassifier.SYSTEM.
- @Parameterized.Parameters(name = "{0}")
- public static Iterable<Object> textClassifierTypes() {
- return Arrays.asList(LOCAL, SESSION, DEFAULT);
- }
-
- @Parameterized.Parameter
- public String mTextClassifierType;
-
- private static final TextClassificationConstants TC_CONSTANTS =
- new TextClassificationConstants();
- private static final LocaleList LOCALES = LocaleList.forLanguageTags("en-US");
- private static final String NO_TYPE = null;
-
- private Context mContext;
- private TextClassificationManager mTcm;
- private TextClassifier mClassifier;
-
- @Before
- public void setup() {
- mContext = InstrumentationRegistry.getTargetContext();
- mTcm = mContext.getSystemService(TextClassificationManager.class);
-
- if (mTextClassifierType.equals(LOCAL)) {
- mClassifier = mTcm.getTextClassifier(TextClassifier.LOCAL);
- } else if (mTextClassifierType.equals(SESSION)) {
- mClassifier = mTcm.createTextClassificationSession(
- new TextClassificationContext.Builder(
- "android",
- TextClassifier.WIDGET_TYPE_NOTIFICATION)
- .build(),
- mTcm.getTextClassifier(TextClassifier.LOCAL));
- } else {
- mClassifier = TextClassifierService.getDefaultTextClassifierImplementation(mContext);
- }
- }
-
- @Test
- public void testSuggestSelection() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Contact me at droid@android.com";
- String selected = "droid";
- String suggested = "droid@android.com";
- int startIndex = text.indexOf(selected);
- int endIndex = startIndex + selected.length();
- int smartStartIndex = text.indexOf(suggested);
- int smartEndIndex = smartStartIndex + suggested.length();
- TextSelection.Request request = new TextSelection.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextSelection selection = mClassifier.suggestSelection(request);
- assertThat(selection,
- isTextSelection(smartStartIndex, smartEndIndex, TextClassifier.TYPE_EMAIL));
- }
-
- @Test
- public void testSuggestSelection_url() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Visit http://www.android.com for more information";
- String selected = "http";
- String suggested = "http://www.android.com";
- int startIndex = text.indexOf(selected);
- int endIndex = startIndex + selected.length();
- int smartStartIndex = text.indexOf(suggested);
- int smartEndIndex = smartStartIndex + suggested.length();
- TextSelection.Request request = new TextSelection.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextSelection selection = mClassifier.suggestSelection(request);
- assertThat(selection,
- isTextSelection(smartStartIndex, smartEndIndex, TextClassifier.TYPE_URL));
- }
-
- @Test
- public void testSmartSelection_withEmoji() {
- if (isTextClassifierDisabled()) return;
-
- String text = "\uD83D\uDE02 Hello.";
- String selected = "Hello";
- int startIndex = text.indexOf(selected);
- int endIndex = startIndex + selected.length();
- TextSelection.Request request = new TextSelection.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextSelection selection = mClassifier.suggestSelection(request);
- assertThat(selection,
- isTextSelection(startIndex, endIndex, NO_TYPE));
- }
-
- @Test
- public void testClassifyText() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Contact me at droid@android.com";
- String classifiedText = "droid@android.com";
- int startIndex = text.indexOf(classifiedText);
- int endIndex = startIndex + classifiedText.length();
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = mClassifier.classifyText(request);
- assertThat(classification, isTextClassification(classifiedText, TextClassifier.TYPE_EMAIL));
- }
-
- @Test
- public void testClassifyText_url() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Visit www.android.com for more information";
- String classifiedText = "www.android.com";
- int startIndex = text.indexOf(classifiedText);
- int endIndex = startIndex + classifiedText.length();
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = mClassifier.classifyText(request);
- assertThat(classification, isTextClassification(classifiedText, TextClassifier.TYPE_URL));
- assertThat(classification, containsIntentWithAction(Intent.ACTION_VIEW));
- }
-
- @Test
- public void testClassifyText_address() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Brandschenkestrasse 110, Zürich, Switzerland";
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, 0, text.length())
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = mClassifier.classifyText(request);
- assertThat(classification, isTextClassification(text, TextClassifier.TYPE_ADDRESS));
- }
-
- @Test
- public void testClassifyText_url_inCaps() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Visit HTTP://ANDROID.COM for more information";
- String classifiedText = "HTTP://ANDROID.COM";
- int startIndex = text.indexOf(classifiedText);
- int endIndex = startIndex + classifiedText.length();
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = mClassifier.classifyText(request);
- assertThat(classification, isTextClassification(classifiedText, TextClassifier.TYPE_URL));
- assertThat(classification, containsIntentWithAction(Intent.ACTION_VIEW));
- }
-
- @Test
- public void testClassifyText_date() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Let's meet on January 9, 2018.";
- String classifiedText = "January 9, 2018";
- int startIndex = text.indexOf(classifiedText);
- int endIndex = startIndex + classifiedText.length();
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = mClassifier.classifyText(request);
- assertThat(classification, isTextClassification(classifiedText, TextClassifier.TYPE_DATE));
- Bundle extras = classification.getExtras();
- List<Bundle> entities = ExtrasUtils.getEntities(extras);
- Truth.assertThat(entities).hasSize(1);
- Bundle entity = entities.get(0);
- Truth.assertThat(ExtrasUtils.getEntityType(entity)).isEqualTo(TextClassifier.TYPE_DATE);
- }
-
- @Test
- public void testClassifyText_datetime() {
- if (isTextClassifierDisabled()) return;
-
- String text = "Let's meet 2018/01/01 10:30:20.";
- String classifiedText = "2018/01/01 10:30:20";
- int startIndex = text.indexOf(classifiedText);
- int endIndex = startIndex + classifiedText.length();
- TextClassification.Request request = new TextClassification.Request.Builder(
- text, startIndex, endIndex)
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = mClassifier.classifyText(request);
- assertThat(classification,
- isTextClassification(classifiedText, TextClassifier.TYPE_DATE_TIME));
- }
-
- @Test
- public void testClassifyText_foreignText() {
- LocaleList originalLocales = LocaleList.getDefault();
- LocaleList.setDefault(LocaleList.forLanguageTags("en"));
- String japaneseText = "これは日本語のテキストです";
-
- Context context = new FakeContextBuilder()
- .setIntentComponent(Intent.ACTION_TRANSLATE, FakeContextBuilder.DEFAULT_COMPONENT)
- .build();
- TextClassifier classifier = new TextClassifierImpl(context, TC_CONSTANTS);
- TextClassification.Request request = new TextClassification.Request.Builder(
- japaneseText, 0, japaneseText.length())
- .setDefaultLocales(LOCALES)
- .build();
-
- TextClassification classification = classifier.classifyText(request);
- RemoteAction translateAction = classification.getActions().get(0);
- assertEquals(1, classification.getActions().size());
- assertEquals(
- context.getString(com.android.internal.R.string.translate),
- translateAction.getTitle());
-
- assertEquals(translateAction, ExtrasUtils.findTranslateAction(classification));
- Intent intent = ExtrasUtils.getActionsIntents(classification).get(0);
- assertEquals(Intent.ACTION_TRANSLATE, intent.getAction());
- Bundle foreignLanguageInfo = ExtrasUtils.getForeignLanguageExtra(classification);
- assertEquals("ja", ExtrasUtils.getEntityType(foreignLanguageInfo));
- assertTrue(ExtrasUtils.getScore(foreignLanguageInfo) >= 0);
- assertTrue(ExtrasUtils.getScore(foreignLanguageInfo) <= 1);
- assertTrue(intent.hasExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER));
- assertEquals("ja", ExtrasUtils.getTopLanguage(intent).getLanguage());
-
- LocaleList.setDefault(originalLocales);
- }
-
- @Test
- public void testGenerateLinks_phone() {
- if (isTextClassifierDisabled()) return;
- String text = "The number is +12122537077. See you tonight!";
- TextLinks.Request request = new TextLinks.Request.Builder(text).build();
- assertThat(mClassifier.generateLinks(request),
- isTextLinksContaining(text, "+12122537077", TextClassifier.TYPE_PHONE));
- }
-
- @Test
- public void testGenerateLinks_exclude() {
- if (isTextClassifierDisabled()) return;
- String text = "You want apple@banana.com. See you tonight!";
- List<String> hints = Collections.EMPTY_LIST;
- List<String> included = Collections.EMPTY_LIST;
- List<String> excluded = Arrays.asList(TextClassifier.TYPE_EMAIL);
- TextLinks.Request request = new TextLinks.Request.Builder(text)
- .setEntityConfig(TextClassifier.EntityConfig.create(hints, included, excluded))
- .setDefaultLocales(LOCALES)
- .build();
- assertThat(mClassifier.generateLinks(request),
- not(isTextLinksContaining(text, "apple@banana.com", TextClassifier.TYPE_EMAIL)));
- }
-
- @Test
- public void testGenerateLinks_explicit_address() {
- if (isTextClassifierDisabled()) return;
- String text = "The address is 1600 Amphitheater Parkway, Mountain View, CA. See you!";
- List<String> explicit = Arrays.asList(TextClassifier.TYPE_ADDRESS);
- TextLinks.Request request = new TextLinks.Request.Builder(text)
- .setEntityConfig(TextClassifier.EntityConfig.createWithExplicitEntityList(explicit))
- .setDefaultLocales(LOCALES)
- .build();
- assertThat(mClassifier.generateLinks(request),
- isTextLinksContaining(text, "1600 Amphitheater Parkway, Mountain View, CA",
- TextClassifier.TYPE_ADDRESS));
- }
-
- @Test
- public void testGenerateLinks_exclude_override() {
- if (isTextClassifierDisabled()) return;
- String text = "You want apple@banana.com. See you tonight!";
- List<String> hints = Collections.EMPTY_LIST;
- List<String> included = Arrays.asList(TextClassifier.TYPE_EMAIL);
- List<String> excluded = Arrays.asList(TextClassifier.TYPE_EMAIL);
- TextLinks.Request request = new TextLinks.Request.Builder(text)
- .setEntityConfig(TextClassifier.EntityConfig.create(hints, included, excluded))
- .setDefaultLocales(LOCALES)
- .build();
- assertThat(mClassifier.generateLinks(request),
- not(isTextLinksContaining(text, "apple@banana.com", TextClassifier.TYPE_EMAIL)));
- }
-
- @Test
- public void testGenerateLinks_maxLength() {
- if (isTextClassifierDisabled()) return;
- char[] manySpaces = new char[mClassifier.getMaxGenerateLinksTextLength()];
- Arrays.fill(manySpaces, ' ');
- TextLinks.Request request = new TextLinks.Request.Builder(new String(manySpaces)).build();
- TextLinks links = mClassifier.generateLinks(request);
- assertTrue(links.getLinks().isEmpty());
- }
-
- @Test
- public void testApplyLinks_unsupportedCharacter() {
- if (isTextClassifierDisabled()) return;
- Spannable url = new SpannableString("\u202Emoc.diordna.com");
- TextLinks.Request request = new TextLinks.Request.Builder(url).build();
- assertEquals(
- TextLinks.STATUS_UNSUPPORTED_CHARACTER,
- mClassifier.generateLinks(request).apply(url, 0, null));
- }
-
- @Test
- public void testGenerateLinks_tooLong() {
- if (isTextClassifierDisabled()) return;
- char[] manySpaces = new char[mClassifier.getMaxGenerateLinksTextLength() + 1];
- Arrays.fill(manySpaces, ' ');
- TextLinks.Request request = new TextLinks.Request.Builder(new String(manySpaces)).build();
- TextLinks links = mClassifier.generateLinks(request);
- assertTrue(links.getLinks().isEmpty());
- }
-
- @Test
- public void testGenerateLinks_entityData() {
- if (isTextClassifierDisabled()) return;
- String text = "The number is +12122537077.";
- Bundle extras = new Bundle();
- ExtrasUtils.putIsSerializedEntityDataEnabled(extras, true);
- TextLinks.Request request = new TextLinks.Request.Builder(text).setExtras(extras).build();
-
- TextLinks textLinks = mClassifier.generateLinks(request);
-
- Truth.assertThat(textLinks.getLinks()).hasSize(1);
- TextLinks.TextLink textLink = textLinks.getLinks().iterator().next();
- List<Bundle> entities = ExtrasUtils.getEntities(textLink.getExtras());
- Truth.assertThat(entities).hasSize(1);
- Bundle entity = entities.get(0);
- Truth.assertThat(ExtrasUtils.getEntityType(entity)).isEqualTo(TextClassifier.TYPE_PHONE);
- }
-
- @Test
- public void testGenerateLinks_entityData_disabled() {
- if (isTextClassifierDisabled()) return;
- String text = "The number is +12122537077.";
- TextLinks.Request request = new TextLinks.Request.Builder(text).build();
-
- TextLinks textLinks = mClassifier.generateLinks(request);
-
- Truth.assertThat(textLinks.getLinks()).hasSize(1);
- TextLinks.TextLink textLink = textLinks.getLinks().iterator().next();
- List<Bundle> entities = ExtrasUtils.getEntities(textLink.getExtras());
- Truth.assertThat(entities).isNull();
- }
-
- @Test
- public void testDetectLanguage() {
- if (isTextClassifierDisabled()) return;
- String text = "This is English text";
- TextLanguage.Request request = new TextLanguage.Request.Builder(text).build();
- TextLanguage textLanguage = mClassifier.detectLanguage(request);
- assertThat(textLanguage, isTextLanguage("en"));
- }
-
- @Test
- public void testDetectLanguage_japanese() {
- if (isTextClassifierDisabled()) return;
- String text = "これは日本語のテキストです";
- TextLanguage.Request request = new TextLanguage.Request.Builder(text).build();
- TextLanguage textLanguage = mClassifier.detectLanguage(request);
- assertThat(textLanguage, isTextLanguage("ja"));
- }
-
- @Ignore // Doesn't work without a language-based model.
- @Test
- public void testSuggestConversationActions_textReplyOnly_maxOne() {
- if (isTextClassifierDisabled()) return;
- ConversationActions.Message message =
- new ConversationActions.Message.Builder(
- ConversationActions.Message.PERSON_USER_OTHERS)
- .setText("Where are you?")
- .build();
- TextClassifier.EntityConfig typeConfig =
- new TextClassifier.EntityConfig.Builder().includeTypesFromTextClassifier(false)
- .setIncludedTypes(
- Collections.singletonList(ConversationAction.TYPE_TEXT_REPLY))
- .build();
- ConversationActions.Request request =
- new ConversationActions.Request.Builder(Collections.singletonList(message))
- .setMaxSuggestions(1)
- .setTypeConfig(typeConfig)
- .build();
-
- ConversationActions conversationActions = mClassifier.suggestConversationActions(request);
- Truth.assertThat(conversationActions.getConversationActions()).hasSize(1);
- ConversationAction conversationAction = conversationActions.getConversationActions().get(0);
- Truth.assertThat(conversationAction.getType()).isEqualTo(
- ConversationAction.TYPE_TEXT_REPLY);
- Truth.assertThat(conversationAction.getTextReply()).isNotNull();
- }
-
- @Ignore // Doesn't work without a language-based model.
- @Test
- public void testSuggestConversationActions_textReplyOnly_noMax() {
- if (isTextClassifierDisabled()) return;
- ConversationActions.Message message =
- new ConversationActions.Message.Builder(
- ConversationActions.Message.PERSON_USER_OTHERS)
- .setText("Where are you?")
- .build();
- TextClassifier.EntityConfig typeConfig =
- new TextClassifier.EntityConfig.Builder().includeTypesFromTextClassifier(false)
- .setIncludedTypes(
- Collections.singletonList(ConversationAction.TYPE_TEXT_REPLY))
- .build();
- ConversationActions.Request request =
- new ConversationActions.Request.Builder(Collections.singletonList(message))
- .setTypeConfig(typeConfig)
- .build();
-
- ConversationActions conversationActions = mClassifier.suggestConversationActions(request);
- assertTrue(conversationActions.getConversationActions().size() > 1);
- for (ConversationAction conversationAction :
- conversationActions.getConversationActions()) {
- assertThat(conversationAction,
- isConversationAction(ConversationAction.TYPE_TEXT_REPLY));
- }
- }
-
- @Test
- public void testSuggestConversationActions_openUrl() {
- if (isTextClassifierDisabled()) return;
- ConversationActions.Message message =
- new ConversationActions.Message.Builder(
- ConversationActions.Message.PERSON_USER_OTHERS)
- .setText("Check this out: https://www.android.com")
- .build();
- TextClassifier.EntityConfig typeConfig =
- new TextClassifier.EntityConfig.Builder().includeTypesFromTextClassifier(false)
- .setIncludedTypes(
- Collections.singletonList(ConversationAction.TYPE_OPEN_URL))
- .build();
- ConversationActions.Request request =
- new ConversationActions.Request.Builder(Collections.singletonList(message))
- .setMaxSuggestions(1)
- .setTypeConfig(typeConfig)
- .build();
-
- ConversationActions conversationActions = mClassifier.suggestConversationActions(request);
- Truth.assertThat(conversationActions.getConversationActions()).hasSize(1);
- ConversationAction conversationAction = conversationActions.getConversationActions().get(0);
- Truth.assertThat(conversationAction.getType()).isEqualTo(ConversationAction.TYPE_OPEN_URL);
- Intent actionIntent = ExtrasUtils.getActionIntent(conversationAction.getExtras());
- Truth.assertThat(actionIntent.getAction()).isEqualTo(Intent.ACTION_VIEW);
- Truth.assertThat(actionIntent.getData()).isEqualTo(Uri.parse("https://www.android.com"));
- }
-
- @Ignore // Doesn't work without a language-based model.
- @Test
- public void testSuggestConversationActions_copy() {
- if (isTextClassifierDisabled()) return;
- ConversationActions.Message message =
- new ConversationActions.Message.Builder(
- ConversationActions.Message.PERSON_USER_OTHERS)
- .setText("Authentication code: 12345")
- .build();
- TextClassifier.EntityConfig typeConfig =
- new TextClassifier.EntityConfig.Builder().includeTypesFromTextClassifier(false)
- .setIncludedTypes(
- Collections.singletonList(ConversationAction.TYPE_COPY))
- .build();
- ConversationActions.Request request =
- new ConversationActions.Request.Builder(Collections.singletonList(message))
- .setMaxSuggestions(1)
- .setTypeConfig(typeConfig)
- .build();
-
- ConversationActions conversationActions = mClassifier.suggestConversationActions(request);
- Truth.assertThat(conversationActions.getConversationActions()).hasSize(1);
- ConversationAction conversationAction = conversationActions.getConversationActions().get(0);
- Truth.assertThat(conversationAction.getType()).isEqualTo(ConversationAction.TYPE_COPY);
- Truth.assertThat(conversationAction.getTextReply()).isAnyOf(null, "");
- Truth.assertThat(conversationAction.getAction()).isNull();
- String code = ExtrasUtils.getCopyText(conversationAction.getExtras());
- Truth.assertThat(code).isEqualTo("12345");
- Truth.assertThat(
- ExtrasUtils.getSerializedEntityData(conversationAction.getExtras())).isNotEmpty();
- }
-
- @Test
- public void testSuggestConversationActions_deduplicate() {
- Context context = new FakeContextBuilder()
- .setIntentComponent(Intent.ACTION_SENDTO, FakeContextBuilder.DEFAULT_COMPONENT)
- .build();
- ConversationActions.Message message =
- new ConversationActions.Message.Builder(
- ConversationActions.Message.PERSON_USER_OTHERS)
- .setText("a@android.com b@android.com")
- .build();
- ConversationActions.Request request =
- new ConversationActions.Request.Builder(Collections.singletonList(message))
- .setMaxSuggestions(3)
- .build();
-
- TextClassifier classifier = new TextClassifierImpl(context, TC_CONSTANTS);
- ConversationActions conversationActions = classifier.suggestConversationActions(request);
-
- Truth.assertThat(conversationActions.getConversationActions()).isEmpty();
- }
-
- private boolean isTextClassifierDisabled() {
- return mClassifier == null || mClassifier == TextClassifier.NO_OP;
- }
-
- private static Matcher<TextSelection> isTextSelection(
- final int startIndex, final int endIndex, final String type) {
- return new BaseMatcher<TextSelection>() {
- @Override
- public boolean matches(Object o) {
- if (o instanceof TextSelection) {
- TextSelection selection = (TextSelection) o;
- return startIndex == selection.getSelectionStartIndex()
- && endIndex == selection.getSelectionEndIndex()
- && typeMatches(selection, type);
- }
- return false;
- }
-
- private boolean typeMatches(TextSelection selection, String type) {
- return type == null
- || (selection.getEntityCount() > 0
- && type.trim().equalsIgnoreCase(selection.getEntity(0)));
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendValue(
- String.format("%d, %d, %s", startIndex, endIndex, type));
- }
- };
- }
-
- private static Matcher<TextLinks> isTextLinksContaining(
- final String text, final String substring, final String type) {
- return new BaseMatcher<TextLinks>() {
-
- @Override
- public void describeTo(Description description) {
- description.appendText("text=").appendValue(text)
- .appendText(", substring=").appendValue(substring)
- .appendText(", type=").appendValue(type);
- }
-
- @Override
- public boolean matches(Object o) {
- if (o instanceof TextLinks) {
- for (TextLinks.TextLink link : ((TextLinks) o).getLinks()) {
- if (text.subSequence(link.getStart(), link.getEnd()).equals(substring)) {
- return type.equals(link.getEntity(0));
- }
- }
- }
- return false;
- }
- };
- }
-
- private static Matcher<TextClassification> isTextClassification(
- final String text, final String type) {
- return new BaseMatcher<TextClassification>() {
- @Override
- public boolean matches(Object o) {
- if (o instanceof TextClassification) {
- TextClassification result = (TextClassification) o;
- return text.equals(result.getText())
- && result.getEntityCount() > 0
- && type.equals(result.getEntity(0));
- }
- return false;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText("text=").appendValue(text)
- .appendText(", type=").appendValue(type);
- }
- };
- }
-
- private static Matcher<TextClassification> containsIntentWithAction(final String action) {
- return new BaseMatcher<TextClassification>() {
- @Override
- public boolean matches(Object o) {
- if (o instanceof TextClassification) {
- TextClassification result = (TextClassification) o;
- return ExtrasUtils.findAction(result, action) != null;
- }
- return false;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText("intent action=").appendValue(action);
- }
- };
- }
-
- private static Matcher<TextLanguage> isTextLanguage(final String languageTag) {
- return new BaseMatcher<TextLanguage>() {
- @Override
- public boolean matches(Object o) {
- if (o instanceof TextLanguage) {
- TextLanguage result = (TextLanguage) o;
- return result.getLocaleHypothesisCount() > 0
- && languageTag.equals(result.getLocale(0).toLanguageTag());
- }
- return false;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText("locale=").appendValue(languageTag);
- }
- };
- }
-
- private static Matcher<ConversationAction> isConversationAction(String actionType) {
- return new BaseMatcher<ConversationAction>() {
- @Override
- public boolean matches(Object o) {
- if (!(o instanceof ConversationAction)) {
- return false;
- }
- ConversationAction conversationAction =
- (ConversationAction) o;
- if (!actionType.equals(conversationAction.getType())) {
- return false;
- }
- if (ConversationAction.TYPE_TEXT_REPLY.equals(actionType)) {
- if (conversationAction.getTextReply() == null) {
- return false;
- }
- }
- if (conversationAction.getConfidenceScore() < 0
- || conversationAction.getConfidenceScore() > 1) {
- return false;
- }
- return true;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText("actionType=").appendValue(actionType);
- }
- };
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java b/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java
index d0d32e3..31f8029 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextLanguageTest.java
@@ -17,6 +17,8 @@
package android.view.textclassifier;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import android.icu.util.ULocale;
import android.os.Bundle;
@@ -75,7 +77,9 @@
final TextLanguage.Request reference = new TextLanguage.Request.Builder(text)
.setExtras(bundle)
.build();
- reference.setCallingPackageName(packageName);
+ final SystemTextClassifierMetadata systemTcMetadata =
+ new SystemTextClassifierMetadata(packageName, 1, false);
+ reference.setSystemTextClassifierMetadata(systemTcMetadata);
final Parcel parcel = Parcel.obtain();
reference.writeToParcel(parcel, 0);
@@ -85,5 +89,11 @@
assertEquals(text, result.getText());
assertEquals("bundle", result.getExtras().getString(bundleKey));
assertEquals(packageName, result.getCallingPackageName());
+ final SystemTextClassifierMetadata resultSystemTcMetadata =
+ result.getSystemTextClassifierMetadata();
+ assertNotNull(resultSystemTcMetadata);
+ assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+ assertEquals(1, resultSystemTcMetadata.getUserId());
+ assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
}
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java b/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java
index ec5813f..4f0b44b 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextLinksTest.java
@@ -17,6 +17,8 @@
package android.view.textclassifier;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import android.os.Bundle;
import android.os.LocaleList;
@@ -115,7 +117,9 @@
.setExtras(BUNDLE)
.setReferenceTime(referenceTime)
.build();
- reference.setCallingPackageName(packageName);
+ final SystemTextClassifierMetadata systemTcMetadata =
+ new SystemTextClassifierMetadata(packageName, 1, false);
+ reference.setSystemTextClassifierMetadata(systemTcMetadata);
// Parcel and unparcel.
final Parcel parcel = Parcel.obtain();
@@ -132,5 +136,11 @@
assertEquals(BUNDLE_VALUE, result.getExtras().getString(BUNDLE_KEY));
assertEquals(packageName, result.getCallingPackageName());
assertEquals(referenceTime, result.getReferenceTime());
+ final SystemTextClassifierMetadata resultSystemTcMetadata =
+ result.getSystemTextClassifierMetadata();
+ assertNotNull(resultSystemTcMetadata);
+ assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+ assertEquals(1, resultSystemTcMetadata.getUserId());
+ assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
}
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java b/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java
index 30cc4e8..82788c8 100644
--- a/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/TextSelectionTest.java
@@ -17,6 +17,8 @@
package android.view.textclassifier;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import android.os.Bundle;
import android.os.LocaleList;
@@ -82,7 +84,9 @@
.setDefaultLocales(new LocaleList(Locale.US, Locale.GERMANY))
.setExtras(BUNDLE)
.build();
- reference.setCallingPackageName(packageName);
+ final SystemTextClassifierMetadata systemTcMetadata =
+ new SystemTextClassifierMetadata(packageName, 1, false);
+ reference.setSystemTextClassifierMetadata(systemTcMetadata);
// Parcel and unparcel.
final Parcel parcel = Parcel.obtain();
@@ -96,5 +100,11 @@
assertEquals("en-US,de-DE", result.getDefaultLocales().toLanguageTags());
assertEquals(BUNDLE_VALUE, result.getExtras().getString(BUNDLE_KEY));
assertEquals(packageName, result.getCallingPackageName());
+ final SystemTextClassifierMetadata resultSystemTcMetadata =
+ result.getSystemTextClassifierMetadata();
+ assertNotNull(resultSystemTcMetadata);
+ assertEquals(packageName, resultSystemTcMetadata.getCallingPackageName());
+ assertEquals(1, resultSystemTcMetadata.getUserId());
+ assertFalse(resultSystemTcMetadata.useDefaultTextClassifier());
}
}
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java
deleted file mode 100644
index 3ad26f5..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.testng.Assert.assertThrows;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.view.textclassifier.FakeContextBuilder;
-import android.view.textclassifier.TextClassifier;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public final class LabeledIntentTest {
- private static final String TITLE_WITHOUT_ENTITY = "Map";
- private static final String TITLE_WITH_ENTITY = "Map NW14D1";
- private static final String DESCRIPTION = "Check the map";
- private static final String DESCRIPTION_WITH_APP_NAME = "Use %1$s to open map";
- private static final Intent INTENT =
- new Intent(Intent.ACTION_VIEW).setDataAndNormalize(Uri.parse("http://www.android.com"));
- private static final int REQUEST_CODE = 42;
- private static final Bundle TEXT_LANGUAGES_BUNDLE = Bundle.EMPTY;
- private static final String APP_LABEL = "fake";
-
- private Context mContext;
-
- @Before
- public void setup() {
- final ComponentName component = FakeContextBuilder.DEFAULT_COMPONENT;
- mContext = new FakeContextBuilder()
- .setIntentComponent(Intent.ACTION_VIEW, component)
- .setAppLabel(component.getPackageName(), APP_LABEL)
- .build();
- }
-
- @Test
- public void resolve_preferTitleWithEntity() {
- LabeledIntent labeledIntent = new LabeledIntent(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- DESCRIPTION,
- null,
- INTENT,
- REQUEST_CODE
- );
-
- LabeledIntent.Result result = labeledIntent.resolve(
- mContext, /*titleChooser*/ null, TEXT_LANGUAGES_BUNDLE);
-
- assertThat(result).isNotNull();
- assertThat(result.remoteAction.getTitle()).isEqualTo(TITLE_WITH_ENTITY);
- assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
- Intent intent = result.resolvedIntent;
- assertThat(intent.getAction()).isEqualTo(intent.getAction());
- assertThat(intent.getComponent()).isNotNull();
- assertThat(intent.hasExtra(TextClassifier.EXTRA_FROM_TEXT_CLASSIFIER)).isTrue();
- }
-
- @Test
- public void resolve_useAvailableTitle() {
- LabeledIntent labeledIntent = new LabeledIntent(
- TITLE_WITHOUT_ENTITY,
- null,
- DESCRIPTION,
- null,
- INTENT,
- REQUEST_CODE
- );
-
- LabeledIntent.Result result = labeledIntent.resolve(
- mContext, /*titleChooser*/ null, TEXT_LANGUAGES_BUNDLE);
-
- assertThat(result).isNotNull();
- assertThat(result.remoteAction.getTitle()).isEqualTo(TITLE_WITHOUT_ENTITY);
- assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
- Intent intent = result.resolvedIntent;
- assertThat(intent.getAction()).isEqualTo(intent.getAction());
- assertThat(intent.getComponent()).isNotNull();
- }
-
- @Test
- public void resolve_titleChooser() {
- LabeledIntent labeledIntent = new LabeledIntent(
- TITLE_WITHOUT_ENTITY,
- null,
- DESCRIPTION,
- null,
- INTENT,
- REQUEST_CODE
- );
-
- LabeledIntent.Result result = labeledIntent.resolve(
- mContext, (labeledIntent1, resolveInfo) -> "chooser", TEXT_LANGUAGES_BUNDLE);
-
- assertThat(result).isNotNull();
- assertThat(result.remoteAction.getTitle()).isEqualTo("chooser");
- assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
- Intent intent = result.resolvedIntent;
- assertThat(intent.getAction()).isEqualTo(intent.getAction());
- assertThat(intent.getComponent()).isNotNull();
- }
-
- @Test
- public void resolve_titleChooserReturnsNull() {
- LabeledIntent labeledIntent = new LabeledIntent(
- TITLE_WITHOUT_ENTITY,
- null,
- DESCRIPTION,
- null,
- INTENT,
- REQUEST_CODE
- );
-
- LabeledIntent.Result result = labeledIntent.resolve(
- mContext, (labeledIntent1, resolveInfo) -> null, TEXT_LANGUAGES_BUNDLE);
-
- assertThat(result).isNotNull();
- assertThat(result.remoteAction.getTitle()).isEqualTo(TITLE_WITHOUT_ENTITY);
- assertThat(result.remoteAction.getContentDescription()).isEqualTo(DESCRIPTION);
- Intent intent = result.resolvedIntent;
- assertThat(intent.getAction()).isEqualTo(intent.getAction());
- assertThat(intent.getComponent()).isNotNull();
- }
-
- @Test
- public void resolve_missingTitle() {
- assertThrows(
- IllegalArgumentException.class,
- () ->
- new LabeledIntent(
- null,
- null,
- DESCRIPTION,
- null,
- INTENT,
- REQUEST_CODE
- ));
- }
-
- @Test
- public void resolve_noIntentHandler() {
- // See setup(). mContext can only resolve Intent.ACTION_VIEW.
- Intent unresolvableIntent = new Intent(Intent.ACTION_TRANSLATE);
- LabeledIntent labeledIntent = new LabeledIntent(
- TITLE_WITHOUT_ENTITY,
- null,
- DESCRIPTION,
- null,
- unresolvableIntent,
- REQUEST_CODE);
-
- LabeledIntent.Result result = labeledIntent.resolve(mContext, null, null);
-
- assertThat(result).isNull();
- }
-
- @Test
- public void resolve_descriptionWithAppName() {
- LabeledIntent labeledIntent = new LabeledIntent(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- INTENT,
- REQUEST_CODE
- );
-
- LabeledIntent.Result result = labeledIntent.resolve(
- mContext, /*titleChooser*/ null, TEXT_LANGUAGES_BUNDLE);
-
- assertThat(result).isNotNull();
- assertThat(result.remoteAction.getContentDescription()).isEqualTo("Use fake to open map");
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/LegacyIntentClassificationFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/LegacyIntentClassificationFactoryTest.java
deleted file mode 100644
index 8891d3f..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/intent/LegacyIntentClassificationFactoryTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Intent;
-import android.view.textclassifier.TextClassifier;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.google.android.textclassifier.AnnotatorModel;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class LegacyIntentClassificationFactoryTest {
-
- private static final String TEXT = "text";
-
- private LegacyClassificationIntentFactory mLegacyIntentClassificationFactory;
-
- @Before
- public void setup() {
- mLegacyIntentClassificationFactory = new LegacyClassificationIntentFactory();
- }
-
- @Test
- public void create_typeDictionary() {
- AnnotatorModel.ClassificationResult classificationResult =
- new AnnotatorModel.ClassificationResult(
- TextClassifier.TYPE_DICTIONARY,
- 1.0f,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- 0L,
- 0L,
- 0d);
-
- List<LabeledIntent> intents = mLegacyIntentClassificationFactory.create(
- InstrumentationRegistry.getContext(),
- TEXT,
- /* foreignText */ false,
- null,
- classificationResult);
-
- assertThat(intents).hasSize(1);
- LabeledIntent labeledIntent = intents.get(0);
- Intent intent = labeledIntent.intent;
- assertThat(intent.getAction()).isEqualTo(Intent.ACTION_DEFINE);
- assertThat(intent.getStringExtra(Intent.EXTRA_TEXT)).isEqualTo(TEXT);
- }
-
- @Test
- public void create_translateAndDictionary() {
- AnnotatorModel.ClassificationResult classificationResult =
- new AnnotatorModel.ClassificationResult(
- TextClassifier.TYPE_DICTIONARY,
- 1.0f,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- 0L,
- 0L,
- 0d);
-
- List<LabeledIntent> intents = mLegacyIntentClassificationFactory.create(
- InstrumentationRegistry.getContext(),
- TEXT,
- /* foreignText */ true,
- null,
- classificationResult);
-
- assertThat(intents).hasSize(2);
- assertThat(intents.get(0).intent.getAction()).isEqualTo(Intent.ACTION_DEFINE);
- assertThat(intents.get(1).intent.getAction()).isEqualTo(Intent.ACTION_TRANSLATE);
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java
deleted file mode 100644
index bcea5fe..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.ArgumentMatchers.same;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-
-import android.content.Context;
-import android.content.Intent;
-import android.view.textclassifier.TextClassifier;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.google.android.textclassifier.AnnotatorModel;
-import com.google.android.textclassifier.RemoteActionTemplate;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.List;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class TemplateClassificationIntentFactoryTest {
-
- private static final String TEXT = "text";
- private static final String TITLE_WITHOUT_ENTITY = "Map";
- private static final String DESCRIPTION = "Opens in Maps";
- private static final String DESCRIPTION_WITH_APP_NAME = "Use %1$s to open Map";
- private static final String ACTION = Intent.ACTION_VIEW;
-
- @Mock
- private ClassificationIntentFactory mFallback;
- private TemplateClassificationIntentFactory mTemplateClassificationIntentFactory;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- mTemplateClassificationIntentFactory = new TemplateClassificationIntentFactory(
- new TemplateIntentFactory(),
- mFallback);
- }
-
- @Test
- public void create_foreignText() {
- AnnotatorModel.ClassificationResult classificationResult =
- new AnnotatorModel.ClassificationResult(
- TextClassifier.TYPE_ADDRESS,
- 1.0f,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- createRemoteActionTemplates(),
- 0L,
- 0L,
- 0d);
-
- List<LabeledIntent> intents =
- mTemplateClassificationIntentFactory.create(
- InstrumentationRegistry.getContext(),
- TEXT,
- /* foreignText */ true,
- null,
- classificationResult);
-
- assertThat(intents).hasSize(2);
- LabeledIntent labeledIntent = intents.get(0);
- assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
- Intent intent = labeledIntent.intent;
- assertThat(intent.getAction()).isEqualTo(ACTION);
-
- labeledIntent = intents.get(1);
- intent = labeledIntent.intent;
- assertThat(intent.getAction()).isEqualTo(Intent.ACTION_TRANSLATE);
- }
-
- @Test
- public void create_notForeignText() {
- AnnotatorModel.ClassificationResult classificationResult =
- new AnnotatorModel.ClassificationResult(
- TextClassifier.TYPE_ADDRESS,
- 1.0f,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- createRemoteActionTemplates(),
- 0L,
- 0L,
- 0d);
-
- List<LabeledIntent> intents =
- mTemplateClassificationIntentFactory.create(
- InstrumentationRegistry.getContext(),
- TEXT,
- /* foreignText */ false,
- null,
- classificationResult);
-
- assertThat(intents).hasSize(1);
- LabeledIntent labeledIntent = intents.get(0);
- assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
- Intent intent = labeledIntent.intent;
- assertThat(intent.getAction()).isEqualTo(ACTION);
- }
-
- @Test
- public void create_nullTemplate() {
- AnnotatorModel.ClassificationResult classificationResult =
- new AnnotatorModel.ClassificationResult(
- TextClassifier.TYPE_ADDRESS,
- 1.0f,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- 0L,
- 0L,
- 0d);
-
- mTemplateClassificationIntentFactory.create(
- InstrumentationRegistry.getContext(),
- TEXT,
- /* foreignText */ false,
- null,
- classificationResult);
-
-
- verify(mFallback).create(
- same(InstrumentationRegistry.getContext()), eq(TEXT), eq(false), eq(null),
- same(classificationResult));
- }
-
- @Test
- public void create_emptyResult() {
- AnnotatorModel.ClassificationResult classificationResult =
- new AnnotatorModel.ClassificationResult(
- TextClassifier.TYPE_ADDRESS,
- 1.0f,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- new RemoteActionTemplate[0],
- 0L,
- 0L,
- 0d);
-
- mTemplateClassificationIntentFactory.create(
- InstrumentationRegistry.getContext(),
- TEXT,
- /* foreignText */ false,
- null,
- classificationResult);
-
-
- verify(mFallback, never()).create(
- any(Context.class), eq(TEXT), eq(false), eq(null),
- any(AnnotatorModel.ClassificationResult.class));
- }
-
-
- private static RemoteActionTemplate[] createRemoteActionTemplates() {
- return new RemoteActionTemplate[]{
- new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- null,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- ACTION,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- )
- };
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java
deleted file mode 100644
index a33c358..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.intent;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Intent;
-import android.net.Uri;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.google.android.textclassifier.NamedVariant;
-import com.google.android.textclassifier.RemoteActionTemplate;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.MockitoAnnotations;
-
-import java.util.List;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class TemplateIntentFactoryTest {
-
- private static final String TEXT = "text";
- private static final String TITLE_WITHOUT_ENTITY = "Map";
- private static final String TITLE_WITH_ENTITY = "Map NW14D1";
- private static final String DESCRIPTION = "Check the map";
- private static final String DESCRIPTION_WITH_APP_NAME = "Use %1$s to open map";
- private static final String ACTION = Intent.ACTION_VIEW;
- private static final String DATA = Uri.parse("http://www.android.com").toString();
- private static final String TYPE = "text/html";
- private static final Integer FLAG = Intent.FLAG_ACTIVITY_NEW_TASK;
- private static final String[] CATEGORY =
- new String[]{Intent.CATEGORY_DEFAULT, Intent.CATEGORY_APP_BROWSER};
- private static final String PACKAGE_NAME = "pkg.name";
- private static final String KEY_ONE = "key1";
- private static final String VALUE_ONE = "value1";
- private static final String KEY_TWO = "key2";
- private static final int VALUE_TWO = 42;
-
- private static final NamedVariant[] NAMED_VARIANTS = new NamedVariant[]{
- new NamedVariant(KEY_ONE, VALUE_ONE),
- new NamedVariant(KEY_TWO, VALUE_TWO)
- };
- private static final Integer REQUEST_CODE = 10;
-
- private TemplateIntentFactory mTemplateIntentFactory;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- mTemplateIntentFactory = new TemplateIntentFactory();
- }
-
- @Test
- public void create_full() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- ACTION,
- DATA,
- TYPE,
- FLAG,
- CATEGORY,
- /* packageName */ null,
- NAMED_VARIANTS,
- REQUEST_CODE
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[]{remoteActionTemplate});
-
- assertThat(intents).hasSize(1);
- LabeledIntent labeledIntent = intents.get(0);
- assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
- assertThat(labeledIntent.titleWithEntity).isEqualTo(TITLE_WITH_ENTITY);
- assertThat(labeledIntent.description).isEqualTo(DESCRIPTION);
- assertThat(labeledIntent.descriptionWithAppName).isEqualTo(DESCRIPTION_WITH_APP_NAME);
- assertThat(labeledIntent.requestCode).isEqualTo(REQUEST_CODE);
- Intent intent = labeledIntent.intent;
- assertThat(intent.getAction()).isEqualTo(ACTION);
- assertThat(intent.getData().toString()).isEqualTo(DATA);
- assertThat(intent.getType()).isEqualTo(TYPE);
- assertThat(intent.getFlags()).isEqualTo(FLAG);
- assertThat(intent.getCategories()).containsExactly((Object[]) CATEGORY);
- assertThat(intent.getPackage()).isNull();
- assertThat(intent.getStringExtra(KEY_ONE)).isEqualTo(VALUE_ONE);
- assertThat(intent.getIntExtra(KEY_TWO, 0)).isEqualTo(VALUE_TWO);
- }
-
- @Test
- public void normalizesScheme() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- ACTION,
- "HTTp://www.android.com",
- TYPE,
- FLAG,
- CATEGORY,
- /* packageName */ null,
- NAMED_VARIANTS,
- REQUEST_CODE
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
-
- String data = intents.get(0).intent.getData().toString();
- assertThat(data).isEqualTo("http://www.android.com");
- }
-
- @Test
- public void create_minimal() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- null,
- DESCRIPTION,
- null,
- ACTION,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[]{remoteActionTemplate});
-
- assertThat(intents).hasSize(1);
- LabeledIntent labeledIntent = intents.get(0);
- assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
- assertThat(labeledIntent.titleWithEntity).isNull();
- assertThat(labeledIntent.description).isEqualTo(DESCRIPTION);
- assertThat(labeledIntent.requestCode).isEqualTo(
- LabeledIntent.DEFAULT_REQUEST_CODE);
- Intent intent = labeledIntent.intent;
- assertThat(intent.getAction()).isEqualTo(ACTION);
- assertThat(intent.getData()).isNull();
- assertThat(intent.getType()).isNull();
- assertThat(intent.getFlags()).isEqualTo(0);
- assertThat(intent.getCategories()).isNull();
- assertThat(intent.getPackage()).isNull();
- }
-
- @Test
- public void invalidTemplate_nullTemplate() {
- RemoteActionTemplate remoteActionTemplate = null;
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
-
- assertThat(intents).isEmpty();
- }
-
- @Test
- public void invalidTemplate_nonEmptyPackageName() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- ACTION,
- DATA,
- TYPE,
- FLAG,
- CATEGORY,
- PACKAGE_NAME,
- NAMED_VARIANTS,
- REQUEST_CODE
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
-
- assertThat(intents).isEmpty();
- }
-
- @Test
- public void invalidTemplate_emptyTitle() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- null,
- null,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- ACTION,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
-
- assertThat(intents).isEmpty();
- }
-
- @Test
- public void invalidTemplate_emptyDescription() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- null,
- null,
- ACTION,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
-
- assertThat(intents).isEmpty();
- }
-
- @Test
- public void invalidTemplate_emptyIntentAction() {
- RemoteActionTemplate remoteActionTemplate = new RemoteActionTemplate(
- TITLE_WITHOUT_ENTITY,
- TITLE_WITH_ENTITY,
- DESCRIPTION,
- DESCRIPTION_WITH_APP_NAME,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- );
-
- List<LabeledIntent> intents =
- mTemplateIntentFactory.create(new RemoteActionTemplate[] {remoteActionTemplate});
-
- assertThat(intents).isEmpty();
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/logging/GenerateLinksLoggerTest.java b/core/tests/coretests/src/android/view/textclassifier/logging/GenerateLinksLoggerTest.java
deleted file mode 100644
index 5e8e582..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/logging/GenerateLinksLoggerTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2017 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.view.textclassifier.logging;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-
-import android.metrics.LogMaker;
-import android.util.ArrayMap;
-import android.view.textclassifier.GenerateLinksLogger;
-import android.view.textclassifier.TextClassifier;
-import android.view.textclassifier.TextLinks;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.android.internal.logging.MetricsLogger;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class GenerateLinksLoggerTest {
-
- private static final String PACKAGE_NAME = "packageName";
- private static final String ZERO = "0";
- private static final int LATENCY_MS = 123;
-
- @Test
- public void testLogGenerateLinks() {
- final String phoneText = "+12122537077";
- final String addressText = "1600 Amphitheater Parkway, Mountain View, CA";
- final String testText = "The number is " + phoneText + ", the address is " + addressText;
- final int phoneOffset = testText.indexOf(phoneText);
- final int addressOffset = testText.indexOf(addressText);
-
- final Map<String, Float> phoneEntityScores = new ArrayMap<>();
- phoneEntityScores.put(TextClassifier.TYPE_PHONE, 0.9f);
- phoneEntityScores.put(TextClassifier.TYPE_OTHER, 0.1f);
- final Map<String, Float> addressEntityScores = new ArrayMap<>();
- addressEntityScores.put(TextClassifier.TYPE_ADDRESS, 1f);
-
- TextLinks links = new TextLinks.Builder(testText)
- .addLink(phoneOffset, phoneOffset + phoneText.length(), phoneEntityScores)
- .addLink(addressOffset, addressOffset + addressText.length(), addressEntityScores)
- .build();
-
- // Set up mock.
- MetricsLogger metricsLogger = mock(MetricsLogger.class);
- ArgumentCaptor<LogMaker> logMakerCapture = ArgumentCaptor.forClass(LogMaker.class);
- doNothing().when(metricsLogger).write(logMakerCapture.capture());
-
- // Generate the log.
- GenerateLinksLogger logger = new GenerateLinksLogger(1 /* sampleRate */, metricsLogger);
- logger.logGenerateLinks(testText, links, PACKAGE_NAME, LATENCY_MS);
-
- // Validate.
- List<LogMaker> logs = logMakerCapture.getAllValues();
- assertEquals(3, logs.size());
- assertHasLog(logs, "" /* entityType */, 2, phoneText.length() + addressText.length(),
- testText.length());
- assertHasLog(logs, TextClassifier.TYPE_ADDRESS, 1, addressText.length(),
- testText.length());
- assertHasLog(logs, TextClassifier.TYPE_PHONE, 1, phoneText.length(),
- testText.length());
- }
-
- private void assertHasLog(List<LogMaker> logs, String entityType, int numLinks,
- int linkTextLength, int textLength) {
- for (LogMaker log : logs) {
- if (!entityType.equals(getEntityType(log))) {
- continue;
- }
- assertEquals(PACKAGE_NAME, log.getPackageName());
- assertNotNull(Objects.toString(log.getTaggedData(MetricsEvent.FIELD_LINKIFY_CALL_ID)));
- assertEquals(numLinks, getIntValue(log, MetricsEvent.FIELD_LINKIFY_NUM_LINKS));
- assertEquals(linkTextLength, getIntValue(log, MetricsEvent.FIELD_LINKIFY_LINK_LENGTH));
- assertEquals(textLength, getIntValue(log, MetricsEvent.FIELD_LINKIFY_TEXT_LENGTH));
- assertEquals(LATENCY_MS, getIntValue(log, MetricsEvent.FIELD_LINKIFY_LATENCY));
- return;
- }
- fail("No log for entity type \"" + entityType + "\"");
- }
-
- private static String getEntityType(LogMaker log) {
- return Objects.toString(log.getTaggedData(MetricsEvent.FIELD_LINKIFY_ENTITY_TYPE), "");
- }
-
- private static int getIntValue(LogMaker log, int eventField) {
- return Integer.parseInt(Objects.toString(log.getTaggedData(eventField), ZERO));
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/logging/SmartSelectionEventTrackerTest.java b/core/tests/coretests/src/android/view/textclassifier/logging/SmartSelectionEventTrackerTest.java
deleted file mode 100644
index 321a7f2..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/logging/SmartSelectionEventTrackerTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2019 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.view.textclassifier.logging;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-import androidx.test.filters.SmallTest;
-
-import com.google.common.truth.Truth;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class SmartSelectionEventTrackerTest {
-
- @Test
- public void getVersionInfo_valid() {
- String signature = "a|702|b";
- String versionInfo = SmartSelectionEventTracker.SelectionEvent.getVersionInfo(signature);
- Truth.assertThat(versionInfo).isEqualTo("702");
- }
-
- @Test
- public void getVersionInfo_invalid() {
- String signature = "|702";
- String versionInfo = SmartSelectionEventTracker.SelectionEvent.getVersionInfo(signature);
- Truth.assertThat(versionInfo).isEmpty();
- }
-}
diff --git a/core/tests/coretests/src/android/view/textclassifier/logging/TextClassifierEventTronLoggerTest.java b/core/tests/coretests/src/android/view/textclassifier/logging/TextClassifierEventTronLoggerTest.java
deleted file mode 100644
index 2c540e5..0000000
--- a/core/tests/coretests/src/android/view/textclassifier/logging/TextClassifierEventTronLoggerTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2018 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.view.textclassifier.logging;
-
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.CONVERSATION_ACTIONS;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_EVENT_TIME;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SCORE;
-import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_WIDGET_TYPE;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.metrics.LogMaker;
-import android.view.textclassifier.ConversationAction;
-import android.view.textclassifier.TextClassificationContext;
-import android.view.textclassifier.TextClassifierEvent;
-import android.view.textclassifier.TextClassifierEventTronLogger;
-
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.android.internal.logging.MetricsLogger;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class TextClassifierEventTronLoggerTest {
- private static final String WIDGET_TYPE = "notification";
- private static final String PACKAGE_NAME = "pkg";
-
- @Mock
- private MetricsLogger mMetricsLogger;
- private TextClassifierEventTronLogger mTextClassifierEventTronLogger;
-
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- mTextClassifierEventTronLogger = new TextClassifierEventTronLogger(mMetricsLogger);
- }
-
- @Test
- public void testWriteEvent() {
- TextClassificationContext textClassificationContext =
- new TextClassificationContext.Builder(PACKAGE_NAME, WIDGET_TYPE)
- .build();
- TextClassifierEvent.ConversationActionsEvent textClassifierEvent =
- new TextClassifierEvent.ConversationActionsEvent.Builder(
- TextClassifierEvent.TYPE_SMART_ACTION)
- .setEntityTypes(ConversationAction.TYPE_CALL_PHONE)
- .setScores(0.5f)
- .setEventContext(textClassificationContext)
- .build();
-
- mTextClassifierEventTronLogger.writeEvent(textClassifierEvent);
-
- ArgumentCaptor<LogMaker> captor = ArgumentCaptor.forClass(LogMaker.class);
- Mockito.verify(mMetricsLogger).write(captor.capture());
- LogMaker logMaker = captor.getValue();
- assertThat(logMaker.getCategory()).isEqualTo(CONVERSATION_ACTIONS);
- assertThat(logMaker.getSubtype()).isEqualTo(ACTION_TEXT_SELECTION_SMART_SHARE);
- assertThat(logMaker.getTaggedData(FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE))
- .isEqualTo(ConversationAction.TYPE_CALL_PHONE);
- assertThat((float) logMaker.getTaggedData(FIELD_TEXT_CLASSIFIER_SCORE))
- .isWithin(0.00001f).of(0.5f);
- // Never write event time.
- assertThat(logMaker.getTaggedData(FIELD_TEXT_CLASSIFIER_EVENT_TIME)).isNull();
- assertThat(logMaker.getPackageName()).isEqualTo(PACKAGE_NAME);
- assertThat(logMaker.getTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_TYPE))
- .isEqualTo(WIDGET_TYPE);
-
- }
-
- @Test
- public void testWriteEvent_unsupportedCategory() {
- TextClassifierEvent.TextSelectionEvent textClassifierEvent =
- new TextClassifierEvent.TextSelectionEvent.Builder(
- TextClassifierEvent.TYPE_SMART_ACTION)
- .build();
-
- mTextClassifierEventTronLogger.writeEvent(textClassifierEvent);
-
- Mockito.verify(mMetricsLogger, Mockito.never()).write(Mockito.any(LogMaker.class));
- }
-}
diff --git a/core/tests/coretests/src/android/widget/EditorCursorDragTest.java b/core/tests/coretests/src/android/widget/EditorCursorDragTest.java
index 0a094c61d..f81964c 100644
--- a/core/tests/coretests/src/android/widget/EditorCursorDragTest.java
+++ b/core/tests/coretests/src/android/widget/EditorCursorDragTest.java
@@ -35,10 +35,13 @@
import android.app.Activity;
import android.app.Instrumentation;
+import android.graphics.Rect;
import android.text.Layout;
+import android.util.ArraySet;
import android.util.Log;
import android.view.InputDevice;
import android.view.MotionEvent;
+import android.view.View;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
@@ -50,11 +53,13 @@
import com.google.common.base.Strings;
+import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
@RunWith(AndroidJUnit4.class)
@@ -70,6 +75,7 @@
private Instrumentation mInstrumentation;
private Activity mActivity;
+ private Set<MotionEvent> mMotionEvents = new ArraySet<>();
@Before
public void before() throws Throwable {
@@ -77,6 +83,14 @@
mActivity = mActivityRule.getActivity();
}
+ @After
+ public void after() throws Throwable {
+ for (MotionEvent event : mMotionEvents) {
+ event.recycle();
+ }
+ mMotionEvents.clear();
+ }
+
@Test
public void testCursorDrag_horizontal_whenTextViewContentsFitOnScreen() throws Throwable {
String text = "Hello world!";
@@ -243,45 +257,45 @@
// Simulate a tap-and-drag gesture.
long event1Time = 1001;
- MotionEvent event1 = downEvent(event1Time, event1Time, 5f, 10f);
+ MotionEvent event1 = downEvent(tv, event1Time, event1Time, 5f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event1));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event2Time = 1002;
- MotionEvent event2 = moveEvent(event1Time, event2Time, 50f, 10f);
+ MotionEvent event2 = moveEvent(tv, event1Time, event2Time, 50f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event2));
assertTrue(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event3Time = 1003;
- MotionEvent event3 = moveEvent(event1Time, event3Time, 100f, 10f);
+ MotionEvent event3 = moveEvent(tv, event1Time, event3Time, 100f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event3));
assertTrue(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event4Time = 2004;
- MotionEvent event4 = upEvent(event1Time, event4Time, 100f, 10f);
+ MotionEvent event4 = upEvent(tv, event1Time, event4Time, 100f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event4));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
// Simulate a quick tap after the drag, near the location where the drag ended.
long event5Time = 2005;
- MotionEvent event5 = downEvent(event5Time, event5Time, 90f, 10f);
+ MotionEvent event5 = downEvent(tv, event5Time, event5Time, 90f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event5));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event6Time = 2006;
- MotionEvent event6 = upEvent(event5Time, event6Time, 90f, 10f);
+ MotionEvent event6 = upEvent(tv, event5Time, event6Time, 90f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event6));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
// Simulate another quick tap in the same location; now selection should be triggered.
long event7Time = 2007;
- MotionEvent event7 = downEvent(event7Time, event7Time, 90f, 10f);
+ MotionEvent event7 = downEvent(tv, event7Time, event7Time, 90f, 10f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event7));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertTrue(editor.getSelectionController().isCursorBeingModified());
@@ -298,19 +312,19 @@
// Simulate a mouse click and drag. This should NOT trigger a cursor drag.
long event1Time = 1001;
- MotionEvent event1 = mouseDownEvent(event1Time, event1Time, 20f, 30f);
+ MotionEvent event1 = mouseDownEvent(tv, event1Time, event1Time, 20f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event1));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event2Time = 1002;
- MotionEvent event2 = mouseMoveEvent(event1Time, event2Time, 120f, 30f);
+ MotionEvent event2 = mouseMoveEvent(tv, event1Time, event2Time, 120f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event2));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertTrue(editor.getSelectionController().isCursorBeingModified());
long event3Time = 1003;
- MotionEvent event3 = mouseUpEvent(event1Time, event3Time, 120f, 30f);
+ MotionEvent event3 = mouseUpEvent(tv, event1Time, event3Time, 120f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event3));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
@@ -327,25 +341,25 @@
// Simulate a tap-and-drag gesture. This should trigger a cursor drag.
long event1Time = 1001;
- MotionEvent event1 = downEvent(event1Time, event1Time, 20f, 30f);
+ MotionEvent event1 = downEvent(tv, event1Time, event1Time, 20f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event1));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event2Time = 1002;
- MotionEvent event2 = moveEvent(event1Time, event2Time, 21f, 30f);
+ MotionEvent event2 = moveEvent(tv, event1Time, event2Time, 21f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event2));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event3Time = 1003;
- MotionEvent event3 = moveEvent(event1Time, event3Time, 120f, 30f);
+ MotionEvent event3 = moveEvent(tv, event1Time, event3Time, 120f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event3));
assertTrue(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event4Time = 1004;
- MotionEvent event4 = upEvent(event1Time, event4Time, 120f, 30f);
+ MotionEvent event4 = upEvent(tv, event1Time, event4Time, 120f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event4));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
@@ -362,31 +376,31 @@
// Simulate a double-tap followed by a drag. This should trigger a selection drag.
long event1Time = 1001;
- MotionEvent event1 = downEvent(event1Time, event1Time, 20f, 30f);
+ MotionEvent event1 = downEvent(tv, event1Time, event1Time, 20f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event1));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event2Time = 1002;
- MotionEvent event2 = upEvent(event1Time, event2Time, 20f, 30f);
+ MotionEvent event2 = upEvent(tv, event1Time, event2Time, 20f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event2));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
long event3Time = 1003;
- MotionEvent event3 = downEvent(event3Time, event3Time, 20f, 30f);
+ MotionEvent event3 = downEvent(tv, event3Time, event3Time, 20f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event3));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertTrue(editor.getSelectionController().isCursorBeingModified());
long event4Time = 1004;
- MotionEvent event4 = moveEvent(event3Time, event4Time, 120f, 30f);
+ MotionEvent event4 = moveEvent(tv, event3Time, event4Time, 120f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event4));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertTrue(editor.getSelectionController().isCursorBeingModified());
long event5Time = 1005;
- MotionEvent event5 = upEvent(event3Time, event5Time, 120f, 30f);
+ MotionEvent event5 = upEvent(tv, event3Time, event5Time, 120f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event5));
assertFalse(editor.getInsertionController().isCursorBeingModified());
assertFalse(editor.getSelectionController().isCursorBeingModified());
@@ -403,7 +417,7 @@
// Simulate a tap. No error should be thrown.
long event1Time = 1001;
- MotionEvent event1 = downEvent(event1Time, event1Time, 20f, 30f);
+ MotionEvent event1 = downEvent(tv, event1Time, event1Time, 20f, 30f);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event1));
// Swipe left to right. No error should be thrown.
@@ -440,7 +454,8 @@
public void testCursorDrag_snapToHandle() throws Throwable {
String text = "line1: This is the 1st line: A\n"
+ "line2: This is the 2nd line: B\n"
- + "line3: This is the 3rd line: C\n";
+ + "line3: This is the 3rd line: C\n"
+ + "line4: This is the 4th line: D\n";
onView(withId(R.id.textview)).perform(replaceText(text));
onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(0));
TextView tv = mActivity.findViewById(R.id.textview);
@@ -454,8 +469,8 @@
// Start dragging along the first line
motionEventInfo(text.indexOf("line1"), 1.0f),
motionEventInfo(text.indexOf("This is the 1st"), 1.0f),
- // Move to the bottom of the third line; cursor should end up on second line
- motionEventInfo(text.indexOf("he 3rd"), 0.0f, text.indexOf("he 2nd")),
+ // Move to the middle of the fourth line; cursor should end up on second line
+ motionEventInfo(text.indexOf("he 4th"), 0.5f, text.indexOf("he 2nd")),
// Move to the middle of the second line; cursor should end up on the first line
motionEventInfo(text.indexOf("he 2nd"), 0.5f, text.indexOf("he 1st"))
};
@@ -473,37 +488,137 @@
simulateDrag(tv, events, true);
}
- private static MotionEvent downEvent(long downTime, long eventTime, float x, float y) {
- return MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);
+ @Test
+ public void testCursorDrag_snapDistance() throws Throwable {
+ String text = "line1: This is the 1st line: A\n"
+ + "line2: This is the 2nd line: B\n"
+ + "line3: This is the 3rd line: C\n";
+ onView(withId(R.id.textview)).perform(replaceText(text));
+ TextView tv = mActivity.findViewById(R.id.textview);
+ Editor editor = tv.getEditorForTesting();
+ final int startIndex = text.indexOf("he 2nd");
+ Layout layout = tv.getLayout();
+ final float cursorStartX = layout.getPrimaryHorizontal(startIndex) + tv.getTotalPaddingLeft();
+ final float cursorStartY = layout.getLineTop(1) + tv.getTotalPaddingTop();
+ final float dragHandleStartX = 20;
+ final float dragHandleStartY = 20;
+
+ // Drag the handle from the 2nd line to the 3rd line.
+ tapAtPoint(tv, cursorStartX, cursorStartY);
+ onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(startIndex));
+ View handleView = editor.getInsertionController().getHandle();
+ final int rawYOfHandleDrag = dragDownUntilLineChange(
+ handleView, dragHandleStartX, dragHandleStartY, tv.getSelectionStart());
+
+ // Drag the cursor from the 2nd line to the 3rd line.
+ tapAtPoint(tv, cursorStartX, cursorStartY);
+ onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(startIndex));
+ final int rawYOfCursorDrag =
+ dragDownUntilLineChange(tv, cursorStartX, cursorStartY, tv.getSelectionStart());
+
+ // Drag the handle with touch through from the 2nd line to the 3rd line.
+ tv.getEditorForTesting().setFlagInsertionHandleGesturesEnabled(true);
+ tapAtPoint(tv, cursorStartX, cursorStartY);
+ onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(startIndex));
+ handleView = editor.getInsertionController().getHandle();
+ int rawYOfHandleDragWithTouchThrough =
+ dragDownUntilLineChange(handleView, dragHandleStartX, dragHandleStartY, tv.getSelectionStart());
+
+ String msg = String.format(
+ "rawYOfHandleDrag: %d, rawYOfCursorDrag: %d, rawYOfHandleDragWithTouchThrough: %d",
+ rawYOfHandleDrag, rawYOfCursorDrag, rawYOfHandleDragWithTouchThrough);
+ final int max = Math.max(
+ rawYOfCursorDrag, Math.max(rawYOfHandleDrag, rawYOfHandleDragWithTouchThrough));
+ final int min = Math.min(
+ rawYOfCursorDrag, Math.min(rawYOfHandleDrag, rawYOfHandleDragWithTouchThrough));
+ // The drag step is 5 pixels in dragDownUntilLineChange().
+ // The difference among the 3 raw Y values should be no bigger than the drag step.
+ assertWithMessage(msg).that(max - min).isLessThan(6);
}
- private static MotionEvent upEvent(long downTime, long eventTime, float x, float y) {
- return MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);
+ private void dispatchTouchEvent(View view, MotionEvent event) {
+ mInstrumentation.runOnMainSync(() -> view.dispatchTouchEvent(event));
}
- private static MotionEvent moveEvent(long downTime, long eventTime, float x, float y) {
- return MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
+ private void tapAtPoint(TextView tv, final float x, final float y) {
+ long downTime = sTicker.addAndGet(10_000);
+ dispatchTouchEvent(tv, downEvent(tv, downTime, downTime, x, y));
+ dispatchTouchEvent(tv, upEvent(tv, downTime, downTime + 1, x, y));
}
- private static MotionEvent mouseDownEvent(long downTime, long eventTime, float x, float y) {
- MotionEvent event = downEvent(downTime, eventTime, x, y);
- event.setSource(InputDevice.SOURCE_MOUSE);
- event.setButtonState(MotionEvent.BUTTON_PRIMARY);
+ private int dragDownUntilLineChange(View view, final float startX, final float startY,
+ final int startOffset) {
+ TextView tv = mActivity.findViewById(R.id.textview);
+ final int startLine = tv.getLayout().getLineForOffset(startOffset);
+
+ int rawY = 0;
+ long downTime = sTicker.addAndGet(10_000);
+ long eventTime = downTime;
+ // Move horizontally first to initiate the cursor drag.
+ dispatchTouchEvent(view, downEvent(view, downTime, eventTime++, startX, startY));
+ dispatchTouchEvent(view, moveEvent(view, downTime, eventTime++, startX + 50, startY));
+ dispatchTouchEvent(view, moveEvent(view, downTime, eventTime++, startX, startY));
+ // Move downwards 5 pixels at a time until a line change occurs.
+ for (int i = 0; i < 200; i++) {
+ MotionEvent ev = moveEvent(view, downTime, eventTime++, startX, startY + i * 5);
+ rawY = (int) ev.getRawY();
+ dispatchTouchEvent(view, ev);
+ if (tv.getLayout().getLineForOffset(tv.getSelectionStart()) > startLine) {
+ break;
+ }
+ }
+ String msg = String.format("The cursor didn't jump from %d!", startOffset);
+ assertWithMessage(msg).that(
+ tv.getLayout().getLineForOffset(tv.getSelectionStart())).isGreaterThan(startLine);
+ dispatchTouchEvent(view, upEvent(view, downTime, eventTime, startX, startY));
+ return rawY;
+ }
+
+ private MotionEvent obtainTouchEvent(
+ View view, int action, long downTime, long eventTime, float x, float y) {
+ Rect r = new Rect();
+ view.getBoundsOnScreen(r);
+ float rawX = x + r.left;
+ float rawY = y + r.top;
+ MotionEvent event =
+ MotionEvent.obtain(downTime, eventTime, action, rawX, rawY, 0);
+ view.toLocalMotionEvent(event);
+ mMotionEvents.add(event);
return event;
}
- private static MotionEvent mouseUpEvent(long downTime, long eventTime, float x, float y) {
- MotionEvent event = upEvent(downTime, eventTime, x, y);
+ private MotionEvent obtainMouseEvent(
+ View view, int action, long downTime, long eventTime, float x, float y) {
+ MotionEvent event = obtainTouchEvent(view, action, downTime, eventTime, x, y);
event.setSource(InputDevice.SOURCE_MOUSE);
- event.setButtonState(0);
+ if (action != MotionEvent.ACTION_UP) {
+ event.setButtonState(MotionEvent.BUTTON_PRIMARY);
+ }
return event;
}
- private static MotionEvent mouseMoveEvent(long downTime, long eventTime, float x, float y) {
- MotionEvent event = moveEvent(downTime, eventTime, x, y);
- event.setSource(InputDevice.SOURCE_MOUSE);
- event.setButtonState(MotionEvent.BUTTON_PRIMARY);
- return event;
+ private MotionEvent downEvent(View view, long downTime, long eventTime, float x, float y) {
+ return obtainTouchEvent(view, MotionEvent.ACTION_DOWN, downTime, eventTime, x, y);
+ }
+
+ private MotionEvent moveEvent(View view, long downTime, long eventTime, float x, float y) {
+ return obtainTouchEvent(view, MotionEvent.ACTION_MOVE, downTime, eventTime, x, y);
+ }
+
+ private MotionEvent upEvent(View view, long downTime, long eventTime, float x, float y) {
+ return obtainTouchEvent(view, MotionEvent.ACTION_UP, downTime, eventTime, x, y);
+ }
+
+ private MotionEvent mouseDownEvent(View view, long downTime, long eventTime, float x, float y) {
+ return obtainMouseEvent(view, MotionEvent.ACTION_DOWN, downTime, eventTime, x, y);
+ }
+
+ private MotionEvent mouseMoveEvent(View view, long downTime, long eventTime, float x, float y) {
+ return obtainMouseEvent(view, MotionEvent.ACTION_MOVE, downTime, eventTime, x, y);
+ }
+
+ private MotionEvent mouseUpEvent(View view, long downTime, long eventTime, float x, float y) {
+ return obtainMouseEvent(view, MotionEvent.ACTION_UP, downTime, eventTime, x, y);
}
public static MotionEventInfo motionEventInfo(int index, float ratioToLineTop) {
@@ -543,14 +658,15 @@
float[] downCoords = events[0].getCoordinates(tv);
long downEventTime = sTicker.addAndGet(10_000);
- MotionEvent downEvent = downEvent(downEventTime, downEventTime,
+ MotionEvent downEvent = downEvent(tv, downEventTime, downEventTime,
downCoords[0], downCoords[1]);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(downEvent));
for (int i = 1; i < events.length; i++) {
float[] moveCoords = events[i].getCoordinates(tv);
long eventTime = downEventTime + i;
- MotionEvent event = moveEvent(downEventTime, eventTime, moveCoords[0], moveCoords[1]);
+ MotionEvent event = moveEvent(tv, downEventTime, eventTime, moveCoords[0],
+ moveCoords[1]);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(event));
assertCursorPosition(tv, events[i].expectedCursorIndex, runAssertions);
}
@@ -558,7 +674,7 @@
MotionEventInfo lastEvent = events[events.length - 1];
float[] upCoords = lastEvent.getCoordinates(tv);
long upEventTime = downEventTime + events.length;
- MotionEvent upEvent = upEvent(downEventTime, upEventTime, upCoords[0], upCoords[1]);
+ MotionEvent upEvent = upEvent(tv, downEventTime, upEventTime, upCoords[0], upCoords[1]);
mInstrumentation.runOnMainSync(() -> editor.onTouchEvent(upEvent));
}
diff --git a/core/tests/coretests/src/android/widget/TextViewActivityTest.java b/core/tests/coretests/src/android/widget/TextViewActivityTest.java
index 88a6f9e..a72be25 100644
--- a/core/tests/coretests/src/android/widget/TextViewActivityTest.java
+++ b/core/tests/coretests/src/android/widget/TextViewActivityTest.java
@@ -497,7 +497,7 @@
@Test
public void testInsertionHandle_multiLine() {
- final String text = "abcd\n" + "efg\n" + "hijk\n";
+ final String text = "abcd\n" + "efg\n" + "hijk\n" + "lmn\n";
onView(withId(R.id.textview)).perform(replaceText(text));
onView(withId(R.id.textview)).perform(clickOnTextAtIndex(text.length()));
@@ -506,12 +506,12 @@
final TextView textView = mActivity.findViewById(R.id.textview);
onHandleView(com.android.internal.R.id.insertion_handle)
- .perform(dragHandle(textView, Handle.INSERTION, text.indexOf('a')));
- onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(text.indexOf("a")));
-
- onHandleView(com.android.internal.R.id.insertion_handle)
.perform(dragHandle(textView, Handle.INSERTION, text.indexOf('f')));
onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(text.indexOf("f")));
+
+ onHandleView(com.android.internal.R.id.insertion_handle)
+ .perform(dragHandle(textView, Handle.INSERTION, text.indexOf('i')));
+ onView(withId(R.id.textview)).check(hasInsertionPointerAtIndex(text.indexOf("i")));
}
private void enableFlagsForInsertionHandleGestures() {
diff --git a/core/tests/coretests/src/com/android/internal/app/AbstractResolverComparatorTest.java b/core/tests/coretests/src/com/android/internal/app/AbstractResolverComparatorTest.java
index 36dd3e4..03ed68c 100644
--- a/core/tests/coretests/src/com/android/internal/app/AbstractResolverComparatorTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/AbstractResolverComparatorTest.java
@@ -98,6 +98,11 @@
@Override
void handleResultMessage(Message message) {}
+
+ @Override
+ List<ComponentName> getTopComponentNames(int topK) {
+ return null;
+ }
};
return testComparator;
}
diff --git a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
index 6d0e58b..a6cbc1a 100644
--- a/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ChooserActivityTest.java
@@ -987,7 +987,8 @@
/* resolveInfoPresentationGetter */ null),
serviceTargets,
TARGET_TYPE_CHOOSER_TARGET,
- directShareToShortcutInfos)
+ directShareToShortcutInfos,
+ null)
);
// Thread.sleep shouldn't be a thing in an integration test but it's
@@ -1058,7 +1059,8 @@
/* resolveInfoPresentationGetter */ null),
serviceTargets,
TARGET_TYPE_CHOOSER_TARGET,
- directShareToShortcutInfos)
+ directShareToShortcutInfos,
+ null)
);
// Thread.sleep shouldn't be a thing in an integration test but it's
// necessary here because of the way the code is structured
@@ -1145,7 +1147,8 @@
/* resolveInfoPresentationGetter */ null),
serviceTargets,
TARGET_TYPE_CHOOSER_TARGET,
- directShareToShortcutInfos)
+ directShareToShortcutInfos,
+ null)
);
// Thread.sleep shouldn't be a thing in an integration test but it's
// necessary here because of the way the code is structured
@@ -1340,7 +1343,7 @@
onView(withText(R.string.resolver_work_tab)).perform(click());
waitForIdle();
- onView(withText(R.string.resolver_turn_on_work_apps))
+ onView(withText(R.string.resolver_turn_on_work_apps_share))
.check(matches(isDisplayed()));
}
diff --git a/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java b/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java
index a7bf488..9d1ca61 100644
--- a/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java
+++ b/core/tests/coretests/src/com/android/internal/app/ResolverActivityTest.java
@@ -624,7 +624,7 @@
onView(withText(R.string.resolver_work_tab)).perform(click());
waitForIdle();
- onView(withText(R.string.resolver_turn_on_work_apps))
+ onView(withText(R.string.resolver_turn_on_work_apps_view))
.check(matches(isDisplayed()));
}
diff --git a/data/etc/car/com.google.android.car.kitchensink.xml b/data/etc/car/com.google.android.car.kitchensink.xml
index 61281ee..efe658a 100644
--- a/data/etc/car/com.google.android.car.kitchensink.xml
+++ b/data/etc/car/com.google.android.car.kitchensink.xml
@@ -33,6 +33,7 @@
<permission name="android.permission.MODIFY_AUDIO_ROUTING"/>
<permission name="android.permission.MODIFY_DAY_NIGHT_MODE"/>
<permission name="android.permission.MODIFY_PHONE_STATE"/>
+ <permission name="android.permission.MONITOR_INPUT"/>
<permission name="android.permission.PROVIDE_TRUST_AGENT"/>
<permission name="android.permission.OVERRIDE_WIFI_CONFIG"/>
<permission name="android.permission.REAL_GET_TASKS"/>
diff --git a/data/etc/com.android.documentsui.xml b/data/etc/com.android.documentsui.xml
index b6671db..1e570ba 100644
--- a/data/etc/com.android.documentsui.xml
+++ b/data/etc/com.android.documentsui.xml
@@ -20,6 +20,7 @@
<permission name="android.permission.INTERACT_ACROSS_USERS"/>
<!-- Permissions required for reading and logging compat changes -->
<permission name="android.permission.LOG_COMPAT_CHANGE"/>
+ <permission name="android.permission.MODIFY_QUIET_MODE"/>
<permission name="android.permission.READ_COMPAT_CHANGE_CONFIG"/>
</privapp-permissions>
</permissions>
diff --git a/data/etc/com.android.systemui.xml b/data/etc/com.android.systemui.xml
index 5d2e303..72827a9 100644
--- a/data/etc/com.android.systemui.xml
+++ b/data/etc/com.android.systemui.xml
@@ -39,6 +39,7 @@
<permission name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<permission name="android.permission.OBSERVE_NETWORK_POLICY"/>
<permission name="android.permission.OVERRIDE_WIFI_CONFIG"/>
+ <permission name="android.permission.PACKAGE_USAGE_STATS" />
<permission name="android.permission.READ_DREAM_STATE"/>
<permission name="android.permission.READ_FRAME_BUFFER"/>
<permission name="android.permission.READ_NETWORK_USAGE_HISTORY"/>
@@ -62,5 +63,6 @@
<permission name="android.permission.WRITE_SECURE_SETTINGS"/>
<permission name="android.permission.WRITE_EMBEDDED_SUBSCRIPTIONS"/>
<permission name="android.permission.CONTROL_DISPLAY_COLOR_TRANSFORMS" />
+ <permission name="android.permission.CAMERA_OPEN_CLOSE_LISTENER" />
</privapp-permissions>
</permissions>
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index afa58d5..5466ac8 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -62,6 +62,10 @@
<permission name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
</privapp-permissions>
+ <privapp-permissions package="com.android.launcher3">
+ <permission name="android.permission.WRITE_SECURE_SETTINGS"/>
+ </privapp-permissions>
+
<privapp-permissions package="com.android.location.fused">
<permission name="android.permission.INSTALL_LOCATION_PROVIDER"/>
<permission name="android.permission.UPDATE_DEVICE_STATS"/>
@@ -164,6 +168,7 @@
<permission name="android.permission.REBOOT"/>
<permission name="android.permission.REGISTER_CALL_PROVIDER"/>
<permission name="android.permission.REGISTER_SIM_SUBSCRIPTION"/>
+ <permission name="android.permission.REGISTER_STATS_PULL_ATOM"/>
<permission name="android.permission.SEND_RESPOND_VIA_MESSAGE"/>
<permission name="android.permission.SET_TIME_ZONE"/>
<permission name="android.permission.SHUTDOWN"/>
@@ -195,6 +200,7 @@
<permission name="android.permission.GET_ACCOUNTS_PRIVILEGED"/>
<permission name="android.permission.INTERACT_ACROSS_USERS"/>
<permission name="android.permission.MANAGE_USERS"/>
+ <permission name="android.permission.READ_PRIVILEGED_PHONE_STATE"/>
<permission name="android.permission.UPDATE_APP_OPS_STATS"/>
<permission name="android.permission.USE_RESERVED_DISK"/>
</privapp-permissions>
diff --git a/identity/java/android/security/identity/CredstoreResultData.java b/identity/java/android/security/identity/CredstoreResultData.java
index ef7afca..2ef735e 100644
--- a/identity/java/android/security/identity/CredstoreResultData.java
+++ b/identity/java/android/security/identity/CredstoreResultData.java
@@ -66,7 +66,7 @@
}
@Override
- public @NonNull Collection<String> getNamespaceNames() {
+ public @NonNull Collection<String> getNamespaces() {
return Collections.unmodifiableCollection(mData.keySet());
}
diff --git a/identity/java/android/security/identity/CredstoreWritableIdentityCredential.java b/identity/java/android/security/identity/CredstoreWritableIdentityCredential.java
index 335636c..725e3d8 100644
--- a/identity/java/android/security/identity/CredstoreWritableIdentityCredential.java
+++ b/identity/java/android/security/identity/CredstoreWritableIdentityCredential.java
@@ -105,11 +105,11 @@
n++;
}
- Collection<String> namespaceNames = personalizationData.getNamespaceNames();
+ Collection<String> namespaces = personalizationData.getNamespaces();
- EntryNamespaceParcel[] ensParcels = new EntryNamespaceParcel[namespaceNames.size()];
+ EntryNamespaceParcel[] ensParcels = new EntryNamespaceParcel[namespaces.size()];
n = 0;
- for (String namespaceName : namespaceNames) {
+ for (String namespaceName : namespaces) {
PersonalizationData.NamespaceData nsd =
personalizationData.getNamespaceData(namespaceName);
diff --git a/identity/java/android/security/identity/IdentityCredential.java b/identity/java/android/security/identity/IdentityCredential.java
index bd43919..1db2f63 100644
--- a/identity/java/android/security/identity/IdentityCredential.java
+++ b/identity/java/android/security/identity/IdentityCredential.java
@@ -209,6 +209,11 @@
* <p>Note that only items referenced in {@code entriesToRequest} are returned - the
* {@code requestMessage} parameter is only used to for enforcing reader authentication.
*
+ * <p>The reason for having {@code requestMessage} and {@code entriesToRequest} as separate
+ * parameters is that the former represents a request from the remote verifier device
+ * (optionally signed) and this allows the application to filter the request to not include
+ * data elements which the user has not consented to sharing.
+ *
* @param requestMessage If not {@code null}, must contain CBOR data conforming to
* the schema mentioned above.
* @param entriesToRequest The entries to request, organized as a map of namespace
diff --git a/identity/java/android/security/identity/PersonalizationData.java b/identity/java/android/security/identity/PersonalizationData.java
index 44370a1..b34f250 100644
--- a/identity/java/android/security/identity/PersonalizationData.java
+++ b/identity/java/android/security/identity/PersonalizationData.java
@@ -46,7 +46,7 @@
return Collections.unmodifiableCollection(mProfiles);
}
- Collection<String> getNamespaceNames() {
+ Collection<String> getNamespaces() {
return Collections.unmodifiableCollection(mNamespaces.keySet());
}
@@ -120,7 +120,7 @@
* @param value The value to add, in CBOR encoding.
* @return The builder.
*/
- public @NonNull Builder setEntry(@NonNull String namespace, @NonNull String name,
+ public @NonNull Builder putEntry(@NonNull String namespace, @NonNull String name,
@NonNull Collection<AccessControlProfileId> accessControlProfileIds,
@NonNull byte[] value) {
NamespaceData namespaceData = mData.mNamespaces.get(namespace);
diff --git a/identity/java/android/security/identity/ResultData.java b/identity/java/android/security/identity/ResultData.java
index 0982c8a..13552d6 100644
--- a/identity/java/android/security/identity/ResultData.java
+++ b/identity/java/android/security/identity/ResultData.java
@@ -152,7 +152,7 @@
* @return collection of name of namespaces containing retrieved entries. May be empty if no
* data was retrieved.
*/
- public abstract @NonNull Collection<String> getNamespaceNames();
+ public abstract @NonNull Collection<String> getNamespaces();
/**
* Get the names of all entries.
@@ -196,8 +196,7 @@
* @param name the name of the entry to get the value for.
* @return the status indicating whether the value was retrieved and if not, why.
*/
- @Status
- public abstract int getStatus(@NonNull String namespaceName, @NonNull String name);
+ public abstract @Status int getStatus(@NonNull String namespaceName, @NonNull String name);
/**
* Gets the raw CBOR data for the value of an entry.
diff --git a/keystore/java/android/security/keystore/KeyGenParameterSpec.java b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
index d9d2eea..a7d0cb8 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -764,8 +764,9 @@
private @KeyProperties.BlockModeEnum String[] mBlockModes;
private boolean mRandomizedEncryptionRequired = true;
private boolean mUserAuthenticationRequired;
- private int mUserAuthenticationValidityDurationSeconds = -1;
- private @KeyProperties.AuthEnum int mUserAuthenticationType;
+ private int mUserAuthenticationValidityDurationSeconds = 0;
+ private @KeyProperties.AuthEnum int mUserAuthenticationType =
+ KeyProperties.AUTH_BIOMETRIC_STRONG;
private boolean mUserPresenceRequired = false;
private byte[] mAttestationChallenge = null;
private boolean mUniqueIdIncluded = false;
@@ -1240,7 +1241,8 @@
if (seconds == -1) {
return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
}
- return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_BIOMETRIC_STRONG);
+ return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_DEVICE_CREDENTIAL
+ | KeyProperties.AUTH_BIOMETRIC_STRONG);
}
/**
diff --git a/keystore/java/android/security/keystore/KeyProtection.java b/keystore/java/android/security/keystore/KeyProtection.java
index 8120a93..2e793de 100644
--- a/keystore/java/android/security/keystore/KeyProtection.java
+++ b/keystore/java/android/security/keystore/KeyProtection.java
@@ -562,8 +562,9 @@
private @KeyProperties.BlockModeEnum String[] mBlockModes;
private boolean mRandomizedEncryptionRequired = true;
private boolean mUserAuthenticationRequired;
- private @KeyProperties.AuthEnum int mUserAuthenticationType;
- private int mUserAuthenticationValidityDurationSeconds = -1;
+ private int mUserAuthenticationValidityDurationSeconds = 0;
+ private @KeyProperties.AuthEnum int mUserAuthenticationType =
+ KeyProperties.AUTH_BIOMETRIC_STRONG;
private boolean mUserPresenceRequired = false;
private boolean mUserAuthenticationValidWhileOnBody;
private boolean mInvalidatedByBiometricEnrollment = true;
@@ -870,7 +871,8 @@
if (seconds == -1) {
return setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
}
- return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_BIOMETRIC_STRONG);
+ return setUserAuthenticationParameters(seconds, KeyProperties.AUTH_DEVICE_CREDENTIAL
+ | KeyProperties.AUTH_BIOMETRIC_STRONG);
}
/**
diff --git a/keystore/java/android/security/keystore/KeymasterUtils.java b/keystore/java/android/security/keystore/KeymasterUtils.java
index 4ead253..670ef5e 100644
--- a/keystore/java/android/security/keystore/KeymasterUtils.java
+++ b/keystore/java/android/security/keystore/KeymasterUtils.java
@@ -82,6 +82,63 @@
}
}
+ private static void addSids(KeymasterArguments args, UserAuthArgs spec) {
+ // If both biometric and credential are accepted, then just use the root sid from gatekeeper
+ if (spec.getUserAuthenticationType() == (KeyProperties.AUTH_BIOMETRIC_STRONG
+ | KeyProperties.AUTH_DEVICE_CREDENTIAL)) {
+ if (spec.getBoundToSpecificSecureUserId() != GateKeeper.INVALID_SECURE_USER_ID) {
+ args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID,
+ KeymasterArguments.toUint64(spec.getBoundToSpecificSecureUserId()));
+ } else {
+ // The key is authorized for use for the specified amount of time after the user has
+ // authenticated. Whatever unlocks the secure lock screen should authorize this key.
+ args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID,
+ KeymasterArguments.toUint64(getRootSid()));
+ }
+ } else {
+ List<Long> sids = new ArrayList<>();
+ if ((spec.getUserAuthenticationType() & KeyProperties.AUTH_BIOMETRIC_STRONG) != 0) {
+ final BiometricManager bm = KeyStore.getApplicationContext()
+ .getSystemService(BiometricManager.class);
+
+ // TODO: Restore permission check in getAuthenticatorIds once the ID is no longer
+ // needed here.
+
+ final long[] biometricSids = bm.getAuthenticatorIds();
+
+ if (biometricSids.length == 0) {
+ throw new IllegalStateException(
+ "At least one biometric must be enrolled to create keys requiring user"
+ + " authentication for every use");
+ }
+
+ if (spec.getBoundToSpecificSecureUserId() != GateKeeper.INVALID_SECURE_USER_ID) {
+ sids.add(spec.getBoundToSpecificSecureUserId());
+ } else if (spec.isInvalidatedByBiometricEnrollment()) {
+ // The biometric-only SIDs will change on biometric enrollment or removal of all
+ // enrolled templates, invalidating the key.
+ for (long sid : biometricSids) {
+ sids.add(sid);
+ }
+ } else {
+ // The root SID will *not* change on fingerprint enrollment, or removal of all
+ // enrolled fingerprints, allowing the key to remain valid.
+ sids.add(getRootSid());
+ }
+ } else if ((spec.getUserAuthenticationType() & KeyProperties.AUTH_DEVICE_CREDENTIAL)
+ != 0) {
+ sids.add(getRootSid());
+ } else {
+ throw new IllegalStateException("Invalid or no authentication type specified.");
+ }
+
+ for (int i = 0; i < sids.size(); i++) {
+ args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID,
+ KeymasterArguments.toUint64(sids.get(i)));
+ }
+ }
+ }
+
/**
* Adds keymaster arguments to express the key's authorization policy supported by user
* authentication.
@@ -114,40 +171,7 @@
if (spec.getUserAuthenticationValidityDurationSeconds() == 0) {
// Every use of this key needs to be authorized by the user.
- final BiometricManager bm = KeyStore.getApplicationContext()
- .getSystemService(BiometricManager.class);
-
- // TODO: Restore permission check in getAuthenticatorIds once the ID is no longer
- // needed here.
-
- final long[] biometricSids = bm.getAuthenticatorIds();
-
- if (biometricSids.length == 0) {
- throw new IllegalStateException(
- "At least one biometric must be enrolled to create keys requiring user"
- + " authentication for every use");
- }
-
- List<Long> sids = new ArrayList<>();
- if (spec.getBoundToSpecificSecureUserId() != GateKeeper.INVALID_SECURE_USER_ID) {
- sids.add(spec.getBoundToSpecificSecureUserId());
- } else if (spec.isInvalidatedByBiometricEnrollment()) {
- // The biometric-only SIDs will change on biometric enrollment or removal of all
- // enrolled templates, invalidating the key.
- for (long sid : biometricSids) {
- sids.add(sid);
- }
- } else {
- // The root SID will *not* change on fingerprint enrollment, or removal of all
- // enrolled fingerprints, allowing the key to remain valid.
- sids.add(getRootSid());
- }
-
- for (int i = 0; i < sids.size(); i++) {
- args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID,
- KeymasterArguments.toUint64(sids.get(i)));
- }
-
+ addSids(args, spec);
args.addEnum(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType());
if (spec.isUserAuthenticationValidWhileOnBody()) {
@@ -155,18 +179,8 @@
+ "supported for keys requiring fingerprint authentication");
}
} else {
- long sid;
- if (spec.getBoundToSpecificSecureUserId() != GateKeeper.INVALID_SECURE_USER_ID) {
- sid = spec.getBoundToSpecificSecureUserId();
- } else {
- // The key is authorized for use for the specified amount of time after the user has
- // authenticated. Whatever unlocks the secure lock screen should authorize this key.
- sid = getRootSid();
- }
- args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID,
- KeymasterArguments.toUint64(sid));
- args.addEnum(KeymasterDefs.KM_TAG_USER_AUTH_TYPE,
- KeymasterDefs.HW_AUTH_PASSWORD | KeymasterDefs.HW_AUTH_BIOMETRIC);
+ addSids(args, spec);
+ args.addEnum(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType());
args.addUnsignedInt(KeymasterDefs.KM_TAG_AUTH_TIMEOUT,
spec.getUserAuthenticationValidityDurationSeconds());
if (spec.isUserAuthenticationValidWhileOnBody()) {
diff --git a/libs/hwui/Readback.cpp b/libs/hwui/Readback.cpp
index 84c07d7..39900e6 100644
--- a/libs/hwui/Readback.cpp
+++ b/libs/hwui/Readback.cpp
@@ -146,12 +146,11 @@
}
Layer layer(mRenderThread.renderState(), nullptr, 255, SkBlendMode::kSrc);
- bool disableFilter = MathUtils::areEqual(skiaSrcRect.width(), skiaDestRect.width()) &&
- MathUtils::areEqual(skiaSrcRect.height(), skiaDestRect.height());
- layer.setForceFilter(!disableFilter);
layer.setSize(displayedWidth, displayedHeight);
texTransform.copyTo(layer.getTexTransform());
layer.setImage(image);
+ // Scaling filter is not explicitly set here, because it is done inside copyLayerInfo
+ // after checking the necessity based on the src/dest rect size and the transformation.
if (copyLayerInto(&layer, &skiaSrcRect, &skiaDestRect, bitmap)) {
copyResult = CopyResult::Success;
}
diff --git a/location/java/android/location/LocationManager.java b/location/java/android/location/LocationManager.java
index e230917..ff7049e 100644
--- a/location/java/android/location/LocationManager.java
+++ b/location/java/android/location/LocationManager.java
@@ -103,6 +103,16 @@
private final Object mLock = new Object();
/**
+ * For apps targeting Android R and above, {@link #getProvider(String)} will no longer throw any
+ * security exceptions.
+ *
+ * @hide
+ */
+ @ChangeId
+ @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
+ private static final long GET_PROVIDER_SECURITY_EXCEPTIONS = 150935354L;
+
+ /**
* For apps targeting Android K and above, supplied {@link PendingIntent}s must be targeted to a
* specific package.
*
@@ -602,7 +612,7 @@
public Location getLastLocation() {
try {
return mService.getLastLocation(null, mContext.getPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -635,7 +645,7 @@
try {
return mService.getLastLocation(request, mContext.getPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -732,7 +742,7 @@
try {
if (mService.getCurrentLocation(currentLocationRequest, remoteCancellationSignal,
- listenerTransport, mContext.getPackageName(), mContext.getFeatureId(),
+ listenerTransport, mContext.getPackageName(), mContext.getAttributionTag(),
getListenerIdentifier(consumer))) {
listenerTransport.register(mContext.getSystemService(AlarmManager.class),
remoteCancellationSignal);
@@ -1179,7 +1189,7 @@
boolean registered = false;
try {
mService.requestLocationUpdates(locationRequest, transport, null,
- mContext.getPackageName(), mContext.getFeatureId(),
+ mContext.getPackageName(), mContext.getAttributionTag(),
getListenerIdentifier(listener));
registered = true;
} catch (RemoteException e) {
@@ -1225,7 +1235,7 @@
try {
mService.requestLocationUpdates(locationRequest, null, pendingIntent,
- mContext.getPackageName(), mContext.getFeatureId(),
+ mContext.getPackageName(), mContext.getAttributionTag(),
getListenerIdentifier(pendingIntent));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -1401,6 +1411,22 @@
*/
public @Nullable LocationProvider getProvider(@NonNull String provider) {
Preconditions.checkArgument(provider != null, "invalid null provider");
+
+ if (!Compatibility.isChangeEnabled(GET_PROVIDER_SECURITY_EXCEPTIONS)) {
+ if (NETWORK_PROVIDER.equals(provider) || FUSED_PROVIDER.equals(provider)) {
+ try {
+ mContext.enforcePermission(ACCESS_FINE_LOCATION, Process.myPid(),
+ Process.myUid(), null);
+ } catch (SecurityException e) {
+ mContext.enforcePermission(ACCESS_COARSE_LOCATION, Process.myPid(),
+ Process.myUid(), null);
+ }
+ } else {
+ mContext.enforcePermission(ACCESS_FINE_LOCATION, Process.myPid(), Process.myUid(),
+ null);
+ }
+ }
+
try {
ProviderProperties properties = mService.getProviderProperties(provider);
if (properties == null) {
@@ -1685,7 +1711,7 @@
LocationRequest request = new LocationRequest().setExpireIn(expiration);
try {
mService.requestGeofence(request, fence, intent, mContext.getPackageName(),
- mContext.getFeatureId(), getListenerIdentifier(intent));
+ mContext.getAttributionTag(), getListenerIdentifier(intent));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1772,7 +1798,7 @@
try {
mService.requestGeofence(request, fence, intent, mContext.getPackageName(),
- mContext.getFeatureId(), getListenerIdentifier(intent));
+ mContext.getAttributionTag(), getListenerIdentifier(intent));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2920,7 +2946,7 @@
GnssStatusListener transport = new GnssStatusListener();
if (mService.registerGnssStatusCallback(transport, mContext.getPackageName(),
- mContext.getFeatureId())) {
+ mContext.getAttributionTag())) {
mListenerTransport = transport;
return true;
} else {
@@ -2986,7 +3012,7 @@
GnssMeasurementsListener transport = new GnssMeasurementsListener();
if (mService.addGnssMeasurementsListener(request, transport, mContext.getPackageName(),
- mContext.getFeatureId(), "gnss measurement callback")) {
+ mContext.getAttributionTag(), "gnss measurement callback")) {
mListenerTransport = transport;
return true;
} else {
@@ -3039,7 +3065,7 @@
GnssNavigationMessageListener transport = new GnssNavigationMessageListener();
if (mService.addGnssNavigationMessageListener(transport, mContext.getPackageName(),
- mContext.getFeatureId(), "gnss navigation callback")) {
+ mContext.getAttributionTag(), "gnss navigation callback")) {
mListenerTransport = transport;
return true;
} else {
@@ -3080,7 +3106,7 @@
GnssAntennaInfoListener transport = new GnssAntennaInfoListener();
if (mService.addGnssAntennaInfoListener(transport, mContext.getPackageName(),
- mContext.getFeatureId(), "gnss antenna info callback")) {
+ mContext.getAttributionTag(), "gnss antenna info callback")) {
mListenerTransport = transport;
return true;
} else {
@@ -3117,7 +3143,7 @@
BatchedLocationCallback transport = new BatchedLocationCallback();
if (mService.addGnssBatchingCallback(transport, mContext.getPackageName(),
- mContext.getFeatureId(), "batched location callback")) {
+ mContext.getAttributionTag(), "batched location callback")) {
mListenerTransport = transport;
return true;
} else {
diff --git a/location/java/com/android/internal/location/gnssmetrics/GnssMetrics.java b/location/java/com/android/internal/location/gnssmetrics/GnssMetrics.java
index 1ac4b4b..323bba3 100644
--- a/location/java/com/android/internal/location/gnssmetrics/GnssMetrics.java
+++ b/location/java/com/android/internal/location/gnssmetrics/GnssMetrics.java
@@ -624,7 +624,7 @@
private void registerGnssStats() {
mPullAtomCallback = new StatsPullAtomCallbackImpl();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
FrameworkStatsLog.GNSS_STATS,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(), mPullAtomCallback);
diff --git a/media/java/android/media/IMediaRoute2ProviderService.aidl b/media/java/android/media/IMediaRoute2ProviderService.aidl
index 6cd2547..eee3d22 100644
--- a/media/java/android/media/IMediaRoute2ProviderService.aidl
+++ b/media/java/android/media/IMediaRoute2ProviderService.aidl
@@ -29,13 +29,13 @@
// MediaRoute2ProviderService#MediaRoute2ProviderServiceStub for readability.
void setCallback(IMediaRoute2ProviderServiceCallback callback);
void updateDiscoveryPreference(in RouteDiscoveryPreference discoveryPreference);
- void setRouteVolume(String routeId, int volume, long requestId);
+ void setRouteVolume(long requestId, String routeId, int volume);
- void requestCreateSession(String packageName, String routeId, long requestId,
+ void requestCreateSession(long requestId, String packageName, String routeId,
in @nullable Bundle sessionHints);
- void selectRoute(String sessionId, String routeId, long requestId);
- void deselectRoute(String sessionId, String routeId, long requestId);
- void transferToRoute(String sessionId, String routeId, long requestId);
- void setSessionVolume(String sessionId, int volume, long requestId);
- void releaseSession(String sessionId, long requestId);
+ void selectRoute(long requestId, String sessionId, String routeId);
+ void deselectRoute(long requestId, String sessionId, String routeId);
+ void transferToRoute(long requestId, String sessionId, String routeId);
+ void setSessionVolume(long requestId, String sessionId, int volume);
+ void releaseSession(long requestId, String sessionId);
}
diff --git a/media/java/android/media/IMediaRoute2ProviderServiceCallback.aidl b/media/java/android/media/IMediaRoute2ProviderServiceCallback.aidl
index 882caad..1755657 100644
--- a/media/java/android/media/IMediaRoute2ProviderServiceCallback.aidl
+++ b/media/java/android/media/IMediaRoute2ProviderServiceCallback.aidl
@@ -27,7 +27,7 @@
oneway interface IMediaRoute2ProviderServiceCallback {
// TODO: Change it to updateRoutes?
void updateState(in MediaRoute2ProviderInfo providerInfo);
- void notifySessionCreated(in RoutingSessionInfo sessionInfo, long requestId);
+ void notifySessionCreated(long requestId, in RoutingSessionInfo sessionInfo);
void notifySessionUpdated(in RoutingSessionInfo sessionInfo);
void notifySessionReleased(in RoutingSessionInfo sessionInfo);
void notifyRequestFailed(long requestId, int reason);
diff --git a/media/java/android/media/IMediaRouter2.aidl b/media/java/android/media/IMediaRouter2.aidl
index 550ecfd..dc06153 100644
--- a/media/java/android/media/IMediaRouter2.aidl
+++ b/media/java/android/media/IMediaRouter2.aidl
@@ -28,7 +28,7 @@
void notifyRoutesAdded(in List<MediaRoute2Info> routes);
void notifyRoutesRemoved(in List<MediaRoute2Info> routes);
void notifyRoutesChanged(in List<MediaRoute2Info> routes);
- void notifySessionCreated(in @nullable RoutingSessionInfo sessionInfo, int requestId);
+ void notifySessionCreated(int requestId, in @nullable RoutingSessionInfo sessionInfo);
void notifySessionInfoChanged(in RoutingSessionInfo sessionInfo);
void notifySessionReleased(in RoutingSessionInfo sessionInfo);
}
diff --git a/media/java/android/media/IMediaRouterService.aidl b/media/java/android/media/IMediaRouterService.aidl
index c7cb07d..0d87736 100644
--- a/media/java/android/media/IMediaRouterService.aidl
+++ b/media/java/android/media/IMediaRouterService.aidl
@@ -57,8 +57,8 @@
in RouteDiscoveryPreference preference);
void setRouteVolumeWithRouter2(IMediaRouter2 router, in MediaRoute2Info route, int volume);
- void requestCreateSessionWithRouter2(IMediaRouter2 router, in MediaRoute2Info route,
- int requestId, in @nullable Bundle sessionHints);
+ void requestCreateSessionWithRouter2(IMediaRouter2 router, int requestId,
+ in MediaRoute2Info route, in @nullable Bundle sessionHints);
void selectRouteWithRouter2(IMediaRouter2 router, String sessionId, in MediaRoute2Info route);
void deselectRouteWithRouter2(IMediaRouter2 router, String sessionId, in MediaRoute2Info route);
void transferToRouteWithRouter2(IMediaRouter2 router, String sessionId,
@@ -70,18 +70,18 @@
List<RoutingSessionInfo> getActiveSessions(IMediaRouter2Manager manager);
void registerManager(IMediaRouter2Manager manager, String packageName);
void unregisterManager(IMediaRouter2Manager manager);
- void setRouteVolumeWithManager(IMediaRouter2Manager manager, in MediaRoute2Info route,
- int volume, int requestId);
+ void setRouteVolumeWithManager(IMediaRouter2Manager manager, int requestId,
+ in MediaRoute2Info route, int volume);
- void requestCreateSessionWithManager(IMediaRouter2Manager manager, String packageName,
- in @nullable MediaRoute2Info route, int requestId);
- void selectRouteWithManager(IMediaRouter2Manager manager, String sessionId,
- in MediaRoute2Info route, int requestId);
- void deselectRouteWithManager(IMediaRouter2Manager manager, String sessionId,
- in MediaRoute2Info route, int requestId);
- void transferToRouteWithManager(IMediaRouter2Manager manager, String sessionId,
- in MediaRoute2Info route, int requestId);
- void setSessionVolumeWithManager(IMediaRouter2Manager manager, String sessionId, int volume,
- int requestId);
- void releaseSessionWithManager(IMediaRouter2Manager manager, String sessionId, int requestId);
+ void requestCreateSessionWithManager(IMediaRouter2Manager manager, int requestId,
+ String packageName, in @nullable MediaRoute2Info route);
+ void selectRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, in MediaRoute2Info route);
+ void deselectRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, in MediaRoute2Info route);
+ void transferToRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, in MediaRoute2Info route);
+ void setSessionVolumeWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, int volume);
+ void releaseSessionWithManager(IMediaRouter2Manager manager, int requestId, String sessionId);
}
diff --git a/media/java/android/media/MediaRoute2Info.java b/media/java/android/media/MediaRoute2Info.java
index 8d63cf04..36ccf00 100644
--- a/media/java/android/media/MediaRoute2Info.java
+++ b/media/java/android/media/MediaRoute2Info.java
@@ -112,38 +112,6 @@
public @interface Type {}
/**
- * The default receiver device type of the route indicating the type is unknown.
- *
- * @see #getDeviceType
- */
- public static final int DEVICE_TYPE_UNKNOWN = 0;
-
- /**
- * A receiver device type of the route indicating the presentation of the media is happening
- * on a TV.
- *
- * @see #getDeviceType
- */
- public static final int DEVICE_TYPE_REMOTE_TV = 1;
-
- /**
- * A receiver device type of the route indicating the presentation of the media is happening
- * on a speaker.
- *
- * @see #getDeviceType
- */
- public static final int DEVICE_TYPE_REMOTE_SPEAKER = 2;
-
- /**
- * A receiver device type of the route indicating the presentation of the media is happening
- * on a bluetooth device such as a bluetooth speaker.
- *
- * @see #getDeviceType
- */
- public static final int DEVICE_TYPE_BLUETOOTH = 3;
-
-
- /**
* The default route type indicating the type is unknown.
*
* @see #getType
@@ -396,18 +364,6 @@
}
/**
- * Gets the type of the receiver device associated with this route.
- *
- * @return The type of the receiver device associated with this route:
- * {@link #DEVICE_TYPE_REMOTE_TV}, {@link #DEVICE_TYPE_REMOTE_SPEAKER},
- * {@link #DEVICE_TYPE_BLUETOOTH}.
- */
- @Type
- public int getDeviceType() {
- return getType();
- }
-
- /**
* Gets the type of this route.
*
* @return The type of this route:
@@ -599,7 +555,6 @@
.append("id=").append(getId())
.append(", name=").append(getName())
.append(", features=").append(getFeatures())
- .append(", deviceType=").append(getDeviceType())
.append(", iconUri=").append(getIconUri())
.append(", description=").append(getDescription())
.append(", connectionState=").append(getConnectionState())
@@ -752,14 +707,6 @@
}
/**
- * Sets the route's device type.
- */
- @NonNull
- public Builder setDeviceType(@Type int type) {
- return setType(type);
- }
-
- /**
* Sets the route's type.
* @hide
*/
diff --git a/media/java/android/media/MediaRoute2ProviderService.java b/media/java/android/media/MediaRoute2ProviderService.java
index 51696a4..fb95e98 100644
--- a/media/java/android/media/MediaRoute2ProviderService.java
+++ b/media/java/android/media/MediaRoute2ProviderService.java
@@ -78,11 +78,11 @@
public static final String SERVICE_INTERFACE = "android.media.MediaRoute2ProviderService";
/**
- * The request ID to pass {@link #notifySessionCreated(RoutingSessionInfo, long)}
+ * The request ID to pass {@link #notifySessionCreated(long, RoutingSessionInfo)}
* when {@link MediaRoute2ProviderService} created a session although there was no creation
* request.
*
- * @see #notifySessionCreated(RoutingSessionInfo, long)
+ * @see #notifySessionCreated(long, RoutingSessionInfo)
*/
public static final long REQUEST_ID_NONE = 0;
@@ -218,16 +218,16 @@
* If this session is created without any creation request, use {@link #REQUEST_ID_NONE}
* as the request ID.
*
- * @param sessionInfo information of the new session.
- * The {@link RoutingSessionInfo#getId() id} of the session must be unique.
* @param requestId id of the previous request to create this session provided in
* {@link #onCreateSession(long, String, String, Bundle)}. Can be
* {@link #REQUEST_ID_NONE} if this session is created without any request.
+ * @param sessionInfo information of the new session.
+ * The {@link RoutingSessionInfo#getId() id} of the session must be unique.
* @see #onCreateSession(long, String, String, Bundle)
* @see #getSessionInfo(String)
*/
- public final void notifySessionCreated(@NonNull RoutingSessionInfo sessionInfo,
- long requestId) {
+ public final void notifySessionCreated(long requestId,
+ @NonNull RoutingSessionInfo sessionInfo) {
Objects.requireNonNull(sessionInfo, "sessionInfo must not be null");
String sessionId = sessionInfo.getId();
@@ -247,7 +247,7 @@
// TODO: Calling binder calls in multiple thread may cause timing issue.
// Consider to change implementations to avoid the problems.
// For example, post binder calls, always send all sessions at once, etc.
- mRemoteCallback.notifySessionCreated(sessionInfo, requestId);
+ mRemoteCallback.notifySessionCreated(requestId, sessionInfo);
} catch (RemoteException ex) {
Log.w(TAG, "Failed to notify session created.");
}
@@ -337,7 +337,7 @@
* Called when the service receives a request to create a session.
* <p>
* You should create and maintain your own session and notifies the client of
- * session info. Call {@link #notifySessionCreated(RoutingSessionInfo, long)}
+ * session info. Call {@link #notifySessionCreated(long, RoutingSessionInfo)}
* with the given {@code requestId} to notify the information of a new session.
* The created session must have the same route feature and must include the given route
* specified by {@code routeId}.
@@ -466,10 +466,6 @@
return;
}
- List<RoutingSessionInfo> sessionInfos;
- synchronized (mSessionLock) {
- sessionInfos = new ArrayList<>(mSessionInfo.values());
- }
try {
mRemoteCallback.updateState(mProviderInfo);
} catch (RemoteException ex) {
@@ -504,7 +500,7 @@
}
@Override
- public void setRouteVolume(String routeId, int volume, long requestId) {
+ public void setRouteVolume(long requestId, String routeId, int volume) {
if (!checkCallerisSystem()) {
return;
}
@@ -513,7 +509,7 @@
}
@Override
- public void requestCreateSession(String packageName, String routeId, long requestId,
+ public void requestCreateSession(long requestId, String packageName, String routeId,
@Nullable Bundle requestCreateSession) {
if (!checkCallerisSystem()) {
return;
@@ -524,7 +520,7 @@
}
@Override
- public void selectRoute(String sessionId, String routeId, long requestId) {
+ public void selectRoute(long requestId, String sessionId, String routeId) {
if (!checkCallerisSystem()) {
return;
}
@@ -537,7 +533,7 @@
}
@Override
- public void deselectRoute(String sessionId, String routeId, long requestId) {
+ public void deselectRoute(long requestId, String sessionId, String routeId) {
if (!checkCallerisSystem()) {
return;
}
@@ -550,7 +546,7 @@
}
@Override
- public void transferToRoute(String sessionId, String routeId, long requestId) {
+ public void transferToRoute(long requestId, String sessionId, String routeId) {
if (!checkCallerisSystem()) {
return;
}
@@ -563,7 +559,7 @@
}
@Override
- public void setSessionVolume(String sessionId, int volume, long requestId) {
+ public void setSessionVolume(long requestId, String sessionId, int volume) {
if (!checkCallerisSystem()) {
return;
}
@@ -572,7 +568,7 @@
}
@Override
- public void releaseSession(String sessionId, long requestId) {
+ public void releaseSession(long requestId, String sessionId) {
if (!checkCallerisSystem()) {
return;
}
diff --git a/media/java/android/media/MediaRouter2.java b/media/java/android/media/MediaRouter2.java
index fd24089..bde45d7 100644
--- a/media/java/android/media/MediaRouter2.java
+++ b/media/java/android/media/MediaRouter2.java
@@ -47,13 +47,18 @@
import java.util.stream.Collectors;
/**
+ * This API is not generally intended for third party application developers.
+ * Use the <a href="{@docRoot}jetpack/androidx.html">AndroidX</a>
+ <a href="{@docRoot}reference/androidx/mediarouter/media/package-summary.html">Media Router
+ * Library</a> for consistent behavior across all devices.
+ *
* Media Router 2 allows applications to control the routing of media channels
* and streams from the current device to remote speakers and devices.
*/
// TODO: Add method names at the beginning of log messages. (e.g. updateControllerOnHandler)
// Not only MediaRouter2, but also to service / manager / provider.
// TODO: ensure thread-safe and document it
-public class MediaRouter2 {
+public final class MediaRouter2 {
private static final String TAG = "MR2";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
private static final Object sRouterLock = new Object();
@@ -88,9 +93,9 @@
MediaRouter2Stub mStub;
@GuardedBy("sRouterLock")
- private Map<String, RoutingController> mRoutingControllers = new ArrayMap<>();
+ private final Map<String, RoutingController> mRoutingControllers = new ArrayMap<>();
- private AtomicInteger mControllerCreationRequestCnt = new AtomicInteger(1);
+ private final AtomicInteger mControllerCreationRequestCnt = new AtomicInteger(1);
final Handler mHandler;
@GuardedBy("sRouterLock")
@@ -372,7 +377,9 @@
* @see TransferCallback#onTransferred
* @see TransferCallback#onTransferFailed
*/
- public void transferTo(@Nullable MediaRoute2Info route) {
+ public void transferTo(@NonNull MediaRoute2Info route) {
+ Objects.requireNonNull(route, "route must not be null");
+
List<RoutingController> controllers = getControllers();
RoutingController controller = controllers.get(controllers.size() - 1);
@@ -380,19 +387,25 @@
}
/**
+ * Stops the current media routing. If the {@link #getSystemController() system controller}
+ * controls the media routing, this method is a no-op.
+ */
+ public void stop() {
+ List<RoutingController> controllers = getControllers();
+ RoutingController controller = controllers.get(controllers.size() - 1);
+
+ controller.release();
+ }
+
+ /**
* Transfers the media of a routing controller to the given route.
* @param controller a routing controller controlling media routing.
- * @param route the route you want to transfer the media to. Pass {@code null} to stop
- * routing controlled by the given controller.
+ * @param route the route you want to transfer the media to.
* @hide
*/
- void transfer(@NonNull RoutingController controller, @Nullable MediaRoute2Info route) {
+ void transfer(@NonNull RoutingController controller, @NonNull MediaRoute2Info route) {
Objects.requireNonNull(controller, "controller must not be null");
-
- if (route == null) {
- controller.release();
- return;
- }
+ Objects.requireNonNull(route, "route must not be null");
// TODO: Check thread-safety
if (!mRoutes.containsKey(route.getId())) {
@@ -406,8 +419,7 @@
controller.release();
- final int requestId;
- requestId = mControllerCreationRequestCnt.getAndIncrement();
+ final int requestId = mControllerCreationRequestCnt.getAndIncrement();
ControllerCreationRequest request =
new ControllerCreationRequest(requestId, controller, route);
@@ -429,11 +441,11 @@
if (stub != null) {
try {
mMediaRouterService.requestCreateSessionWithRouter2(
- stub, route, requestId, controllerHints);
+ stub, requestId, route, controllerHints);
} catch (RemoteException ex) {
Log.e(TAG, "transfer: Unable to request to create controller.", ex);
mHandler.sendMessage(obtainMessage(MediaRouter2::createControllerOnHandler,
- MediaRouter2.this, null, requestId));
+ MediaRouter2.this, requestId, null));
}
}
}
@@ -559,7 +571,7 @@
* <p>
* Pass {@code null} to sessionInfo for the failure case.
*/
- void createControllerOnHandler(@Nullable RoutingSessionInfo sessionInfo, int requestId) {
+ void createControllerOnHandler(int requestId, @Nullable RoutingSessionInfo sessionInfo) {
ControllerCreationRequest matchingRequest = null;
for (ControllerCreationRequest request : mControllerCreationRequests) {
if (request.mRequestId == requestId) {
@@ -597,10 +609,16 @@
}
if (sessionInfo != null) {
- RoutingController newController = new RoutingController(sessionInfo);
- synchronized (sRouterLock) {
- mRoutingControllers.put(newController.getId(), newController);
+ RoutingController newController;
+ if (sessionInfo.isSystemSession()) {
+ newController = getSystemController();
+ } else {
+ newController = new RoutingController(sessionInfo);
+ synchronized (sRouterLock) {
+ mRoutingControllers.put(newController.getId(), newController);
+ }
}
+ //TODO: Determine oldController properly when transfer is launched by Output Switcher.
notifyTransferred(matchingRequest != null ? matchingRequest.mController :
getSystemController(), newController);
}
@@ -676,7 +694,7 @@
if (removed) {
matchingController.release();
- notifyControllerReleased(matchingController);
+ notifyStopped(matchingController);
}
}
@@ -733,16 +751,16 @@
}
}
- private void notifyControllerUpdated(RoutingController controller) {
- for (ControllerCallbackRecord record: mControllerCallbackRecords) {
- record.mExecutor.execute(() -> record.mCallback.onControllerUpdated(controller));
+ private void notifyStopped(RoutingController controller) {
+ for (TransferCallbackRecord record: mTransferCallbackRecords) {
+ record.mExecutor.execute(
+ () -> record.mTransferCallback.onStopped(controller));
}
}
- private void notifyControllerReleased(RoutingController controller) {
- for (TransferCallbackRecord record: mTransferCallbackRecords) {
- record.mExecutor.execute(
- () -> record.mTransferCallback.onTransferred(controller, null));
+ private void notifyControllerUpdated(RoutingController controller) {
+ for (ControllerCallbackRecord record: mControllerCallbackRecords) {
+ record.mExecutor.execute(() -> record.mCallback.onControllerUpdated(controller));
}
}
@@ -783,20 +801,26 @@
* This can happen by calling {@link #transferTo(MediaRoute2Info)} or
* {@link RoutingController#release()}.
*
- * @param oldController the previous controller that controlled routing.
- * @param newController the new controller to control routing or {@code null} if the
- * previous controller is released.
+ * @param oldController the previous controller that controlled routing
+ * @param newController the new controller to control routing
* @see #transferTo(MediaRoute2Info)
*/
public void onTransferred(@NonNull RoutingController oldController,
- @Nullable RoutingController newController) {}
+ @NonNull RoutingController newController) {}
/**
* Called when {@link #transferTo(MediaRoute2Info)} failed.
*
- * @param requestedRoute the route info which was used for the transfer.
+ * @param requestedRoute the route info which was used for the transfer
*/
public void onTransferFailed(@NonNull MediaRoute2Info requestedRoute) {}
+
+ /**
+ * Called when a media routing stops. It can be stopped by a user or a provider.
+ *
+ * @param controller the controller that controlled the stopped media routing.
+ */
+ public void onStopped(@NonNull RoutingController controller) { }
}
/**
@@ -1181,7 +1205,7 @@
}
if (removed) {
- mHandler.post(() -> notifyControllerReleased(RoutingController.this));
+ mHandler.post(() -> notifyStopped(RoutingController.this));
}
if (stub != null) {
@@ -1378,9 +1402,9 @@
}
@Override
- public void notifySessionCreated(@Nullable RoutingSessionInfo sessionInfo, int requestId) {
+ public void notifySessionCreated(int requestId, @Nullable RoutingSessionInfo sessionInfo) {
mHandler.sendMessage(obtainMessage(MediaRouter2::createControllerOnHandler,
- MediaRouter2.this, sessionInfo, requestId));
+ MediaRouter2.this, requestId, sessionInfo));
}
@Override
diff --git a/media/java/android/media/MediaRouter2Manager.java b/media/java/android/media/MediaRouter2Manager.java
index cf45328..88bcd6a 100644
--- a/media/java/android/media/MediaRouter2Manager.java
+++ b/media/java/android/media/MediaRouter2Manager.java
@@ -50,7 +50,7 @@
* A class that monitors and controls media routing of other apps.
* @hide
*/
-public class MediaRouter2Manager {
+public final class MediaRouter2Manager {
private static final String TAG = "MR2Manager";
private static final Object sLock = new Object();
@@ -61,7 +61,7 @@
final String mPackageName;
- private Context mContext;
+ private final Context mContext;
@GuardedBy("sLock")
private Client mClient;
private final IMediaRouterService mMediaRouterService;
@@ -74,7 +74,7 @@
@NonNull
final ConcurrentMap<String, List<String>> mPreferredFeaturesMap = new ConcurrentHashMap<>();
- private AtomicInteger mNextRequestId = new AtomicInteger(1);
+ private final AtomicInteger mNextRequestId = new AtomicInteger(1);
/**
* Gets an instance of media router manager that controls media route of other applications.
@@ -329,7 +329,7 @@
try {
int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.requestCreateSessionWithManager(
- client, sessionInfo.getClientPackageName(), route, requestId);
+ client, requestId, sessionInfo.getClientPackageName(), route);
} catch (RemoteException ex) {
Log.e(TAG, "Unable to select media route", ex);
}
@@ -373,7 +373,7 @@
if (client != null) {
try {
int requestId = mNextRequestId.getAndIncrement();
- mMediaRouterService.setRouteVolumeWithManager(client, route, volume, requestId);
+ mMediaRouterService.setRouteVolumeWithManager(client, requestId, route, volume);
} catch (RemoteException ex) {
Log.e(TAG, "Unable to send control request.", ex);
}
@@ -406,7 +406,7 @@
try {
int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.setSessionVolumeWithManager(
- client, sessionInfo.getId(), volume, requestId);
+ client, requestId, sessionInfo.getId(), volume);
} catch (RemoteException ex) {
Log.e(TAG, "Unable to send control request.", ex);
}
@@ -594,7 +594,7 @@
try {
int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.selectRouteWithManager(
- mClient, sessionInfo.getId(), route, requestId);
+ mClient, requestId, sessionInfo.getId(), route);
} catch (RemoteException ex) {
Log.e(TAG, "selectRoute: Failed to send a request.", ex);
}
@@ -639,7 +639,7 @@
try {
int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.deselectRouteWithManager(
- mClient, sessionInfo.getId(), route, requestId);
+ mClient, requestId, sessionInfo.getId(), route);
} catch (RemoteException ex) {
Log.e(TAG, "deselectRoute: Failed to send a request.", ex);
}
@@ -675,7 +675,7 @@
try {
int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.transferToRouteWithManager(
- mClient, sessionInfo.getId(), route, requestId);
+ mClient, requestId, sessionInfo.getId(), route);
} catch (RemoteException ex) {
Log.e(TAG, "transferToRoute: Failed to send a request.", ex);
}
@@ -703,7 +703,7 @@
try {
int requestId = mNextRequestId.getAndIncrement();
mMediaRouterService.releaseSessionWithManager(
- mClient, sessionInfo.getId(), requestId);
+ mClient, requestId, sessionInfo.getId());
} catch (RemoteException ex) {
Log.e(TAG, "releaseSession: Failed to send a request", ex);
}
diff --git a/media/java/android/media/tv/tuner/Lnb.java b/media/java/android/media/tv/tuner/Lnb.java
index 7932dcb..ea06632 100644
--- a/media/java/android/media/tv/tuner/Lnb.java
+++ b/media/java/android/media/tv/tuner/Lnb.java
@@ -156,7 +156,7 @@
private long mNativeContext;
- Lnb(int id) {
+ private Lnb(int id) {
mId = id;
}
diff --git a/media/java/android/media/tv/tuner/Tuner.java b/media/java/android/media/tv/tuner/Tuner.java
index bcbc12b..08a33f1 100644
--- a/media/java/android/media/tv/tuner/Tuner.java
+++ b/media/java/android/media/tv/tuner/Tuner.java
@@ -43,7 +43,11 @@
import android.media.tv.tuner.frontend.FrontendStatus.FrontendStatusType;
import android.media.tv.tuner.frontend.OnTuneEventListener;
import android.media.tv.tuner.frontend.ScanCallback;
+import android.media.tv.tunerresourcemanager.ResourceClientProfile;
+import android.media.tv.tunerresourcemanager.TunerLnbRequest;
+import android.media.tv.tunerresourcemanager.TunerResourceManager;
import android.os.Handler;
+import android.os.HandlerExecutor;
import android.os.Looper;
import android.os.Message;
@@ -67,6 +71,7 @@
private static final String TAG = "MediaTvTuner";
private static final boolean DEBUG = false;
+ private static final int MSG_RESOURCE_LOST = 1;
private static final int MSG_ON_FILTER_EVENT = 2;
private static final int MSG_ON_FILTER_STATUS = 3;
private static final int MSG_ON_LNB_EVENT = 4;
@@ -93,6 +98,8 @@
}
private final Context mContext;
+ private final TunerResourceManager mTunerResourceManager;
+ private final int mClientId;
private List<Integer> mFrontendIds;
private Frontend mFrontend;
@@ -102,6 +109,7 @@
private List<Integer> mLnbIds;
private Lnb mLnb;
+ private Integer mLnbId;
@Nullable
private OnTuneEventListener mOnTuneEventListener;
@Nullable
@@ -115,6 +123,15 @@
@Nullable
private Executor mOnResourceLostListenerExecutor;
+
+ private final TunerResourceManager.ResourcesReclaimListener mResourceListener =
+ new TunerResourceManager.ResourcesReclaimListener() {
+ @Override
+ public void onReclaimResources() {
+ mHandler.sendMessage(mHandler.obtainMessage(MSG_RESOURCE_LOST));
+ }
+ };
+
/**
* Constructs a Tuner instance.
*
@@ -127,6 +144,14 @@
@TvInputService.PriorityHintUseCaseType int useCase) {
nativeSetup();
mContext = context;
+ mTunerResourceManager = (TunerResourceManager)
+ context.getSystemService(Context.TV_TUNER_RESOURCE_MGR_SERVICE);
+
+ int[] clientId = new int[1];
+ ResourceClientProfile profile = new ResourceClientProfile(tvInputSessionId, useCase);
+ mTunerResourceManager.registerClientProfile(
+ profile, new HandlerExecutor(mHandler), mResourceListener, clientId);
+ mClientId = clientId[0];
}
/**
@@ -226,6 +251,7 @@
private native List<Integer> nativeGetLnbIds();
private native Lnb nativeOpenLnbById(int id);
+ private native Lnb nativeOpenLnbByName(String name);
private native Descrambler nativeOpenDescrambler();
@@ -275,6 +301,14 @@
}
break;
}
+ case MSG_RESOURCE_LOST: {
+ if (mOnResourceLostListener != null
+ && mOnResourceLostListenerExecutor != null) {
+ mOnResourceLostListenerExecutor.execute(
+ () -> mOnResourceLostListener.onResourceLost(Tuner.this));
+ }
+ break;
+ }
default:
// fall through
}
@@ -698,7 +732,10 @@
Objects.requireNonNull(executor, "executor must not be null");
Objects.requireNonNull(cb, "LnbCallback must not be null");
TunerUtils.checkTunerPermission(mContext);
- return openLnbByName(null, executor, cb);
+ if (mLnbId == null && !requestLnb()) {
+ return null;
+ }
+ return nativeOpenLnbById(mLnbId);
}
/**
@@ -714,11 +751,21 @@
@Nullable
public Lnb openLnbByName(@NonNull String name, @CallbackExecutor @NonNull Executor executor,
@NonNull LnbCallback cb) {
+ Objects.requireNonNull(name, "LNB name must not be null");
Objects.requireNonNull(executor, "executor must not be null");
Objects.requireNonNull(cb, "LnbCallback must not be null");
TunerUtils.checkTunerPermission(mContext);
- // TODO: use resource manager to get LNB ID.
- return new Lnb(0);
+ return nativeOpenLnbByName(name);
+ }
+
+ private boolean requestLnb() {
+ int[] lnbId = new int[1];
+ TunerLnbRequest request = new TunerLnbRequest(mClientId);
+ boolean granted = mTunerResourceManager.requestLnb(request, lnbId);
+ if (granted) {
+ mLnbId = lnbId[0];
+ }
+ return granted;
}
/**
diff --git a/media/java/android/media/tv/tuner/dvr/DvrPlayback.java b/media/java/android/media/tv/tuner/dvr/DvrPlayback.java
index dbd9db4..37a016e 100644
--- a/media/java/android/media/tv/tuner/dvr/DvrPlayback.java
+++ b/media/java/android/media/tv/tuner/dvr/DvrPlayback.java
@@ -69,7 +69,7 @@
*/
public static final int PLAYBACK_STATUS_FULL = Constants.PlaybackStatus.SPACE_FULL;
- long mNativeContext;
+ private long mNativeContext;
private native int nativeAttachFilter(Filter filter);
private native int nativeDetachFilter(Filter filter);
diff --git a/media/java/android/media/tv/tuner/dvr/DvrRecorder.java b/media/java/android/media/tv/tuner/dvr/DvrRecorder.java
index c1c6c62..d06356c 100644
--- a/media/java/android/media/tv/tuner/dvr/DvrRecorder.java
+++ b/media/java/android/media/tv/tuner/dvr/DvrRecorder.java
@@ -30,7 +30,7 @@
*/
@SystemApi
public class DvrRecorder implements AutoCloseable {
- long mNativeContext;
+ private long mNativeContext;
private native int nativeAttachFilter(Filter filter);
private native int nativeDetachFilter(Filter filter);
diff --git a/media/java/android/media/tv/tuner/filter/AlpFilterConfiguration.java b/media/java/android/media/tv/tuner/filter/AlpFilterConfiguration.java
index 7b29494..8a29442 100644
--- a/media/java/android/media/tv/tuner/filter/AlpFilterConfiguration.java
+++ b/media/java/android/media/tv/tuner/filter/AlpFilterConfiguration.java
@@ -18,6 +18,7 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.content.Context;
@@ -33,7 +34,7 @@
* @hide
*/
@SystemApi
-public class AlpFilterConfiguration extends FilterConfiguration {
+public final class AlpFilterConfiguration extends FilterConfiguration {
/**
* IPv4 packet type.
*/
@@ -123,9 +124,10 @@
/**
* Builder for {@link AlpFilterConfiguration}.
*/
- public static class Builder extends FilterConfiguration.Builder<Builder> {
+ public static final class Builder {
private int mPacketType;
private int mLengthType;
+ private Settings mSettings;
private Builder() {
}
@@ -150,16 +152,20 @@
}
/**
+ * Sets filter settings.
+ */
+ @NonNull
+ public Builder setSettings(@Nullable Settings settings) {
+ mSettings = settings;
+ return this;
+ }
+
+ /**
* Builds a {@link AlpFilterConfiguration} object.
*/
@NonNull
public AlpFilterConfiguration build() {
return new AlpFilterConfiguration(mSettings, mPacketType, mLengthType);
}
-
- @Override
- Builder self() {
- return this;
- }
}
}
diff --git a/media/java/android/media/tv/tuner/filter/Filter.java b/media/java/android/media/tv/tuner/filter/Filter.java
index 52bdb59..4777fe8 100644
--- a/media/java/android/media/tv/tuner/filter/Filter.java
+++ b/media/java/android/media/tv/tuner/filter/Filter.java
@@ -225,6 +225,7 @@
mCallback = cb;
mExecutor = executor;
}
+
/** @hide */
public FilterCallback getCallback() {
return mCallback;
diff --git a/media/java/android/media/tv/tuner/filter/FilterConfiguration.java b/media/java/android/media/tv/tuner/filter/FilterConfiguration.java
index a8c9356..dd7e5fc 100644
--- a/media/java/android/media/tv/tuner/filter/FilterConfiguration.java
+++ b/media/java/android/media/tv/tuner/filter/FilterConfiguration.java
@@ -16,7 +16,6 @@
package android.media.tv.tuner.filter;
-import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
@@ -48,26 +47,4 @@
public Settings getSettings() {
return mSettings;
}
-
- /**
- * Builder for {@link FilterConfiguration}.
- *
- * @param <T> The subclass to be built.
- */
- public abstract static class Builder<T extends Builder<T>> {
- /* package */ Settings mSettings;
-
- /* package */ Builder() {
- }
-
- /**
- * Sets filter settings.
- */
- @NonNull
- public T setSettings(@Nullable Settings settings) {
- mSettings = settings;
- return self();
- }
- /* package */ abstract T self();
- }
}
diff --git a/media/java/android/media/tv/tuner/filter/IpFilterConfiguration.java b/media/java/android/media/tv/tuner/filter/IpFilterConfiguration.java
index a8dbfa5..04f3410 100644
--- a/media/java/android/media/tv/tuner/filter/IpFilterConfiguration.java
+++ b/media/java/android/media/tv/tuner/filter/IpFilterConfiguration.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.filter;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.Size;
import android.annotation.SystemApi;
@@ -29,7 +30,7 @@
* @hide
*/
@SystemApi
-public class IpFilterConfiguration extends FilterConfiguration {
+public final class IpFilterConfiguration extends FilterConfiguration {
private final byte[] mSrcIpAddress;
private final byte[] mDstIpAddress;
private final int mSrcPort;
@@ -104,12 +105,13 @@
/**
* Builder for {@link IpFilterConfiguration}.
*/
- public static class Builder extends FilterConfiguration.Builder<Builder> {
+ public static final class Builder {
private byte[] mSrcIpAddress;
private byte[] mDstIpAddress;
private int mSrcPort;
private int mDstPort;
private boolean mPassthrough;
+ private Settings mSettings;
private Builder() {
}
@@ -156,6 +158,15 @@
}
/**
+ * Sets filter settings.
+ */
+ @NonNull
+ public Builder setSettings(@Nullable Settings settings) {
+ mSettings = settings;
+ return this;
+ }
+
+ /**
* Builds a {@link IpFilterConfiguration} object.
*/
@NonNull
@@ -169,10 +180,5 @@
return new IpFilterConfiguration(
mSettings, mSrcIpAddress, mDstIpAddress, mSrcPort, mDstPort, mPassthrough);
}
-
- @Override
- Builder self() {
- return this;
- }
}
}
diff --git a/media/java/android/media/tv/tuner/filter/MmtpFilterConfiguration.java b/media/java/android/media/tv/tuner/filter/MmtpFilterConfiguration.java
index 0601829..c0453b4 100644
--- a/media/java/android/media/tv/tuner/filter/MmtpFilterConfiguration.java
+++ b/media/java/android/media/tv/tuner/filter/MmtpFilterConfiguration.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.filter;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.content.Context;
@@ -28,7 +29,7 @@
* @hide
*/
@SystemApi
-public class MmtpFilterConfiguration extends FilterConfiguration {
+public final class MmtpFilterConfiguration extends FilterConfiguration {
private final int mMmtpPid;
private MmtpFilterConfiguration(Settings settings, int mmtpPid) {
@@ -65,8 +66,9 @@
/**
* Builder for {@link IpFilterConfiguration}.
*/
- public static class Builder extends FilterConfiguration.Builder<Builder> {
+ public static final class Builder {
private int mMmtpPid;
+ private Settings mSettings;
private Builder() {
}
@@ -81,16 +83,20 @@
}
/**
+ * Sets filter settings.
+ */
+ @NonNull
+ public Builder setSettings(@Nullable Settings settings) {
+ mSettings = settings;
+ return this;
+ }
+
+ /**
* Builds a {@link IpFilterConfiguration} object.
*/
@NonNull
public MmtpFilterConfiguration build() {
return new MmtpFilterConfiguration(mSettings, mMmtpPid);
}
-
- @Override
- Builder self() {
- return this;
- }
}
}
diff --git a/media/java/android/media/tv/tuner/filter/TlvFilterConfiguration.java b/media/java/android/media/tv/tuner/filter/TlvFilterConfiguration.java
index ac4fc83..c5191bf 100644
--- a/media/java/android/media/tv/tuner/filter/TlvFilterConfiguration.java
+++ b/media/java/android/media/tv/tuner/filter/TlvFilterConfiguration.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.filter;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.content.Context;
@@ -28,7 +29,7 @@
* @hide
*/
@SystemApi
-public class TlvFilterConfiguration extends FilterConfiguration {
+public final class TlvFilterConfiguration extends FilterConfiguration {
/**
* IPv4 packet type.
*/
@@ -108,10 +109,11 @@
/**
* Builder for {@link TlvFilterConfiguration}.
*/
- public static class Builder extends FilterConfiguration.Builder<Builder> {
+ public static final class Builder {
private int mPacketType;
private boolean mIsCompressedIpPacket;
private boolean mPassthrough;
+ private Settings mSettings;
private Builder() {
}
@@ -144,6 +146,15 @@
}
/**
+ * Sets filter settings.
+ */
+ @NonNull
+ public Builder setSettings(@Nullable Settings settings) {
+ mSettings = settings;
+ return this;
+ }
+
+ /**
* Builds a {@link TlvFilterConfiguration} object.
*/
@NonNull
@@ -151,10 +162,5 @@
return new TlvFilterConfiguration(
mSettings, mPacketType, mIsCompressedIpPacket, mPassthrough);
}
-
- @Override
- Builder self() {
- return this;
- }
}
}
diff --git a/media/java/android/media/tv/tuner/filter/TsFilterConfiguration.java b/media/java/android/media/tv/tuner/filter/TsFilterConfiguration.java
index 6a8b6da..a7140eb 100644
--- a/media/java/android/media/tv/tuner/filter/TsFilterConfiguration.java
+++ b/media/java/android/media/tv/tuner/filter/TsFilterConfiguration.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.filter;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.content.Context;
@@ -28,7 +29,7 @@
* @hide
*/
@SystemApi
-public class TsFilterConfiguration extends FilterConfiguration {
+public final class TsFilterConfiguration extends FilterConfiguration {
private final int mTpid;
private TsFilterConfiguration(Settings settings, int tpid) {
@@ -63,8 +64,9 @@
/**
* Builder for {@link TsFilterConfiguration}.
*/
- public static class Builder extends FilterConfiguration.Builder<Builder> {
+ public static final class Builder {
private int mTpid;
+ private Settings mSettings;
private Builder() {
}
@@ -81,16 +83,20 @@
}
/**
+ * Sets filter settings.
+ */
+ @NonNull
+ public Builder setSettings(@Nullable Settings settings) {
+ mSettings = settings;
+ return this;
+ }
+
+ /**
* Builds a {@link TsFilterConfiguration} object.
*/
@NonNull
public TsFilterConfiguration build() {
return new TsFilterConfiguration(mSettings, mTpid);
}
-
- @Override
- Builder self() {
- return this;
- }
}
}
diff --git a/media/java/android/media/tv/tuner/frontend/AnalogFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/AnalogFrontendSettings.java
index 7b85fa8..382cc85 100644
--- a/media/java/android/media/tv/tuner/frontend/AnalogFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/AnalogFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -213,13 +214,24 @@
/**
* Builder for {@link AnalogFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mSignalType;
private int mSifStandard;
private Builder() {}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets analog signal type.
*/
@NonNull
@@ -244,10 +256,5 @@
public AnalogFrontendSettings build() {
return new AnalogFrontendSettings(mFrequency, mSignalType, mSifStandard);
}
-
- @Override
- Builder self() {
- return this;
- }
}
}
diff --git a/media/java/android/media/tv/tuner/frontend/Atsc3FrontendSettings.java b/media/java/android/media/tv/tuner/frontend/Atsc3FrontendSettings.java
index b40ab00..1394716 100644
--- a/media/java/android/media/tv/tuner/frontend/Atsc3FrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/Atsc3FrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -325,7 +326,8 @@
/**
* Builder for {@link Atsc3FrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mBandwidth;
private int mDemodOutputFormat;
private Atsc3PlpSettings[] mPlpSettings;
@@ -334,6 +336,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets bandwidth.
*/
@NonNull
@@ -366,11 +378,6 @@
return new Atsc3FrontendSettings(
mFrequency, mBandwidth, mDemodOutputFormat, mPlpSettings);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tuner/frontend/AtscFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/AtscFrontendSettings.java
index fc82a1c..53352f0 100644
--- a/media/java/android/media/tv/tuner/frontend/AtscFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/AtscFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -91,13 +92,24 @@
/**
* Builder for {@link AtscFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mModulation;
private Builder() {
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Modulation.
*/
@NonNull
@@ -113,11 +125,6 @@
public AtscFrontendSettings build() {
return new AtscFrontendSettings(mFrequency, mModulation);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tuner/frontend/DvbcFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/DvbcFrontendSettings.java
index 705d520..6d58570 100644
--- a/media/java/android/media/tv/tuner/frontend/DvbcFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/DvbcFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -144,17 +145,17 @@
private final int mModulation;
- private final long mFec;
+ private final long mInnerFec;
private final int mSymbolRate;
private final int mOuterFec;
private final int mAnnex;
private final int mSpectralInversion;
- private DvbcFrontendSettings(int frequency, int modulation, long fec, int symbolRate,
+ private DvbcFrontendSettings(int frequency, int modulation, long innerFec, int symbolRate,
int outerFec, int annex, int spectralInversion) {
super(frequency);
mModulation = modulation;
- mFec = fec;
+ mInnerFec = innerFec;
mSymbolRate = symbolRate;
mOuterFec = outerFec;
mAnnex = annex;
@@ -172,8 +173,8 @@
* Gets Inner Forward Error Correction.
*/
@InnerFec
- public long getFec() {
- return mFec;
+ public long getInnerFec() {
+ return mInnerFec;
}
/**
* Gets Symbol Rate in symbols per second.
@@ -218,9 +219,10 @@
/**
* Builder for {@link DvbcFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mModulation;
- private long mFec;
+ private long mInnerFec;
private int mSymbolRate;
private int mOuterFec;
private int mAnnex;
@@ -230,6 +232,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Modulation.
*/
@NonNull
@@ -241,8 +253,8 @@
* Sets Inner Forward Error Correction.
*/
@NonNull
- public Builder setFec(@InnerFec long fec) {
- mFec = fec;
+ public Builder setInnerFec(@InnerFec long fec) {
+ mInnerFec = fec;
return this;
}
/**
@@ -283,13 +295,8 @@
*/
@NonNull
public DvbcFrontendSettings build() {
- return new DvbcFrontendSettings(mFrequency, mModulation, mFec, mSymbolRate, mOuterFec,
- mAnnex, mSpectralInversion);
- }
-
- @Override
- Builder self() {
- return this;
+ return new DvbcFrontendSettings(mFrequency, mModulation, mInnerFec, mSymbolRate,
+ mOuterFec, mAnnex, mSpectralInversion);
}
}
diff --git a/media/java/android/media/tv/tuner/frontend/DvbsFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/DvbsFrontendSettings.java
index 4a4fed5..9c45dd1 100644
--- a/media/java/android/media/tv/tuner/frontend/DvbsFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/DvbsFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
@@ -303,7 +304,8 @@
/**
* Builder for {@link DvbsFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mModulation;
private DvbsCodeRate mCodeRate;
private int mSymbolRate;
@@ -317,6 +319,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Modulation.
*/
@NonNull
@@ -389,11 +401,6 @@
return new DvbsFrontendSettings(mFrequency, mModulation, mCodeRate, mSymbolRate,
mRolloff, mPilot, mInputStreamId, mStandard, mVcmMode);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tuner/frontend/DvbtFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/DvbtFrontendSettings.java
index e99fd36f..4accabb 100644
--- a/media/java/android/media/tv/tuner/frontend/DvbtFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/DvbtFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -125,9 +126,9 @@
/** @hide */
@IntDef(flag = true,
prefix = "CONSTELLATION_",
- value = {CONSTELLATION_UNDEFINED, CONSTELLATION_AUTO, CONSTELLATION_CONSTELLATION_QPSK,
- CONSTELLATION_CONSTELLATION_16QAM, CONSTELLATION_CONSTELLATION_64QAM,
- CONSTELLATION_CONSTELLATION_256QAM})
+ value = {CONSTELLATION_UNDEFINED, CONSTELLATION_AUTO, CONSTELLATION_QPSK,
+ CONSTELLATION_16QAM, CONSTELLATION_64QAM,
+ CONSTELLATION_256QAM})
@Retention(RetentionPolicy.SOURCE)
public @interface Constellation {}
@@ -142,22 +143,22 @@
/**
* QPSK Constellation.
*/
- public static final int CONSTELLATION_CONSTELLATION_QPSK =
+ public static final int CONSTELLATION_QPSK =
Constants.FrontendDvbtConstellation.CONSTELLATION_QPSK;
/**
* 16QAM Constellation.
*/
- public static final int CONSTELLATION_CONSTELLATION_16QAM =
+ public static final int CONSTELLATION_16QAM =
Constants.FrontendDvbtConstellation.CONSTELLATION_16QAM;
/**
* 64QAM Constellation.
*/
- public static final int CONSTELLATION_CONSTELLATION_64QAM =
+ public static final int CONSTELLATION_64QAM =
Constants.FrontendDvbtConstellation.CONSTELLATION_64QAM;
/**
* 256QAM Constellation.
*/
- public static final int CONSTELLATION_CONSTELLATION_256QAM =
+ public static final int CONSTELLATION_256QAM =
Constants.FrontendDvbtConstellation.CONSTELLATION_256QAM;
@@ -275,11 +276,11 @@
@IntDef(flag = true,
prefix = "GUARD_INTERVAL_",
value = {GUARD_INTERVAL_UNDEFINED, GUARD_INTERVAL_AUTO,
- GUARD_INTERVAL_INTERVAL_1_32, GUARD_INTERVAL_INTERVAL_1_16,
- GUARD_INTERVAL_INTERVAL_1_8, GUARD_INTERVAL_INTERVAL_1_4,
- GUARD_INTERVAL_INTERVAL_1_128,
- GUARD_INTERVAL_INTERVAL_19_128,
- GUARD_INTERVAL_INTERVAL_19_256})
+ GUARD_INTERVAL_1_32, GUARD_INTERVAL_1_16,
+ GUARD_INTERVAL_1_8, GUARD_INTERVAL_1_4,
+ GUARD_INTERVAL_1_128,
+ GUARD_INTERVAL_19_128,
+ GUARD_INTERVAL_19_256})
@Retention(RetentionPolicy.SOURCE)
public @interface GuardInterval {}
@@ -295,37 +296,37 @@
/**
* 1/32 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_1_32 =
+ public static final int GUARD_INTERVAL_1_32 =
Constants.FrontendDvbtGuardInterval.INTERVAL_1_32;
/**
* 1/16 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_1_16 =
+ public static final int GUARD_INTERVAL_1_16 =
Constants.FrontendDvbtGuardInterval.INTERVAL_1_16;
/**
* 1/8 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_1_8 =
+ public static final int GUARD_INTERVAL_1_8 =
Constants.FrontendDvbtGuardInterval.INTERVAL_1_8;
/**
* 1/4 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_1_4 =
+ public static final int GUARD_INTERVAL_1_4 =
Constants.FrontendDvbtGuardInterval.INTERVAL_1_4;
/**
* 1/128 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_1_128 =
+ public static final int GUARD_INTERVAL_1_128 =
Constants.FrontendDvbtGuardInterval.INTERVAL_1_128;
/**
* 19/128 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_19_128 =
+ public static final int GUARD_INTERVAL_19_128 =
Constants.FrontendDvbtGuardInterval.INTERVAL_19_128;
/**
* 19/256 Guard Interval.
*/
- public static final int GUARD_INTERVAL_INTERVAL_19_256 =
+ public static final int GUARD_INTERVAL_19_256 =
Constants.FrontendDvbtGuardInterval.INTERVAL_19_256;
/** @hide */
@@ -435,14 +436,14 @@
* Gets Code Rate for High Priority level.
*/
@CodeRate
- public int getHpCodeRate() {
+ public int getHighPriorityCodeRate() {
return mHpCodeRate;
}
/**
* Gets Code Rate for Low Priority level.
*/
@CodeRate
- public int getLpCodeRate() {
+ public int getLowPriorityCodeRate() {
return mLpCodeRate;
}
/**
@@ -506,7 +507,8 @@
/**
* Builder for {@link DvbtFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mTransmissionMode;
private int mBandwidth;
private int mConstellation;
@@ -525,6 +527,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Transmission Mode.
*/
@NonNull
@@ -560,7 +572,7 @@
* Sets Code Rate for High Priority level.
*/
@NonNull
- public Builder setHpCodeRate(@CodeRate int hpCodeRate) {
+ public Builder setHighPriorityCodeRate(@CodeRate int hpCodeRate) {
mHpCodeRate = hpCodeRate;
return this;
}
@@ -568,7 +580,7 @@
* Sets Code Rate for Low Priority level.
*/
@NonNull
- public Builder setLpCodeRate(@CodeRate int lpCodeRate) {
+ public Builder setLowPriorityCodeRate(@CodeRate int lpCodeRate) {
mLpCodeRate = lpCodeRate;
return this;
}
@@ -638,11 +650,6 @@
mConstellation, mHierarchy, mHpCodeRate, mLpCodeRate, mGuardInterval,
mIsHighPriority, mStandard, mIsMiso, mPlpMode, mPlpId, mPlpGroupId);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tuner/frontend/FrontendSettings.java b/media/java/android/media/tv/tuner/frontend/FrontendSettings.java
index 9071526..2f2fa97 100644
--- a/media/java/android/media/tv/tuner/frontend/FrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/FrontendSettings.java
@@ -17,9 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
-import android.annotation.IntRange;
import android.annotation.LongDef;
-import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.hardware.tv.tuner.V1_0.Constants;
@@ -265,27 +263,4 @@
public int getFrequency() {
return mFrequency;
}
-
- /**
- * Builder for {@link FrontendSettings}.
- *
- * @param <T> The subclass to be built.
- */
- public abstract static class Builder<T extends Builder<T>> {
- /* package */ int mFrequency;
-
- /* package */ Builder() {}
-
- /**
- * Sets frequency in Hz.
- */
- @NonNull
- @IntRange(from = 1)
- public T setFrequency(int frequency) {
- mFrequency = frequency;
- return self();
- }
-
- /* package */ abstract T self();
- }
}
diff --git a/media/java/android/media/tv/tuner/frontend/FrontendStatus.java b/media/java/android/media/tv/tuner/frontend/FrontendStatus.java
index 63de0334..ea91ee9 100644
--- a/media/java/android/media/tv/tuner/frontend/FrontendStatus.java
+++ b/media/java/android/media/tv/tuner/frontend/FrontendStatus.java
@@ -304,7 +304,7 @@
* and ETSI EN 302 307-2 V1.1.1.
*/
@FrontendSettings.InnerFec
- public long getFec() {
+ public long getInnerFec() {
if (mInnerFec == null) {
throw new IllegalStateException();
}
diff --git a/media/java/android/media/tv/tuner/frontend/Isdbs3FrontendSettings.java b/media/java/android/media/tv/tuner/frontend/Isdbs3FrontendSettings.java
index 9b0e533..f385379 100644
--- a/media/java/android/media/tv/tuner/frontend/Isdbs3FrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/Isdbs3FrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -224,7 +225,8 @@
/**
* Builder for {@link Isdbs3FrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mStreamId;
private int mStreamIdType;
private int mModulation;
@@ -236,6 +238,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Stream ID.
*/
@NonNull
@@ -292,11 +304,6 @@
return new Isdbs3FrontendSettings(mFrequency, mStreamId, mStreamIdType, mModulation,
mCodeRate, mSymbolRate, mRolloff);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tuner/frontend/IsdbsFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/IsdbsFrontendSettings.java
index 14c08b1..4667b9b 100644
--- a/media/java/android/media/tv/tuner/frontend/IsdbsFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/IsdbsFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -208,7 +209,8 @@
/**
* Builder for {@link IsdbsFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mStreamId;
private int mStreamIdType;
private int mModulation;
@@ -220,6 +222,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Stream ID.
*/
@NonNull
@@ -276,11 +288,6 @@
return new IsdbsFrontendSettings(mFrequency, mStreamId, mStreamIdType, mModulation,
mCodeRate, mSymbolRate, mRolloff);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tuner/frontend/IsdbtFrontendSettings.java b/media/java/android/media/tv/tuner/frontend/IsdbtFrontendSettings.java
index de3c80d..b607623 100644
--- a/media/java/android/media/tv/tuner/frontend/IsdbtFrontendSettings.java
+++ b/media/java/android/media/tv/tuner/frontend/IsdbtFrontendSettings.java
@@ -17,6 +17,7 @@
package android.media.tv.tuner.frontend;
import android.annotation.IntDef;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
@@ -202,7 +203,8 @@
/**
* Builder for {@link IsdbtFrontendSettings}.
*/
- public static class Builder extends FrontendSettings.Builder<Builder> {
+ public static class Builder {
+ private int mFrequency;
private int mModulation;
private int mBandwidth;
private int mMode;
@@ -214,6 +216,16 @@
}
/**
+ * Sets frequency in Hz.
+ */
+ @NonNull
+ @IntRange(from = 1)
+ public Builder setFrequency(int frequency) {
+ mFrequency = frequency;
+ return this;
+ }
+
+ /**
* Sets Modulation.
*/
@NonNull
@@ -270,11 +282,6 @@
return new IsdbtFrontendSettings(mFrequency, mModulation, mBandwidth, mMode, mCodeRate,
mGuardInterval, mServiceAreaId);
}
-
- @Override
- Builder self() {
- return this;
- }
}
@Override
diff --git a/media/java/android/media/tv/tunerresourcemanager/ITunerResourceManager.aidl b/media/java/android/media/tv/tunerresourcemanager/ITunerResourceManager.aidl
index 20efaa1..77cac6e 100644
--- a/media/java/android/media/tv/tunerresourcemanager/ITunerResourceManager.aidl
+++ b/media/java/android/media/tv/tunerresourcemanager/ITunerResourceManager.aidl
@@ -19,6 +19,8 @@
import android.media.tv.tunerresourcemanager.CasSessionRequest;
import android.media.tv.tunerresourcemanager.IResourcesReclaimListener;
import android.media.tv.tunerresourcemanager.ResourceClientProfile;
+import android.media.tv.tunerresourcemanager.TunerDemuxRequest;
+import android.media.tv.tunerresourcemanager.TunerDescramblerRequest;
import android.media.tv.tunerresourcemanager.TunerFrontendInfo;
import android.media.tv.tunerresourcemanager.TunerFrontendRequest;
import android.media.tv.tunerresourcemanager.TunerLnbRequest;
@@ -148,6 +150,53 @@
void shareFrontend(in int selfClientId, in int targetClientId);
/*
+ * This API is used by the Tuner framework to request an available demux from the TunerHAL.
+ *
+ * <p>There are three possible scenarios:
+ * <ul>
+ * <li>If there is demux available, the API would send the handle back.
+ *
+ * <li>If no Demux is available but the current request info can show higher priority than
+ * other uses of demuxes, the API will send
+ * {@link IResourcesReclaimListener#onReclaimResources()} to the {@link Tuner}. Tuner would
+ * handle the resource reclaim on the holder of lower priority and notify the holder of its
+ * resource loss.
+ *
+ * <li>If no demux can be granted, the API would return false.
+ * <ul>
+ *
+ * @param request {@link TunerDemuxRequest} information of the current request.
+ * @param demuxHandle a one-element array to return the granted demux handle.
+ *
+ * @return true if there is demux granted.
+ */
+ boolean requestDemux(in TunerDemuxRequest request, out int[] demuxHandle);
+
+ /*
+ * This API is used by the Tuner framework to request an available descrambler from the
+ * TunerHAL.
+ *
+ * <p>There are three possible scenarios:
+ * <ul>
+ * <li>If there is descrambler available, the API would send the handle back.
+ *
+ * <li>If no Descrambler is available but the current request info can show higher priority than
+ * other uses of Descrambler, the API will send
+ * {@link IResourcesReclaimListener#onReclaimResources()} to the {@link Tuner}. Tuner would
+ * handle the resource reclaim on the holder of lower priority and notify the holder of its
+ * resource loss.
+ *
+ * <li>If no Descrambler can be granted, the API would return false.
+ * <ul>
+ *
+ * @param request {@link TunerDescramblerRequest} information of the current request.
+ * @param descramblerHandle a one-element array to return the granted descrambler handle.
+ *
+ * @return true if there is Descrambler granted.
+ */
+ boolean requestDescrambler(in TunerDescramblerRequest request, out int[] descramblerHandle);
+
+ /*
* This API is used by the Tuner framework to request an available Cas session. This session
* needs to be under the CAS system with the id indicated in the {@code request}.
*
@@ -210,6 +259,24 @@
void releaseFrontend(in int frontendId);
/*
+ * Notifies the TRM that the Demux with the given handle was released.
+ *
+ * <p>Client must call this whenever it releases a demux.
+ *
+ * @param demuxHandle the handle of the released Tuner Demux.
+ */
+ void releaseDemux(in int demuxHandle);
+
+ /*
+ * Notifies the TRM that the Descrambler with the given handle was released.
+ *
+ * <p>Client must call this whenever it releases a descrambler.
+ *
+ * @param demuxHandle the handle of the released Tuner Descrambler.
+ */
+ void releaseDescrambler(in int descramblerHandle);
+
+ /*
* Notifies the TRM that the given Cas session has been released.
*
* <p>Client must call this whenever it releases a Cas session.
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/media/java/android/media/tv/tunerresourcemanager/TunerDemuxRequest.aidl
similarity index 67%
copy from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
copy to media/java/android/media/tv/tunerresourcemanager/TunerDemuxRequest.aidl
index d691f41..919a215 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/media/java/android/media/tv/tunerresourcemanager/TunerDemuxRequest.aidl
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright 2020 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.
@@ -14,16 +14,11 @@
* limitations under the License.
*/
-package android.net.wifi;
+package android.media.tv.tunerresourcemanager;
/**
- * Interface for Wi-Fi score callback.
+ * Information required to request a Tuner Demux.
*
* @hide
*/
-oneway interface IScoreChangeCallback
-{
- void onScoreChange(int sessionId, int score);
-
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
-}
+parcelable TunerDemuxRequest;
\ No newline at end of file
diff --git a/media/java/android/media/tv/tunerresourcemanager/TunerDemuxRequest.java b/media/java/android/media/tv/tunerresourcemanager/TunerDemuxRequest.java
new file mode 100644
index 0000000..34a7761
--- /dev/null
+++ b/media/java/android/media/tv/tunerresourcemanager/TunerDemuxRequest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2020 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.tv.tunerresourcemanager;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * Information required to request a Tuner Demux.
+ *
+ * @hide
+ */
+public final class TunerDemuxRequest implements Parcelable {
+ static final String TAG = "TunerDemuxRequest";
+
+ public static final
+ @NonNull
+ Parcelable.Creator<TunerDemuxRequest> CREATOR =
+ new Parcelable.Creator<TunerDemuxRequest>() {
+ @Override
+ public TunerDemuxRequest createFromParcel(Parcel source) {
+ try {
+ return new TunerDemuxRequest(source);
+ } catch (Exception e) {
+ Log.e(TAG, "Exception creating TunerDemuxRequest from parcel", e);
+ return null;
+ }
+ }
+
+ @Override
+ public TunerDemuxRequest[] newArray(int size) {
+ return new TunerDemuxRequest[size];
+ }
+ };
+
+ /**
+ * Client id of the client that sends the request.
+ */
+ private final int mClientId;
+
+ private TunerDemuxRequest(@NonNull Parcel source) {
+ mClientId = source.readInt();
+ }
+
+ /**
+ * Constructs a new {@link TunerDemuxRequest} with the given parameters.
+ *
+ * @param clientId id of the client.
+ */
+ public TunerDemuxRequest(int clientId) {
+ mClientId = clientId;
+ }
+
+ /**
+ * Returns the id of the client.
+ */
+ public int getClientId() {
+ return mClientId;
+ }
+
+ // Parcelable
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @NonNull
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder(128);
+ b.append("TunerDemuxRequest {clientId=").append(mClientId);
+ b.append("}");
+ return b.toString();
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mClientId);
+ }
+}
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/media/java/android/media/tv/tunerresourcemanager/TunerDescramblerRequest.aidl
similarity index 67%
copy from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
copy to media/java/android/media/tv/tunerresourcemanager/TunerDescramblerRequest.aidl
index d691f41..fbafb3b 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/media/java/android/media/tv/tunerresourcemanager/TunerDescramblerRequest.aidl
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright 2020 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.
@@ -14,16 +14,11 @@
* limitations under the License.
*/
-package android.net.wifi;
+package android.media.tv.tunerresourcemanager;
/**
- * Interface for Wi-Fi score callback.
+ * Information required to request a Tuner Descrambler.
*
* @hide
*/
-oneway interface IScoreChangeCallback
-{
- void onScoreChange(int sessionId, int score);
-
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
-}
+parcelable TunerDescramblerRequest;
\ No newline at end of file
diff --git a/media/java/android/media/tv/tunerresourcemanager/TunerDescramblerRequest.java b/media/java/android/media/tv/tunerresourcemanager/TunerDescramblerRequest.java
new file mode 100644
index 0000000..5816287
--- /dev/null
+++ b/media/java/android/media/tv/tunerresourcemanager/TunerDescramblerRequest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2020 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.tv.tunerresourcemanager;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * Information required to request a Tuner Descrambler.
+ *
+ * @hide
+ */
+public final class TunerDescramblerRequest implements Parcelable {
+ static final String TAG = "TunerDescramblerRequest";
+
+ public static final
+ @NonNull
+ Parcelable.Creator<TunerDescramblerRequest> CREATOR =
+ new Parcelable.Creator<TunerDescramblerRequest>() {
+ @Override
+ public TunerDescramblerRequest createFromParcel(Parcel source) {
+ try {
+ return new TunerDescramblerRequest(source);
+ } catch (Exception e) {
+ Log.e(TAG, "Exception creating TunerDescramblerRequest from parcel", e);
+ return null;
+ }
+ }
+
+ @Override
+ public TunerDescramblerRequest[] newArray(int size) {
+ return new TunerDescramblerRequest[size];
+ }
+ };
+
+ /**
+ * Client id of the client that sends the request.
+ */
+ private final int mClientId;
+
+ private TunerDescramblerRequest(@NonNull Parcel source) {
+ mClientId = source.readInt();
+ }
+
+ /**
+ * Constructs a new {@link TunerDescramblerRequest} with the given parameters.
+ *
+ * @param clientId id of the client.
+ */
+ public TunerDescramblerRequest(int clientId) {
+ mClientId = clientId;
+ }
+
+ /**
+ * Returns the id of the client.
+ */
+ public int getClientId() {
+ return mClientId;
+ }
+
+ // Parcelable
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @NonNull
+ @Override
+ public String toString() {
+ StringBuilder b = new StringBuilder(128);
+ b.append("TunerDescramblerRequest {clientId=").append(mClientId);
+ b.append("}");
+ return b.toString();
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mClientId);
+ }
+}
diff --git a/media/java/android/media/tv/tunerresourcemanager/TunerResourceManager.java b/media/java/android/media/tv/tunerresourcemanager/TunerResourceManager.java
index 7c11ed4..9dddcd4 100644
--- a/media/java/android/media/tv/tunerresourcemanager/TunerResourceManager.java
+++ b/media/java/android/media/tv/tunerresourcemanager/TunerResourceManager.java
@@ -60,11 +60,7 @@
private static final String TAG = "TunerResourceManager";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
- public static final int INVALID_FRONTEND_ID = -1;
- public static final int INVALID_CAS_SESSION_RESOURCE_ID = -1;
- public static final int INVALID_LNB_ID = -1;
- public static final int INVALID_TV_INPUT_DEVICE_ID = -1;
- public static final int INVALID_TV_INPUT_PORT_ID = -1;
+ public static final int INVALID_RESOURCE_HANDLE = -1;
private final ITunerResourceManager mService;
private final int mUserId;
@@ -260,6 +256,71 @@
}
/**
+ * Requests a Tuner Demux resource.
+ *
+ * <p>There are three possible scenarios:
+ * <ul>
+ * <li>If there is Demux available, the API would send the handle back.
+ *
+ * <li>If no Demux is available but the current request has a higher priority than other uses of
+ * demuxes, the API will send {@link IResourcesReclaimListener#onReclaimResources()} to the
+ * {@link Tuner}. Tuner would handle the resource reclaim on the holder of lower priority and
+ * notify the holder of its resource loss.
+ *
+ * <li>If no Demux system can be granted, the API would return false.
+ * <ul>
+ *
+ * @param request {@link TunerDemuxRequest} information of the current request.
+ * @param demuxHandle a one-element array to return the granted Demux handle.
+ * If no Demux granted, this will return {@link #INVALID_RESOURCE_HANDLE}.
+ *
+ * @return true if there is Demux granted.
+ */
+ public boolean requestDemux(@NonNull TunerDemuxRequest request, @NonNull int[] demuxHandle) {
+ boolean result = false;
+ try {
+ result = mService.requestDemux(request, demuxHandle);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ return result;
+ }
+
+ /**
+ * Requests a Tuner Descrambler resource.
+ *
+ * <p>There are three possible scenarios:
+ * <ul>
+ * <li>If there is Descrambler available, the API would send the handle back.
+ *
+ * <li>If no Descrambler is available but the current request has a higher priority than other
+ * uses of descramblers, the API will send
+ * {@link IResourcesReclaimListener#onReclaimResources()} to the {@link Tuner}. Tuner would
+ * handle the resource reclaim on the holder of lower priority and notify the holder of its
+ * resource loss.
+ *
+ * <li>If no Descrambler system can be granted, the API would return false.
+ * <ul>
+ *
+ * @param request {@link TunerDescramblerRequest} information of the current request.
+ * @param descramblerHandle a one-element array to return the granted Descrambler handle.
+ * If no Descrambler granted, this will return
+ * {@link #INVALID_RESOURCE_HANDLE}.
+ *
+ * @return true if there is Descrambler granted.
+ */
+ public boolean requestDescrambler(@NonNull TunerDescramblerRequest request,
+ @NonNull int[] descramblerHandle) {
+ boolean result = false;
+ try {
+ result = mService.requestDescrambler(request, descramblerHandle);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ return result;
+ }
+
+ /**
* Requests a CAS session resource.
*
* <p>There are three possible scenarios:
@@ -345,6 +406,36 @@
}
/**
+ * Notifies the TRM that the Demux with the given handle has been released.
+ *
+ * <p>Client must call this whenever it releases an Demux.
+ *
+ * @param demuxHandle the handle of the released Tuner Demux.
+ */
+ public void releaseDemux(int demuxHandle) {
+ try {
+ mService.releaseDemux(demuxHandle);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Notifies the TRM that the Descrambler with the given handle has been released.
+ *
+ * <p>Client must call this whenever it releases an Descrambler.
+ *
+ * @param descramblerHandle the handle of the released Tuner Descrambler.
+ */
+ public void releaseDescrambler(int descramblerHandle) {
+ try {
+ mService.releaseDescrambler(descramblerHandle);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Notifies the TRM that the given Cas session has been released.
*
* <p>Client must call this whenever it releases a Cas session.
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index 737c95d..893e516 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -242,13 +242,6 @@
});
}
-void JMediaCodec::releaseAsync() {
- if (mCodec != NULL) {
- mCodec->releaseAsync();
- }
- mInitStatus = NO_INIT;
-}
-
JMediaCodec::~JMediaCodec() {
if (mLooper != NULL) {
/* MediaCodec and looper should have been released explicitly already
@@ -1131,10 +1124,7 @@
}
static void android_media_MediaCodec_release(JNIEnv *env, jobject thiz) {
- sp<JMediaCodec> codec = getMediaCodec(env, thiz);
- if (codec != NULL) {
- codec->releaseAsync();
- }
+ setMediaCodec(env, thiz, NULL);
}
static void throwCodecException(JNIEnv *env, status_t err, int32_t actionCode, const char *msg) {
@@ -2807,7 +2797,7 @@
static void android_media_MediaCodec_native_finalize(
JNIEnv *env, jobject thiz) {
- setMediaCodec(env, thiz, NULL);
+ android_media_MediaCodec_release(env, thiz);
}
// MediaCodec.LinearBlock
diff --git a/media/jni/android_media_MediaCodec.h b/media/jni/android_media_MediaCodec.h
index 400ce1b..8899fee 100644
--- a/media/jni/android_media_MediaCodec.h
+++ b/media/jni/android_media_MediaCodec.h
@@ -61,7 +61,6 @@
void registerSelf();
void release();
- void releaseAsync();
status_t enableOnFrameRenderedListener(jboolean enable);
diff --git a/media/jni/android_media_tv_Tuner.cpp b/media/jni/android_media_tv_Tuner.cpp
index 273c776..a37c9e5 100644
--- a/media/jni/android_media_tv_Tuner.cpp
+++ b/media/jni/android_media_tv_Tuner.cpp
@@ -34,19 +34,28 @@
using ::android::hardware::Void;
using ::android::hardware::hidl_bitfield;
using ::android::hardware::hidl_vec;
+using ::android::hardware::tv::tuner::V1_0::AudioExtraMetaData;
+using ::android::hardware::tv::tuner::V1_0::Constant;
using ::android::hardware::tv::tuner::V1_0::DataFormat;
using ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterSettings;
using ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterType;
using ::android::hardware::tv::tuner::V1_0::DemuxAlpLengthType;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterAvSettings;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterDownloadEvent;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterDownloadSettings;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterIpPayloadEvent;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterMediaEvent;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterMmtpRecordEvent;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterPesDataSettings;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterPesEvent;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterRecordSettings;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionBits;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionEvent;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionSettings;
using ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterTemiEvent;
+using ::android::hardware::tv::tuner::V1_0::DemuxFilterTsRecordEvent;
using ::android::hardware::tv::tuner::V1_0::DemuxIpAddress;
using ::android::hardware::tv::tuner::V1_0::DemuxIpFilterSettings;
using ::android::hardware::tv::tuner::V1_0::DemuxIpFilterType;
@@ -129,13 +138,16 @@
jfieldID filterContext;
jfieldID timeFilterContext;
jfieldID descramblerContext;
- jfieldID dvrContext;
+ jfieldID dvrRecorderContext;
+ jfieldID dvrPlaybackContext;
jmethodID frontendInitID;
jmethodID filterInitID;
jmethodID timeFilterInitID;
- jmethodID dvrInitID;
+ jmethodID dvrRecorderInitID;
+ jmethodID dvrPlaybackInitID;
jmethodID onFrontendEventID;
jmethodID onFilterStatusID;
+ jmethodID onFilterEventID;
jmethodID lnbInitID;
jmethodID onLnbEventID;
jmethodID descramblerInitID;
@@ -248,48 +260,287 @@
return linearBlock;
}
-jobject FilterCallback::getMediaEvent(const DemuxFilterEvent::Event& event) {
+jobjectArray FilterCallback::getSectionEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
JNIEnv *env = AndroidRuntime::getJNIEnv();
- jclass clazz = env->FindClass("android/media/tv/tuner/filter/MediaEvent");
- jmethodID eventInit = env->GetMethodID(clazz,
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/SectionEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(IIII)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterSectionEvent sectionEvent = event.section();
+
+ jint tableId = static_cast<jint>(sectionEvent.tableId);
+ jint version = static_cast<jint>(sectionEvent.version);
+ jint sectionNum = static_cast<jint>(sectionEvent.sectionNum);
+ jint dataLength = static_cast<jint>(sectionEvent.dataLength);
+
+ jobject obj =
+ env->NewObject(eventClazz, eventInit, tableId, version, sectionNum, dataLength);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getMediaEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/MediaEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz,
"<init>",
"(IZJJJLandroid/media/MediaCodec$LinearBlock;"
"ZJIZLandroid/media/tv/tuner/filter/AudioDescriptor;)V");
- DemuxFilterMediaEvent mediaEvent = event.media();
- uint32_t dataLength = mediaEvent.dataLength;
- const native_handle_t* h = mediaEvent.avMemory.getNativeHandle();
- jobject block = handleToLinearBlock(h, dataLength);
- // TODO: handle other fields
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterMediaEvent mediaEvent = event.media();
- return env->NewObject(clazz, eventInit, (jint) 0, (jboolean) 0, (jlong) 0, (jlong) 0, (jlong) 0,
- block, (jboolean) 0, (jlong) 0, (jint) 0, (jboolean) 0, NULL);
+ jobject audioDescriptor = NULL;
+ if (mediaEvent.extraMetaData.getDiscriminator()
+ == DemuxFilterMediaEvent::ExtraMetaData::hidl_discriminator::audio) {
+ jclass adClazz = env->FindClass("android/media/tv/tuner/filter/AudioDescriptor");
+ jmethodID adInit = env->GetMethodID(adClazz, "<init>", "(BBCBBB)V");
+
+ AudioExtraMetaData ad = mediaEvent.extraMetaData.audio();
+ jbyte adFade = static_cast<jbyte>(ad.adFade);
+ jbyte adPan = static_cast<jbyte>(ad.adPan);
+ jchar versionTextTag = static_cast<jchar>(ad.versionTextTag);
+ jbyte adGainCenter = static_cast<jbyte>(ad.adGainCenter);
+ jbyte adGainFront = static_cast<jbyte>(ad.adGainFront);
+ jbyte adGainSurround = static_cast<jbyte>(ad.adGainSurround);
+
+ audioDescriptor =
+ env->NewObject(adClazz, adInit, adFade, adPan, versionTextTag, adGainCenter,
+ adGainFront, adGainSurround);
+ }
+
+ jlong dataLength = static_cast<jlong>(mediaEvent.dataLength);
+ const native_handle_t* h = NULL;
+ jobject block = NULL;
+ if (mediaEvent.avMemory != NULL) {
+ h = mediaEvent.avMemory.getNativeHandle();
+ block = handleToLinearBlock(h, dataLength);
+ }
+
+ jint streamId = static_cast<jint>(mediaEvent.streamId);
+ jboolean isPtsPresent = static_cast<jboolean>(mediaEvent.isPtsPresent);
+ jlong pts = static_cast<jlong>(mediaEvent.pts);
+ jlong offset = static_cast<jlong>(mediaEvent.offset);
+ jboolean isSecureMemory = static_cast<jboolean>(mediaEvent.isSecureMemory);
+ jlong avDataId = static_cast<jlong>(mediaEvent.avDataId);
+ jint mpuSequenceNumber = static_cast<jint>(mediaEvent.mpuSequenceNumber);
+ jboolean isPesPrivateData = static_cast<jboolean>(mediaEvent.isPesPrivateData);
+
+ jobject obj =
+ env->NewObject(eventClazz, eventInit, streamId, isPtsPresent, pts, dataLength,
+ offset, block, isSecureMemory, avDataId, mpuSequenceNumber, isPesPrivateData,
+ audioDescriptor);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getPesEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/PesEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(III)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterPesEvent pesEvent = event.pes();
+
+ jint streamId = static_cast<jint>(pesEvent.streamId);
+ jint dataLength = static_cast<jint>(pesEvent.dataLength);
+ jint mpuSequenceNumber = static_cast<jint>(pesEvent.mpuSequenceNumber);
+
+ jobject obj =
+ env->NewObject(eventClazz, eventInit, streamId, dataLength, mpuSequenceNumber);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getTsRecordEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/TsRecordEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(IIIJ)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterTsRecordEvent tsRecordEvent = event.tsRecord();
+ DemuxPid pid = tsRecordEvent.pid;
+
+ jint jpid = static_cast<jint>(Constant::INVALID_TS_PID);
+
+ if (pid.getDiscriminator() == DemuxPid::hidl_discriminator::tPid) {
+ jpid = static_cast<jint>(pid.tPid());
+ } else if (pid.getDiscriminator() == DemuxPid::hidl_discriminator::mmtpPid) {
+ jpid = static_cast<jint>(pid.mmtpPid());
+ }
+
+ jint sc = 0;
+
+ if (tsRecordEvent.scIndexMask.getDiscriminator()
+ == DemuxFilterTsRecordEvent::ScIndexMask::hidl_discriminator::sc) {
+ sc = static_cast<jint>(tsRecordEvent.scIndexMask.sc());
+ } else if (tsRecordEvent.scIndexMask.getDiscriminator()
+ == DemuxFilterTsRecordEvent::ScIndexMask::hidl_discriminator::scHevc) {
+ sc = static_cast<jint>(tsRecordEvent.scIndexMask.scHevc());
+ }
+
+ jint ts = static_cast<jint>(tsRecordEvent.tsIndexMask);
+
+ jlong byteNumber = static_cast<jlong>(tsRecordEvent.byteNumber);
+
+ jobject obj =
+ env->NewObject(eventClazz, eventInit, jpid, ts, sc, byteNumber);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getMmtpRecordEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/MmtpRecordEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(IJ)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterMmtpRecordEvent mmtpRecordEvent = event.mmtpRecord();
+
+ jint scHevcIndexMask = static_cast<jint>(mmtpRecordEvent.scHevcIndexMask);
+ jlong byteNumber = static_cast<jlong>(mmtpRecordEvent.byteNumber);
+
+ jobject obj =
+ env->NewObject(eventClazz, eventInit, scHevcIndexMask, byteNumber);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getDownloadEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/DownloadEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(IIIII)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterDownloadEvent downloadEvent = event.download();
+
+ jint itemId = static_cast<jint>(downloadEvent.itemId);
+ jint mpuSequenceNumber = static_cast<jint>(downloadEvent.mpuSequenceNumber);
+ jint itemFragmentIndex = static_cast<jint>(downloadEvent.itemFragmentIndex);
+ jint lastItemFragmentIndex = static_cast<jint>(downloadEvent.lastItemFragmentIndex);
+ jint dataLength = static_cast<jint>(downloadEvent.dataLength);
+
+ jobject obj =
+ env->NewObject(eventClazz, eventInit, itemId, mpuSequenceNumber, itemFragmentIndex,
+ lastItemFragmentIndex, dataLength);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getIpPayloadEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/IpPayloadEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(I)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterIpPayloadEvent ipPayloadEvent = event.ipPayload();
+ jint dataLength = static_cast<jint>(ipPayloadEvent.dataLength);
+ jobject obj = env->NewObject(eventClazz, eventInit, dataLength);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
+}
+
+jobjectArray FilterCallback::getTemiEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/TemiEvent");
+ jmethodID eventInit = env->GetMethodID(eventClazz, "<init>", "(JB[B)V");
+
+ for (int i = 0; i < events.size(); i++) {
+ auto event = events[i];
+ DemuxFilterTemiEvent temiEvent = event.temi();
+ jlong pts = static_cast<jlong>(temiEvent.pts);
+ jbyte descrTag = static_cast<jbyte>(temiEvent.descrTag);
+ std::vector<uint8_t> descrData = temiEvent.descrData;
+
+ jbyteArray array = env->NewByteArray(descrData.size());
+ env->SetByteArrayRegion(
+ array, 0, descrData.size(), reinterpret_cast<jbyte*>(&descrData[0]));
+
+ jobject obj = env->NewObject(eventClazz, eventInit, pts, descrTag, array);
+ env->SetObjectArrayElement(arr, i, obj);
+ }
+ return arr;
}
Return<void> FilterCallback::onFilterEvent(const DemuxFilterEvent& filterEvent) {
ALOGD("FilterCallback::onFilterEvent");
JNIEnv *env = AndroidRuntime::getJNIEnv();
- jclass clazz = env->FindClass("android/media/tv/tuner/filter/Filter");
std::vector<DemuxFilterEvent::Event> events = filterEvent.events;
jclass eventClazz = env->FindClass("android/media/tv/tuner/filter/FilterEvent");
jobjectArray array = env->NewObjectArray(events.size(), eventClazz, NULL);
- for (int i = 0; i < events.size(); i++) {
- auto event = events[i];
- if (event.getDiscriminator() == DemuxFilterEvent::Event::hidl_discriminator::media) {
- env->SetObjectArrayElement(array, i, getMediaEvent(event));
+ if (!events.empty()) {
+ auto event = events[0];
+ switch (event.getDiscriminator()) {
+ case DemuxFilterEvent::Event::hidl_discriminator::media: {
+ array = getMediaEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::section: {
+ array = getSectionEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::pes: {
+ array = getPesEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::tsRecord: {
+ array = getTsRecordEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::mmtpRecord: {
+ array = getMmtpRecordEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::download: {
+ array = getDownloadEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::ipPayload: {
+ array = getIpPayloadEvent(array, events);
+ break;
+ }
+ case DemuxFilterEvent::Event::hidl_discriminator::temi: {
+ array = getTemiEvent(array, events);
+ break;
+ }
+ default: {
+ break;
+ }
}
}
env->CallVoidMethod(
mFilter,
- env->GetMethodID(clazz, "onFilterEvent",
- "([Landroid/media/tv/tuner/filter/FilterEvent;)V"),
+ gFields.onFilterEventID,
array);
return Void();
}
+
Return<void> FilterCallback::onFilterStatus(const DemuxFilterStatus status) {
ALOGD("FilterCallback::onFilterStatus");
JNIEnv *env = AndroidRuntime::getJNIEnv();
@@ -308,9 +559,16 @@
/////////////// Filter ///////////////////////
-Filter::Filter(sp<IFilter> sp, jweak obj) : mFilterSp(sp), mFilterObj(obj) {}
+Filter::Filter(sp<IFilter> sp, jobject obj) : mFilterSp(sp) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ mFilterObj = env->NewWeakGlobalRef(obj);
+}
Filter::~Filter() {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+
+ env->DeleteWeakGlobalRef(mFilterObj);
+ mFilterObj = NULL;
EventFlag::deleteEventFlag(&mFilterMQEventFlag);
}
@@ -816,6 +1074,37 @@
return lnbObj;
}
+jobject JTuner::openLnbByName(jstring name) {
+ JNIEnv *env = AndroidRuntime::getJNIEnv();
+ std::string lnbName(env->GetStringUTFChars(name, nullptr));
+ sp<ILnb> iLnbSp;
+ Result res;
+ LnbId id;
+ mTuner->openLnbByName(lnbName, [&](Result r, LnbId lnbId, const sp<ILnb>& lnb) {
+ res = r;
+ iLnbSp = lnb;
+ id = lnbId;
+ });
+ if (res != Result::SUCCESS || iLnbSp == nullptr) {
+ ALOGE("Failed to open lnb");
+ return NULL;
+ }
+ mLnb = iLnbSp;
+ sp<LnbCallback> lnbCb = new LnbCallback(mObject, id);
+ mLnb->setCallback(lnbCb);
+
+ jobject lnbObj = env->NewObject(
+ env->FindClass("android/media/tv/tuner/Lnb"),
+ gFields.lnbInitID,
+ id);
+
+ sp<Lnb> lnbSp = new Lnb(iLnbSp, lnbObj);
+ lnbSp->incStrong(lnbObj);
+ env->SetLongField(lnbObj, gFields.lnbContext, (jlong) lnbSp.get());
+
+ return lnbObj;
+}
+
int JTuner::tune(const FrontendSettings& settings) {
if (mFe == NULL) {
ALOGE("frontend is not initialized");
@@ -1046,7 +1335,7 @@
return timeFilterObj;
}
-jobject JTuner::openDvr(DvrType type, int bufferSize) {
+jobject JTuner::openDvr(DvrType type, jlong bufferSize) {
ALOGD("JTuner::openDvr");
if (mDemux == NULL) {
if (openDemux() != Result::SUCCESS) {
@@ -1055,24 +1344,38 @@
}
sp<IDvr> iDvrSp;
sp<DvrCallback> callback = new DvrCallback();
- mDemux->openDvr(type, bufferSize, callback,
- [&](Result, const sp<IDvr>& dvr) {
+ Result res;
+ mDemux->openDvr(type, (uint32_t) bufferSize, callback,
+ [&](Result r, const sp<IDvr>& dvr) {
+ res = r;
iDvrSp = dvr;
});
- if (iDvrSp == NULL) {
+ if (res != Result::SUCCESS || iDvrSp == NULL) {
return NULL;
}
JNIEnv *env = AndroidRuntime::getJNIEnv();
- jobject dvrObj =
- env->NewObject(
- env->FindClass("android/media/tv/tuner/dvr/Dvr"),
- gFields.dvrInitID,
- mObject);
- sp<Dvr> dvrSp = new Dvr(iDvrSp, dvrObj);
- dvrSp->incStrong(dvrObj);
- env->SetLongField(dvrObj, gFields.dvrContext, (jlong)dvrSp.get());
+ jobject dvrObj;
+ if (type == DvrType::RECORD) {
+ dvrObj =
+ env->NewObject(
+ env->FindClass("android/media/tv/tuner/dvr/DvrRecorder"),
+ gFields.dvrRecorderInitID,
+ mObject);
+ sp<Dvr> dvrSp = new Dvr(iDvrSp, dvrObj);
+ dvrSp->incStrong(dvrObj);
+ env->SetLongField(dvrObj, gFields.dvrRecorderContext, (jlong)dvrSp.get());
+ } else {
+ dvrObj =
+ env->NewObject(
+ env->FindClass("android/media/tv/tuner/dvr/DvrPlayback"),
+ gFields.dvrPlaybackInitID,
+ mObject);
+ sp<Dvr> dvrSp = new Dvr(iDvrSp, dvrObj);
+ dvrSp->incStrong(dvrObj);
+ env->SetLongField(dvrObj, gFields.dvrPlaybackContext, (jlong)dvrSp.get());
+ }
callback->setDvr(dvrObj);
@@ -1596,7 +1899,11 @@
}
static sp<Dvr> getDvr(JNIEnv *env, jobject dvr) {
- return (Dvr *)env->GetLongField(dvr, gFields.dvrContext);
+ bool isRecorder =
+ env->IsInstanceOf(dvr, env->FindClass("android/media/tv/tuner/dvr/DvrRecorder"));
+ jfieldID fieldId =
+ isRecorder ? gFields.dvrRecorderContext : gFields.dvrPlaybackContext;
+ return (Dvr *)env->GetLongField(dvr, fieldId);
}
static void android_media_tv_Tuner_native_init(JNIEnv *env) {
@@ -1616,8 +1923,7 @@
jclass lnbClazz = env->FindClass("android/media/tv/tuner/Lnb");
gFields.lnbContext = env->GetFieldID(lnbClazz, "mNativeContext", "J");
- gFields.lnbInitID =
- env->GetMethodID(lnbClazz, "<init>", "(I)V");
+ gFields.lnbInitID = env->GetMethodID(lnbClazz, "<init>", "(I)V");
jclass filterClazz = env->FindClass("android/media/tv/tuner/filter/Filter");
gFields.filterContext = env->GetFieldID(filterClazz, "mNativeContext", "J");
@@ -1625,6 +1931,9 @@
env->GetMethodID(filterClazz, "<init>", "(I)V");
gFields.onFilterStatusID =
env->GetMethodID(filterClazz, "onFilterStatus", "(I)V");
+ gFields.onFilterEventID =
+ env->GetMethodID(filterClazz, "onFilterEvent",
+ "([Landroid/media/tv/tuner/filter/FilterEvent;)V");
jclass timeFilterClazz = env->FindClass("android/media/tv/tuner/filter/TimeFilter");
gFields.timeFilterContext = env->GetFieldID(timeFilterClazz, "mNativeContext", "J");
@@ -1635,9 +1944,13 @@
gFields.descramblerInitID =
env->GetMethodID(descramblerClazz, "<init>", "()V");
- jclass dvrClazz = env->FindClass("android/media/tv/tuner/dvr/Dvr");
- gFields.dvrContext = env->GetFieldID(dvrClazz, "mNativeContext", "J");
- gFields.dvrInitID = env->GetMethodID(dvrClazz, "<init>", "()V");
+ jclass dvrRecorderClazz = env->FindClass("android/media/tv/tuner/dvr/DvrRecorder");
+ gFields.dvrRecorderContext = env->GetFieldID(dvrRecorderClazz, "mNativeContext", "J");
+ gFields.dvrRecorderInitID = env->GetMethodID(dvrRecorderClazz, "<init>", "()V");
+
+ jclass dvrPlaybackClazz = env->FindClass("android/media/tv/tuner/dvr/DvrPlayback");
+ gFields.dvrPlaybackContext = env->GetFieldID(dvrPlaybackClazz, "mNativeContext", "J");
+ gFields.dvrPlaybackInitID = env->GetMethodID(dvrPlaybackClazz, "<init>", "()V");
jclass linearBlockClazz = env->FindClass("android/media/MediaCodec$LinearBlock");
gFields.linearBlockInitID = env->GetMethodID(linearBlockClazz, "<init>", "()V");
@@ -1737,6 +2050,12 @@
return tuner->openLnbById(id);
}
+static jobject android_media_tv_Tuner_open_lnb_by_name(JNIEnv *env, jobject thiz, jstring name) {
+ sp<JTuner> tuner = getTuner(env, thiz);
+ return tuner->openLnbByName(name);
+}
+
+
static jobject android_media_tv_Tuner_open_filter(
JNIEnv *env, jobject thiz, jint type, jint subType, jlong bufferSize) {
sp<JTuner> tuner = getTuner(env, thiz);
@@ -2359,13 +2678,15 @@
}
static jobject android_media_tv_Tuner_open_dvr_recorder(
- JNIEnv* /* env */, jobject /* thiz */, jlong /* bufferSize */) {
- return NULL;
+ JNIEnv* env, jobject thiz, jlong bufferSize) {
+ sp<JTuner> tuner = getTuner(env, thiz);
+ return tuner->openDvr(DvrType::RECORD, bufferSize);
}
static jobject android_media_tv_Tuner_open_dvr_playback(
- JNIEnv* /* env */, jobject /* thiz */, jlong /* bufferSize */) {
- return NULL;
+ JNIEnv* env, jobject thiz, jlong bufferSize) {
+ sp<JTuner> tuner = getTuner(env, thiz);
+ return tuner->openDvr(DvrType::PLAYBACK, bufferSize);
}
static jobject android_media_tv_Tuner_get_demux_caps(JNIEnv*, jobject) {
@@ -2419,11 +2740,13 @@
}
static int android_media_tv_Tuner_start_dvr(JNIEnv *env, jobject dvr) {
+
sp<IDvr> dvrSp = getDvr(env, dvr)->getIDvr();
if (dvrSp == NULL) {
ALOGD("Failed to start dvr: dvr not found");
return false;
}
+
Result result = dvrSp->start();
return (int) result;
}
@@ -2629,6 +2952,8 @@
(void *)android_media_tv_Tuner_get_lnb_ids },
{ "nativeOpenLnbById", "(I)Landroid/media/tv/tuner/Lnb;",
(void *)android_media_tv_Tuner_open_lnb_by_id },
+ { "nativeOpenLnbByName", "(Ljava/lang/String;)Landroid/media/tv/tuner/Lnb;",
+ (void *)android_media_tv_Tuner_open_lnb_by_name },
{ "nativeOpenDescrambler", "()Landroid/media/tv/tuner/Descrambler;",
(void *)android_media_tv_Tuner_open_descrambler },
{ "nativeOpenDvrRecorder", "(J)Landroid/media/tv/tuner/dvr/DvrRecorder;",
@@ -2671,7 +2996,7 @@
{ "nativeClose", "()I", (void *)android_media_tv_Tuner_close_descrambler },
};
-static const JNINativeMethod gDvrMethods[] = {
+static const JNINativeMethod gDvrRecorderMethods[] = {
{ "nativeAttachFilter", "(Landroid/media/tv/tuner/filter/Filter;)I",
(void *)android_media_tv_Tuner_attach_filter },
{ "nativeDetachFilter", "(Landroid/media/tv/tuner/filter/Filter;)I",
@@ -2683,14 +3008,22 @@
{ "nativeFlushDvr", "()I", (void *)android_media_tv_Tuner_flush_dvr },
{ "nativeClose", "()I", (void *)android_media_tv_Tuner_close_dvr },
{ "nativeSetFileDescriptor", "(I)V", (void *)android_media_tv_Tuner_dvr_set_fd },
-};
-
-static const JNINativeMethod gDvrRecorderMethods[] = {
{ "nativeWrite", "(J)J", (void *)android_media_tv_Tuner_write_dvr },
{ "nativeWrite", "([BJJ)J", (void *)android_media_tv_Tuner_write_dvr_to_array },
};
static const JNINativeMethod gDvrPlaybackMethods[] = {
+ { "nativeAttachFilter", "(Landroid/media/tv/tuner/filter/Filter;)I",
+ (void *)android_media_tv_Tuner_attach_filter },
+ { "nativeDetachFilter", "(Landroid/media/tv/tuner/filter/Filter;)I",
+ (void *)android_media_tv_Tuner_detach_filter },
+ { "nativeConfigureDvr", "(Landroid/media/tv/tuner/dvr/DvrSettings;)I",
+ (void *)android_media_tv_Tuner_configure_dvr },
+ { "nativeStartDvr", "()I", (void *)android_media_tv_Tuner_start_dvr },
+ { "nativeStopDvr", "()I", (void *)android_media_tv_Tuner_stop_dvr },
+ { "nativeFlushDvr", "()I", (void *)android_media_tv_Tuner_flush_dvr },
+ { "nativeClose", "()I", (void *)android_media_tv_Tuner_close_dvr },
+ { "nativeSetFileDescriptor", "(I)V", (void *)android_media_tv_Tuner_dvr_set_fd },
{ "nativeRead", "(J)J", (void *)android_media_tv_Tuner_read_dvr },
{ "nativeRead", "([BJJ)J", (void *)android_media_tv_Tuner_read_dvr_from_array },
};
@@ -2731,13 +3064,6 @@
return false;
}
if (AndroidRuntime::registerNativeMethods(
- env, "android/media/tv/tuner/dvr/Dvr",
- gDvrMethods,
- NELEM(gDvrMethods)) != JNI_OK) {
- ALOGE("Failed to register dvr native methods");
- return false;
- }
- if (AndroidRuntime::registerNativeMethods(
env, "android/media/tv/tuner/dvr/DvrRecorder",
gDvrRecorderMethods,
NELEM(gDvrRecorderMethods)) != JNI_OK) {
diff --git a/media/jni/android_media_tv_Tuner.h b/media/jni/android_media_tv_Tuner.h
index fec4cd8..5d2bba6 100644
--- a/media/jni/android_media_tv_Tuner.h
+++ b/media/jni/android_media_tv_Tuner.h
@@ -114,7 +114,22 @@
jobject handleToLinearBlock(const native_handle_t* handle, uint32_t size);
private:
jweak mFilter;
- jobject getMediaEvent(const DemuxFilterEvent::Event& event);
+ jobjectArray getSectionEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getMediaEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getPesEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getTsRecordEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getMmtpRecordEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getDownloadEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getIpPayloadEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
+ jobjectArray getTemiEvent(
+ jobjectArray& arr, const std::vector<DemuxFilterEvent::Event>& events);
};
struct FrontendCallback : public IFrontendCallback {
@@ -129,7 +144,7 @@
};
struct Filter : public RefBase {
- Filter(sp<IFilter> sp, jweak obj);
+ Filter(sp<IFilter> sp, jobject obj);
~Filter();
int close();
sp<IFilter> getIFilter();
@@ -165,10 +180,11 @@
int setLna(bool enable);
jobject getLnbIds();
jobject openLnbById(int id);
+ jobject openLnbByName(jstring name);
jobject openFilter(DemuxFilterType type, int bufferSize);
jobject openTimeFilter();
jobject openDescrambler();
- jobject openDvr(DvrType type, int bufferSize);
+ jobject openDvr(DvrType type, jlong bufferSize);
protected:
Result openDemux();
diff --git a/media/jni/audioeffect/Visualizer.cpp b/media/jni/audioeffect/Visualizer.cpp
index 83f3b6e..efeb335 100644
--- a/media/jni/audioeffect/Visualizer.cpp
+++ b/media/jni/audioeffect/Visualizer.cpp
@@ -120,8 +120,9 @@
}
if (mCaptureThread != 0) {
+ sp<CaptureThread> t = mCaptureThread;
mCaptureLock.unlock();
- mCaptureThread->requestExitAndWait();
+ t->requestExitAndWait();
mCaptureLock.lock();
}
diff --git a/media/jni/soundpool/StreamManager.h b/media/jni/soundpool/StreamManager.h
index 15b39f2..30ad220 100644
--- a/media/jni/soundpool/StreamManager.h
+++ b/media/jni/soundpool/StreamManager.h
@@ -70,9 +70,10 @@
static int staticFunction(void *data) {
JavaThread *jt = static_cast<JavaThread *>(data);
jt->mF();
+ jt->mIsClosed = true; // set the flag that we are closed
+ // now before we allow the destructor to execute;
+ // otherwise there may be a use after free.
jt->mPromise.set_value();
- jt->mIsClosed = true; // publicly inform that we are closed
- // after we have accessed all variables.
return 0;
}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java
index c529952..ebd7658 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraBinderTest.java
@@ -284,12 +284,12 @@
ICameraDeviceCallbacks dummyCallbacks = new DummyCameraDeviceCallbacks();
String clientPackageName = getContext().getPackageName();
- String clientFeatureId = getContext().getFeatureId();
+ String clientAttributionTag = getContext().getAttributionTag();
ICameraDeviceUser cameraUser =
mUtils.getCameraService().connectDevice(
dummyCallbacks, String.valueOf(cameraId),
- clientPackageName, clientFeatureId,
+ clientPackageName, clientAttributionTag,
ICameraService.USE_CALLING_UID);
assertNotNull(String.format("Camera %s was null", cameraId), cameraUser);
@@ -320,6 +320,15 @@
public void onCameraAccessPrioritiesChanged() {
Log.v(TAG, "Camera access permission change");
}
+ @Override
+ public void onCameraOpened(String cameraId, String clientPackageName) {
+ Log.v(TAG, String.format("Camera %s is opened by client package %s",
+ cameraId, clientPackageName));
+ }
+ @Override
+ public void onCameraClosed(String cameraId) {
+ Log.v(TAG, String.format("Camera %s is closed", cameraId));
+ }
}
/**
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java
index 466c5f4..bf3e746 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/integration/CameraDeviceBinderTest.java
@@ -238,12 +238,12 @@
ICameraDeviceCallbacks.Stub dummyCallbacks = new DummyCameraDeviceCallbacks();
String clientPackageName = getContext().getPackageName();
- String clientFeatureId = getContext().getFeatureId();
+ String clientAttributionTag = getContext().getAttributionTag();
mMockCb = spy(dummyCallbacks);
mCameraUser = mUtils.getCameraService().connectDevice(mMockCb, mCameraId,
- clientPackageName, clientFeatureId, ICameraService.USE_CALLING_UID);
+ clientPackageName, clientAttributionTag, ICameraService.USE_CALLING_UID);
assertNotNull(String.format("Camera %s was null", mCameraId), mCameraUser);
mHandlerThread = new HandlerThread(TAG);
mHandlerThread.start();
diff --git a/media/tests/MediaRouter/AndroidManifest.xml b/media/tests/MediaRouter/AndroidManifest.xml
index 9546500..d9806f3 100644
--- a/media/tests/MediaRouter/AndroidManifest.xml
+++ b/media/tests/MediaRouter/AndroidManifest.xml
@@ -19,7 +19,7 @@
<application android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
- <service android:name=".SampleMediaRoute2ProviderService"
+ <service android:name=".StubMediaRoute2ProviderService"
android:exported="true">
<intent-filter>
<action android:name="android.media.MediaRoute2ProviderService" />
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java
index 230b9e4..a97baaf 100644
--- a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java
@@ -22,16 +22,16 @@
import static android.media.MediaRoute2ProviderService.REASON_REJECTED;
import static android.media.MediaRoute2ProviderService.REQUEST_ID_NONE;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.FEATURE_SAMPLE;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.FEATURE_SPECIAL;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_ID1;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_ID2;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_ID5_TO_TRANSFER_TO;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_ID_FIXED_VOLUME;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_ID_SPECIAL_FEATURE;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_ID_VARIABLE_VOLUME;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.ROUTE_NAME2;
-import static com.android.mediaroutertest.SampleMediaRoute2ProviderService.VOLUME_MAX;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.FEATURE_SAMPLE;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.FEATURE_SPECIAL;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_ID1;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_ID2;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_ID5_TO_TRANSFER_TO;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_ID_FIXED_VOLUME;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_ID_SPECIAL_FEATURE;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_ID_VARIABLE_VOLUME;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.ROUTE_NAME2;
+import static com.android.mediaroutertest.StubMediaRoute2ProviderService.VOLUME_MAX;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -115,7 +115,7 @@
// unregister callbacks
clearCallbacks();
- SampleMediaRoute2ProviderService instance = SampleMediaRoute2ProviderService.getInstance();
+ StubMediaRoute2ProviderService instance = StubMediaRoute2ProviderService.getInstance();
if (instance != null) {
instance.setProxy(null);
}
@@ -161,8 +161,8 @@
MediaRoute2Info routeToRemove = routes.get(ROUTE_ID2);
- SampleMediaRoute2ProviderService sInstance =
- SampleMediaRoute2ProviderService.getInstance();
+ StubMediaRoute2ProviderService sInstance =
+ StubMediaRoute2ProviderService.getInstance();
assertNotNull(sInstance);
sInstance.removeRoute(ROUTE_ID2);
assertTrue(removedLatch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
@@ -413,12 +413,12 @@
Map<String, MediaRoute2Info> routes = waitAndGetRoutesWithManager(FEATURES_ALL);
MediaRoute2Info volRoute = routes.get(ROUTE_ID_VARIABLE_VOLUME);
- SampleMediaRoute2ProviderService instance = SampleMediaRoute2ProviderService.getInstance();
+ StubMediaRoute2ProviderService instance = StubMediaRoute2ProviderService.getInstance();
assertNotNull(instance);
final List<Long> requestIds = new ArrayList<>();
final CountDownLatch onSetRouteVolumeLatch = new CountDownLatch(1);
- instance.setProxy(new SampleMediaRoute2ProviderService.Proxy() {
+ instance.setProxy(new StubMediaRoute2ProviderService.Proxy() {
@Override
public void onSetRouteVolume(String routeId, int volume, long requestId) {
requestIds.add(requestId);
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/SampleMediaRoute2ProviderService.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/StubMediaRoute2ProviderService.java
similarity index 98%
rename from media/tests/MediaRouter/src/com/android/mediaroutertest/SampleMediaRoute2ProviderService.java
rename to media/tests/MediaRouter/src/com/android/mediaroutertest/StubMediaRoute2ProviderService.java
index 22c5bce..6d46ba5 100644
--- a/media/tests/MediaRouter/src/com/android/mediaroutertest/SampleMediaRoute2ProviderService.java
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/StubMediaRoute2ProviderService.java
@@ -36,7 +36,7 @@
import javax.annotation.concurrent.GuardedBy;
-public class SampleMediaRoute2ProviderService extends MediaRoute2ProviderService {
+public class StubMediaRoute2ProviderService extends MediaRoute2ProviderService {
private static final String TAG = "SampleMR2ProviderSvc";
private static final Object sLock = new Object();
@@ -74,7 +74,7 @@
private int mNextSessionId = 1000;
@GuardedBy("sLock")
- private static SampleMediaRoute2ProviderService sInstance;
+ private static StubMediaRoute2ProviderService sInstance;
private Proxy mProxy;
private void initializeRoutes() {
@@ -127,7 +127,7 @@
mRoutes.put(variableVolumeRoute.getId(), variableVolumeRoute);
}
- public static SampleMediaRoute2ProviderService getInstance() {
+ public static StubMediaRoute2ProviderService getInstance() {
synchronized (sLock) {
return sInstance;
}
@@ -239,7 +239,7 @@
// Set control hints with given sessionHints
.setControlHints(sessionHints)
.build();
- notifySessionCreated(sessionInfo, requestId);
+ notifySessionCreated(requestId, sessionInfo);
publishRoutes();
}
diff --git a/packages/CarSystemUI/res/layout/car_fullscreen_user_switcher.xml b/packages/CarSystemUI/res/layout/car_fullscreen_user_switcher.xml
index 55207b3..6ecab51 100644
--- a/packages/CarSystemUI/res/layout/car_fullscreen_user_switcher.xml
+++ b/packages/CarSystemUI/res/layout/car_fullscreen_user_switcher.xml
@@ -18,8 +18,7 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fullscreen_user_switcher"
android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fitsSystemWindows="true">
+ android:layout_height="match_parent">
<LinearLayout
android:id="@+id/container"
@@ -28,11 +27,10 @@
android:layout_alignParentTop="true"
android:orientation="vertical">
- <!-- TODO(b/150302361): Status bar is commented out since a top inset is being added which causes it to be displayed below the top of the screen. -->
- <!-- <include
- layout="@layout/car_status_bar_header"
- android:layout_alignParentTop="true"
- android:theme="@android:style/Theme"/>-->
+ <include
+ layout="@layout/car_status_bar_header"
+ android:layout_alignParentTop="true"
+ android:theme="@android:style/Theme"/>
<FrameLayout
@@ -42,9 +40,8 @@
android:id="@+id/user_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"/>
- <!-- TODO(b/150302361): Re-add marginTop once status bar has been added back. -->
- <!-- android:layout_marginTop="@dimen/car_user_switcher_margin_top"/>-->
+ android:layout_gravity="center_vertical"
+ android:layout_marginTop="@dimen/car_user_switcher_margin_top"/>
</FrameLayout>
</LinearLayout>
diff --git a/packages/CarSystemUI/res/layout/super_notification_shade.xml b/packages/CarSystemUI/res/layout/super_notification_shade.xml
index cb65045..e36d8ca 100644
--- a/packages/CarSystemUI/res/layout/super_notification_shade.xml
+++ b/packages/CarSystemUI/res/layout/super_notification_shade.xml
@@ -72,11 +72,6 @@
android:layout_marginBottom="@dimen/navigation_bar_height"
android:visibility="invisible"/>
- <include layout="@layout/headsup_container"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:visibility="invisible"/>
-
<include layout="@layout/status_bar_expanded"
android:layout_width="match_parent"
android:layout_height="match_parent"
diff --git a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java
index c010881..59fa9d0 100644
--- a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java
+++ b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java
@@ -18,6 +18,7 @@
import com.android.systemui.biometrics.AuthController;
import com.android.systemui.bubbles.dagger.BubbleModule;
+import com.android.systemui.car.notification.CarNotificationModule;
import com.android.systemui.globalactions.GlobalActionsComponent;
import com.android.systemui.keyguard.KeyguardViewMediator;
import com.android.systemui.keyguard.dagger.KeyguardModule;
@@ -49,7 +50,8 @@
/** Binder for car specific {@link SystemUI} modules. */
@Module(includes = {RecentsModule.class, CarStatusBarModule.class, NotificationsModule.class,
- BubbleModule.class, KeyguardModule.class, OverlayWindowModule.class})
+ BubbleModule.class, KeyguardModule.class, OverlayWindowModule.class,
+ CarNotificationModule.class})
public abstract class CarSystemUIBinder {
/** Inject into AuthController. */
@Binds
diff --git a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
index a0d5a1b..8292d30 100644
--- a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
+++ b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIModule.java
@@ -21,8 +21,9 @@
import android.content.Context;
+import com.android.keyguard.KeyguardViewController;
+import com.android.systemui.car.CarDeviceProvisionedController;
import com.android.systemui.car.CarDeviceProvisionedControllerImpl;
-import com.android.systemui.car.CarNotificationInterruptionStateProvider;
import com.android.systemui.dagger.SystemUIRootComponent;
import com.android.systemui.dock.DockManager;
import com.android.systemui.dock.DockManagerImpl;
@@ -39,7 +40,6 @@
import com.android.systemui.statusbar.car.CarStatusBar;
import com.android.systemui.statusbar.car.CarStatusBarKeyguardViewManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
import com.android.systemui.statusbar.phone.KeyguardEnvironmentImpl;
@@ -47,6 +47,8 @@
import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
+import com.android.systemui.statusbar.policy.BatteryController;
+import com.android.systemui.statusbar.policy.BatteryControllerImpl;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -63,10 +65,6 @@
@Module(includes = {DividerModule.class})
abstract class CarSystemUIModule {
- @Binds
- abstract NotificationInterruptionStateProvider bindNotificationInterruptionStateProvider(
- CarNotificationInterruptionStateProvider notificationInterruptionStateProvider);
-
@Singleton
@Provides
@Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME)
@@ -104,6 +102,11 @@
NotificationLockscreenUserManagerImpl notificationLockscreenUserManager);
@Binds
+ @Singleton
+ public abstract BatteryController provideBatteryController(
+ BatteryControllerImpl controllerImpl);
+
+ @Binds
abstract DockManager bindDockManager(DockManagerImpl dockManager);
@Binds
@@ -136,6 +139,14 @@
CarStatusBarKeyguardViewManager keyguardViewManager);
@Binds
+ abstract KeyguardViewController bindKeyguardViewController(
+ CarStatusBarKeyguardViewManager keyguardViewManager);
+
+ @Binds
abstract DeviceProvisionedController bindDeviceProvisionedController(
CarDeviceProvisionedControllerImpl deviceProvisionedController);
+
+ @Binds
+ abstract CarDeviceProvisionedController bindCarDeviceProvisionedController(
+ CarDeviceProvisionedControllerImpl deviceProvisionedController);
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java
index 38d5211b..09e62d2 100644
--- a/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java
+++ b/packages/CarSystemUI/src/com/android/systemui/car/CarDeviceProvisionedControllerImpl.java
@@ -44,8 +44,9 @@
CarSettings.Secure.KEY_SETUP_WIZARD_IN_PROGRESS);
private final ContentObserver mCarSettingsObserver = new ContentObserver(
Dependency.get(Dependency.MAIN_HANDLER)) {
+
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, Uri uri, int flags) {
if (USER_SETUP_IN_PROGRESS_URI.equals(uri)) {
notifyUserSetupInProgressChanged();
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java b/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java
deleted file mode 100644
index 447e579..0000000
--- a/packages/CarSystemUI/src/com/android/systemui/car/CarNotificationInterruptionStateProvider.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2018 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.car;
-
-import android.content.Context;
-
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
-import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.policy.BatteryController;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-/** Auto-specific implementation of {@link NotificationInterruptionStateProvider}. */
-@Singleton
-public class CarNotificationInterruptionStateProvider extends
- NotificationInterruptionStateProvider {
-
- @Inject
- public CarNotificationInterruptionStateProvider(Context context,
- NotificationFilter filter,
- StatusBarStateController stateController,
- BatteryController batteryController) {
- super(context, filter, stateController, batteryController);
- }
-
- @Override
- public boolean shouldHeadsUp(NotificationEntry entry) {
- // Because space is usually constrained in the auto use-case, there should not be a
- // pinned notification when the shade has been expanded. Ensure this by not pinning any
- // notification if the shade is already opened.
- if (!getPresenter().isPresenterFullyCollapsed()) {
- return false;
- }
-
- return super.shouldHeadsUp(entry);
- }
-}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/notification/CarHeadsUpNotificationSystemContainer.java b/packages/CarSystemUI/src/com/android/systemui/car/notification/CarHeadsUpNotificationSystemContainer.java
new file mode 100644
index 0000000..689d2d5
--- /dev/null
+++ b/packages/CarSystemUI/src/com/android/systemui/car/notification/CarHeadsUpNotificationSystemContainer.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2020 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.car.notification;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.PixelFormat;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.widget.FrameLayout;
+
+import com.android.car.notification.R;
+import com.android.car.notification.headsup.CarHeadsUpNotificationContainer;
+import com.android.systemui.car.CarDeviceProvisionedController;
+import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.statusbar.car.CarStatusBar;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import dagger.Lazy;
+
+/**
+ * A controller for SysUI's HUN display.
+ */
+@Singleton
+public class CarHeadsUpNotificationSystemContainer implements CarHeadsUpNotificationContainer {
+ private final CarDeviceProvisionedController mCarDeviceProvisionedController;
+ private final Lazy<CarStatusBar> mCarStatusBarLazy;
+
+ private final ViewGroup mWindow;
+ private final FrameLayout mHeadsUpContentFrame;
+
+ private final boolean mEnableHeadsUpNotificationWhenNotificationShadeOpen;
+
+ @Inject
+ CarHeadsUpNotificationSystemContainer(Context context,
+ @Main Resources resources,
+ CarDeviceProvisionedController deviceProvisionedController,
+ WindowManager windowManager,
+ // TODO: Remove dependency on CarStatusBar
+ Lazy<CarStatusBar> carStatusBarLazy) {
+ mCarDeviceProvisionedController = deviceProvisionedController;
+ mCarStatusBarLazy = carStatusBarLazy;
+
+ WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG,
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+ | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
+ PixelFormat.TRANSLUCENT);
+
+ lp.gravity = Gravity.TOP;
+ lp.setTitle("HeadsUpNotification");
+
+ mWindow = (ViewGroup) LayoutInflater.from(context)
+ .inflate(R.layout.headsup_container, null, false);
+ windowManager.addView(mWindow, lp);
+ mWindow.setVisibility(View.INVISIBLE);
+ mHeadsUpContentFrame = mWindow.findViewById(R.id.headsup_content);
+
+ mEnableHeadsUpNotificationWhenNotificationShadeOpen = resources.getBoolean(
+ R.bool.config_enableHeadsUpNotificationWhenNotificationShadeOpen);
+ }
+
+ private void animateShow() {
+ if ((mEnableHeadsUpNotificationWhenNotificationShadeOpen
+ || !mCarStatusBarLazy.get().isPanelExpanded()) && isCurrentUserSetup()) {
+ mWindow.setVisibility(View.VISIBLE);
+ }
+ }
+
+ private void animateHide() {
+ mWindow.setVisibility(View.INVISIBLE);
+ }
+
+ @Override
+ public void displayNotification(View notificationView) {
+ mHeadsUpContentFrame.addView(notificationView);
+ animateShow();
+ }
+
+ @Override
+ public void removeNotification(View notificationView) {
+ mHeadsUpContentFrame.removeView(notificationView);
+ if (mHeadsUpContentFrame.getChildCount() == 0) {
+ animateHide();
+ }
+ }
+
+ @Override
+ public boolean isVisible() {
+ return mWindow.getVisibility() == View.VISIBLE;
+ }
+
+ private boolean isCurrentUserSetup() {
+ return mCarDeviceProvisionedController.isCurrentUserSetup()
+ && !mCarDeviceProvisionedController.isCurrentUserSetupInProgress();
+ }
+}
diff --git a/packages/CarSystemUI/src/com/android/systemui/car/notification/CarNotificationModule.java b/packages/CarSystemUI/src/com/android/systemui/car/notification/CarNotificationModule.java
new file mode 100644
index 0000000..b7bc631
--- /dev/null
+++ b/packages/CarSystemUI/src/com/android/systemui/car/notification/CarNotificationModule.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2020 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.car.notification;
+
+import android.content.Context;
+
+import com.android.car.notification.CarHeadsUpNotificationManager;
+import com.android.car.notification.CarNotificationListener;
+import com.android.car.notification.CarUxRestrictionManagerWrapper;
+import com.android.car.notification.NotificationClickHandlerFactory;
+import com.android.car.notification.NotificationDataManager;
+import com.android.car.notification.headsup.CarHeadsUpNotificationContainer;
+import com.android.internal.statusbar.IStatusBarService;
+
+import javax.inject.Singleton;
+
+import dagger.Binds;
+import dagger.Module;
+import dagger.Provides;
+
+/**
+ * Module for Car SysUI Notifications
+ */
+@Module
+public abstract class CarNotificationModule {
+ @Provides
+ @Singleton
+ static NotificationClickHandlerFactory provideNotificationClickHandlerFactory(
+ IStatusBarService barService) {
+ return new NotificationClickHandlerFactory(barService);
+ }
+
+ @Provides
+ @Singleton
+ static NotificationDataManager provideNotificationDataManager() {
+ return new NotificationDataManager();
+ }
+
+ @Provides
+ @Singleton
+ static CarUxRestrictionManagerWrapper provideCarUxRestrictionManagerWrapper() {
+ return new CarUxRestrictionManagerWrapper();
+ }
+
+ @Provides
+ @Singleton
+ static CarNotificationListener provideCarNotificationListener(Context context,
+ CarUxRestrictionManagerWrapper carUxRestrictionManagerWrapper,
+ CarHeadsUpNotificationManager carHeadsUpNotificationManager,
+ NotificationDataManager notificationDataManager) {
+ CarNotificationListener listener = new CarNotificationListener();
+ listener.registerAsSystemService(context, carUxRestrictionManagerWrapper,
+ carHeadsUpNotificationManager, notificationDataManager);
+ return listener;
+ }
+
+ @Provides
+ @Singleton
+ static CarHeadsUpNotificationManager provideCarHeadsUpNotificationManager(Context context,
+ NotificationClickHandlerFactory notificationClickHandlerFactory,
+ NotificationDataManager notificationDataManager,
+ CarHeadsUpNotificationContainer headsUpNotificationDisplay) {
+ return new CarHeadsUpNotificationManager(context, notificationClickHandlerFactory,
+ notificationDataManager, headsUpNotificationDisplay);
+ }
+
+ @Binds
+ abstract CarHeadsUpNotificationContainer bindsCarHeadsUpNotificationContainer(
+ CarHeadsUpNotificationSystemContainer carHeadsUpNotificationSystemContainer);
+}
diff --git a/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java b/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java
index 2045527..3ee92bd7 100644
--- a/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java
@@ -49,7 +49,6 @@
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.phone.AutoHideController;
import com.android.systemui.statusbar.phone.BarTransitions;
-import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import java.io.FileDescriptor;
@@ -105,7 +104,7 @@
public CarNavigationBar(Context context,
CarNavigationBarController carNavigationBarController,
WindowManager windowManager,
- DeviceProvisionedController deviceProvisionedController,
+ CarDeviceProvisionedController deviceProvisionedController,
CommandQueue commandQueue,
AutoHideController autoHideController,
ButtonSelectionStateListener buttonSelectionStateListener,
@@ -117,8 +116,7 @@
super(context);
mCarNavigationBarController = carNavigationBarController;
mWindowManager = windowManager;
- mCarDeviceProvisionedController = (CarDeviceProvisionedController)
- deviceProvisionedController;
+ mCarDeviceProvisionedController = deviceProvisionedController;
mCommandQueue = commandQueue;
mAutoHideController = autoHideController;
mButtonSelectionStateListener = buttonSelectionStateListener;
@@ -240,10 +238,12 @@
}
buildNavBarContent();
- // If the UI was rebuilt (day/night change) while the keyguard was up we need to
- // correctly respect that state.
+ // If the UI was rebuilt (day/night change or user change) while the keyguard was up we need
+ // to correctly respect that state.
if (mKeyguardStateControllerLazy.get().isShowing()) {
mCarNavigationBarController.showAllKeyguardButtons(isDeviceSetupForUser());
+ } else {
+ mCarNavigationBarController.hideAllKeyguardButtons(isDeviceSetupForUser());
}
// Upon restarting the Navigation Bar, CarFacetButtonController should immediately apply the
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index 83248f4..411f14d 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -43,11 +43,9 @@
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
-import com.android.car.notification.CarHeadsUpNotificationManager;
import com.android.car.notification.CarNotificationListener;
import com.android.car.notification.CarNotificationView;
import com.android.car.notification.CarUxRestrictionManagerWrapper;
-import com.android.car.notification.HeadsUpEntry;
import com.android.car.notification.NotificationClickHandlerFactory;
import com.android.car.notification.NotificationDataManager;
import com.android.car.notification.NotificationViewController;
@@ -97,13 +95,15 @@
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.VibratorHelper;
-import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.init.NotificationsController;
+import com.android.systemui.statusbar.notification.interruption.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptSuppressor;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.phone.AutoHideController;
@@ -132,7 +132,6 @@
import com.android.systemui.statusbar.phone.dagger.StatusBarComponent;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.ExtensionController;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.statusbar.policy.NetworkController;
@@ -184,14 +183,15 @@
private final Lazy<PowerManagerHelper> mPowerManagerHelperLazy;
private final ShadeController mShadeController;
private final CarServiceProvider mCarServiceProvider;
+ private final NotificationDataManager mNotificationDataManager;
private final CarDeviceProvisionedController mCarDeviceProvisionedController;
private final ScreenLifecycle mScreenLifecycle;
+ private final CarNotificationListener mCarNotificationListener;
private boolean mDeviceIsSetUpForUser = true;
private boolean mIsUserSetupInProgress = false;
private PowerManagerHelper mPowerManagerHelper;
private FlingAnimationUtils mFlingAnimationUtils;
- private NotificationDataManager mNotificationDataManager;
private NotificationClickHandlerFactory mNotificationClickHandlerFactory;
// The container for the notifications.
@@ -229,24 +229,8 @@
private boolean mIsNotificationCardSwiping;
// If notification shade is being swiped vertically to close.
private boolean mIsSwipingVerticallyToClose;
- // Whether heads-up notifications should be shown when shade is open.
- private boolean mEnableHeadsUpNotificationWhenNotificationShadeOpen;
- private CarUxRestrictionManagerWrapper mCarUxRestrictionManagerWrapper;
-
- private final CarPowerStateListener mCarPowerStateListener =
- (int state) -> {
- // When the car powers on, clear all notifications and mute/unread states.
- Log.d(TAG, "New car power state: " + state);
- if (state == CarPowerStateListener.ON) {
- if (mNotificationClickHandlerFactory != null) {
- mNotificationClickHandlerFactory.clearAllNotifications();
- }
- if (mNotificationDataManager != null) {
- mNotificationDataManager.clearAll();
- }
- }
- };
+ private final CarUxRestrictionManagerWrapper mCarUxRestrictionManagerWrapper;
public CarStatusBar(
Context context,
@@ -267,7 +251,7 @@
RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler,
NotificationGutsManager notificationGutsManager,
NotificationLogger notificationLogger,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptStateProvider,
NotificationViewHierarchyManager notificationViewHierarchyManager,
KeyguardViewMediator keyguardViewMediator,
NotificationAlertingManager notificationAlertingManager,
@@ -288,7 +272,7 @@
BubbleController bubbleController,
NotificationGroupManager groupManager,
VisualStabilityManager visualStabilityManager,
- DeviceProvisionedController deviceProvisionedController,
+ CarDeviceProvisionedController carDeviceProvisionedController,
NavigationBarController navigationBarController,
Lazy<AssistManager> assistManagerLazy,
ConfigurationController configurationController,
@@ -330,7 +314,10 @@
CarServiceProvider carServiceProvider,
Lazy<PowerManagerHelper> powerManagerHelperLazy,
CarNavigationBarController carNavigationBarController,
- FlingAnimationUtils.Builder flingAnimationUtilsBuilder) {
+ FlingAnimationUtils.Builder flingAnimationUtilsBuilder,
+ NotificationDataManager notificationDataManager,
+ CarUxRestrictionManagerWrapper carUxRestrictionManagerWrapper,
+ CarNotificationListener carNotificationListener) {
super(
context,
notificationsController,
@@ -350,7 +337,7 @@
remoteInputQuickSettingsDisabler,
notificationGutsManager,
notificationLogger,
- notificationInterruptionStateProvider,
+ notificationInterruptStateProvider,
notificationViewHierarchyManager,
keyguardViewMediator,
notificationAlertingManager,
@@ -371,7 +358,7 @@
bubbleController,
groupManager,
visualStabilityManager,
- deviceProvisionedController,
+ carDeviceProvisionedController,
navigationBarController,
assistManagerLazy,
configurationController,
@@ -412,14 +399,16 @@
mUserSwitcherController = userSwitcherController;
mScrimController = scrimController;
mLockscreenLockIconController = lockscreenLockIconController;
- mCarDeviceProvisionedController =
- (CarDeviceProvisionedController) deviceProvisionedController;
+ mCarDeviceProvisionedController = carDeviceProvisionedController;
mShadeController = shadeController;
mCarServiceProvider = carServiceProvider;
mPowerManagerHelperLazy = powerManagerHelperLazy;
mCarNavigationBarController = carNavigationBarController;
mFlingAnimationUtilsBuilder = flingAnimationUtilsBuilder;
mScreenLifecycle = screenLifecycle;
+ mNotificationDataManager = notificationDataManager;
+ mCarUxRestrictionManagerWrapper = carUxRestrictionManagerWrapper;
+ mCarNotificationListener = carNotificationListener;
}
@Override
@@ -462,7 +451,17 @@
mCarBatteryController.startListening();
mPowerManagerHelper = mPowerManagerHelperLazy.get();
- mPowerManagerHelper.setCarPowerStateListener(mCarPowerStateListener);
+ mPowerManagerHelper.setCarPowerStateListener(
+ state -> {
+ // When the car powers on, clear all notifications and mute/unread states.
+ Log.d(TAG, "New car power state: " + state);
+ if (state == CarPowerStateListener.ON) {
+ if (mNotificationClickHandlerFactory != null) {
+ mNotificationClickHandlerFactory.clearAllNotifications();
+ }
+ mNotificationDataManager.clearAll();
+ }
+ });
mPowerManagerHelper.connectToCarService();
mCarDeviceProvisionedController.addCallback(
@@ -491,6 +490,22 @@
.isCurrentUserSetupInProgress();
}
});
+
+ mNotificationInterruptStateProvider.addSuppressor(new NotificationInterruptSuppressor() {
+ @Override
+ public String getName() {
+ return TAG;
+ }
+
+ @Override
+ public boolean suppressInterruptions(NotificationEntry entry) {
+ // Because space is usually constrained in the auto use-case, there should not be a
+ // pinned notification when the shade has been expanded.
+ // Ensure this by not allowing any interruptions (ie: pinning any notifications) if
+ // the shade is already opened.
+ return !getPresenter().isPresenterFullyCollapsed();
+ }
+ });
}
@Override
@@ -597,27 +612,13 @@
mShadeController.animateCollapsePanels();
}
});
- CarNotificationListener carNotificationListener = new CarNotificationListener();
- mCarUxRestrictionManagerWrapper = new CarUxRestrictionManagerWrapper();
-
- mNotificationDataManager = new NotificationDataManager();
mNotificationDataManager.setOnUnseenCountUpdateListener(() -> {
- if (mNotificationDataManager != null) {
- onUseenCountUpdate(mNotificationDataManager.getUnseenNotificationCount());
- }
+ onUseenCountUpdate(mNotificationDataManager.getUnseenNotificationCount());
});
- mEnableHeadsUpNotificationWhenNotificationShadeOpen = mContext.getResources().getBoolean(
- R.bool.config_enableHeadsUpNotificationWhenNotificationShadeOpen);
- CarHeadsUpNotificationManager carHeadsUpNotificationManager =
- new CarSystemUIHeadsUpNotificationManager(mContext,
- mNotificationClickHandlerFactory, mNotificationDataManager);
mNotificationClickHandlerFactory.setNotificationDataManager(mNotificationDataManager);
- carNotificationListener.registerAsSystemService(mContext, mCarUxRestrictionManagerWrapper,
- carHeadsUpNotificationManager, mNotificationDataManager);
-
final View glassPane = mNotificationShadeWindowView.findViewById(R.id.glass_pane);
mNotificationView = mNotificationShadeWindowView.findViewById(R.id.notification_view);
mHandleBar = mNotificationShadeWindowView.findViewById(R.id.handle_bar);
@@ -720,7 +721,7 @@
mNotificationViewController = new NotificationViewController(
mNotificationView,
PreprocessingManager.getInstance(mContext),
- carNotificationListener,
+ mCarNotificationListener,
mCarUxRestrictionManagerWrapper,
mNotificationDataManager);
mNotificationViewController.enable();
@@ -1206,61 +1207,4 @@
return true;
}
}
-
- /**
- * SystemUi version of the notification manager that overrides methods such that the
- * notifications end up in the status bar layouts instead of a standalone window.
- */
- private class CarSystemUIHeadsUpNotificationManager extends CarHeadsUpNotificationManager {
-
- CarSystemUIHeadsUpNotificationManager(Context context,
- NotificationClickHandlerFactory clickHandlerFactory,
- NotificationDataManager notificationDataManager) {
- super(context, clickHandlerFactory, notificationDataManager);
- }
-
- @Override
- protected View createHeadsUpPanel() {
- // In SystemUi the view is already in the window so just return a reference.
- return mNotificationShadeWindowView.findViewById(R.id.notification_headsup);
- }
-
- @Override
- protected void addHeadsUpPanelToDisplay() {
- // Set the panel initial state to invisible
- mHeadsUpPanel.setVisibility(View.INVISIBLE);
- }
-
- @Override
- protected void setInternalInsetsInfo(ViewTreeObserver.InternalInsetsInfo info,
- HeadsUpEntry currentNotification, boolean panelExpanded) {
- super.setInternalInsetsInfo(info, currentNotification, mPanelExpanded);
- }
-
- @Override
- protected void setHeadsUpVisible() {
- // if the Notifications panel is showing or SUW for user is in progress then don't show
- // heads up notifications
- if ((!mEnableHeadsUpNotificationWhenNotificationShadeOpen && mPanelExpanded)
- || !isDeviceSetupForUser()) {
- return;
- }
-
- super.setHeadsUpVisible();
- if (mHeadsUpPanel.getVisibility() == View.VISIBLE) {
- mNotificationShadeWindowController.setHeadsUpShowing(true);
- mStatusBarWindowController.setForceStatusBarVisible(true);
- }
- }
-
- @Override
- protected void removeNotificationFromPanel(HeadsUpEntry currentHeadsUpNotification) {
- super.removeNotificationFromPanel(currentHeadsUpNotification);
- // If the panel ended up empty and hidden we can remove it from SystemUi
- if (mHeadsUpPanel.getVisibility() != View.VISIBLE) {
- mNotificationShadeWindowController.setHeadsUpShowing(false);
- mStatusBarWindowController.setForceStatusBarVisible(false);
- }
- }
- }
}
diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java
index aea4bd4..160268b 100644
--- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java
+++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java
@@ -23,6 +23,9 @@
import android.os.PowerManager;
import android.util.DisplayMetrics;
+import com.android.car.notification.CarNotificationListener;
+import com.android.car.notification.CarUxRestrictionManagerWrapper;
+import com.android.car.notification.NotificationDataManager;
import com.android.internal.logging.MetricsLogger;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.keyguard.ViewMediatorCallback;
@@ -30,6 +33,7 @@
import com.android.systemui.assist.AssistManager;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.bubbles.BubbleController;
+import com.android.systemui.car.CarDeviceProvisionedController;
import com.android.systemui.car.CarServiceProvider;
import com.android.systemui.colorextraction.SysuiColorExtractor;
import com.android.systemui.dagger.qualifiers.UiBackground;
@@ -58,13 +62,13 @@
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.VibratorHelper;
import com.android.systemui.statusbar.dagger.StatusBarDependenciesModule;
-import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.init.NotificationsController;
+import com.android.systemui.statusbar.notification.interruption.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.notification.row.NotificationRowModule;
@@ -93,7 +97,6 @@
import com.android.systemui.statusbar.phone.dagger.StatusBarPhoneDependenciesModule;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.ConfigurationController;
-import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.ExtensionController;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.statusbar.policy.NetworkController;
@@ -143,7 +146,7 @@
RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler,
NotificationGutsManager notificationGutsManager,
NotificationLogger notificationLogger,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptionStateProvider,
NotificationViewHierarchyManager notificationViewHierarchyManager,
KeyguardViewMediator keyguardViewMediator,
NotificationAlertingManager notificationAlertingManager,
@@ -164,7 +167,7 @@
BubbleController bubbleController,
NotificationGroupManager groupManager,
VisualStabilityManager visualStabilityManager,
- DeviceProvisionedController deviceProvisionedController,
+ CarDeviceProvisionedController carDeviceProvisionedController,
NavigationBarController navigationBarController,
Lazy<AssistManager> assistManagerLazy,
ConfigurationController configurationController,
@@ -205,7 +208,10 @@
CarServiceProvider carServiceProvider,
Lazy<PowerManagerHelper> powerManagerHelperLazy,
CarNavigationBarController carNavigationBarController,
- FlingAnimationUtils.Builder flingAnimationUtilsBuilder) {
+ FlingAnimationUtils.Builder flingAnimationUtilsBuilder,
+ NotificationDataManager notificationDataManager,
+ CarUxRestrictionManagerWrapper carUxRestrictionManagerWrapper,
+ CarNotificationListener carNotificationListener) {
return new CarStatusBar(
context,
notificationsController,
@@ -246,7 +252,7 @@
bubbleController,
groupManager,
visualStabilityManager,
- deviceProvisionedController,
+ carDeviceProvisionedController,
navigationBarController,
assistManagerLazy,
configurationController,
@@ -286,6 +292,9 @@
carServiceProvider,
powerManagerHelperLazy,
carNavigationBarController,
- flingAnimationUtilsBuilder);
+ flingAnimationUtilsBuilder,
+ notificationDataManager,
+ carUxRestrictionManagerWrapper,
+ carNotificationListener);
}
}
diff --git a/packages/CarSystemUI/tests/src/com/android/systemui/car/notification/CarHeadsUpNotificationSystemContainerTest.java b/packages/CarSystemUI/tests/src/com/android/systemui/car/notification/CarHeadsUpNotificationSystemContainerTest.java
new file mode 100644
index 0000000..05b8e6a
--- /dev/null
+++ b/packages/CarSystemUI/tests/src/com/android/systemui/car/notification/CarHeadsUpNotificationSystemContainerTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2020 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.car.notification;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.testing.TestableResources;
+import android.view.View;
+import android.view.WindowManager;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.R;
+import com.android.systemui.SysuiTestCase;
+import com.android.systemui.car.CarDeviceProvisionedController;
+import com.android.systemui.statusbar.car.CarStatusBar;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper
+@SmallTest
+public class CarHeadsUpNotificationSystemContainerTest extends SysuiTestCase {
+ private CarHeadsUpNotificationSystemContainer mDefaultController;
+ private CarHeadsUpNotificationSystemContainer mOverrideEnabledController;
+ @Mock
+ private CarDeviceProvisionedController mCarDeviceProvisionedController;
+ @Mock
+ private CarStatusBar mCarStatusBar;
+ @Mock
+ private WindowManager mWindowManager;
+
+ @Mock
+ private View mNotificationView;
+ @Mock
+ private View mNotificationView2;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ when(mCarStatusBar.isPanelExpanded()).thenReturn(false);
+ when(mCarDeviceProvisionedController.isCurrentUserSetup()).thenReturn(true);
+ when(mCarDeviceProvisionedController.isCurrentUserSetupInProgress()).thenReturn(false);
+
+ TestableResources testableResources = mContext.getOrCreateTestableResources();
+
+ testableResources.addOverride(
+ R.bool.config_enableHeadsUpNotificationWhenNotificationShadeOpen, false);
+
+ mDefaultController = new CarHeadsUpNotificationSystemContainer(mContext,
+ testableResources.getResources(), mCarDeviceProvisionedController, mWindowManager,
+ () -> mCarStatusBar);
+
+ testableResources.addOverride(
+ R.bool.config_enableHeadsUpNotificationWhenNotificationShadeOpen, true);
+
+ mOverrideEnabledController = new CarHeadsUpNotificationSystemContainer(mContext,
+ testableResources.getResources(), mCarDeviceProvisionedController, mWindowManager,
+ () -> mCarStatusBar);
+ }
+
+ @Test
+ public void testDisplayNotification_firstNotification_isVisible() {
+ mDefaultController.displayNotification(mNotificationView);
+ assertThat(mDefaultController.isVisible()).isTrue();
+ }
+
+ @Test
+ public void testRemoveNotification_lastNotification_isInvisible() {
+ mDefaultController.displayNotification(mNotificationView);
+ mDefaultController.removeNotification(mNotificationView);
+ assertThat(mDefaultController.isVisible()).isFalse();
+ }
+
+ @Test
+ public void testRemoveNotification_nonLastNotification_isVisible() {
+ mDefaultController.displayNotification(mNotificationView);
+ mDefaultController.displayNotification(mNotificationView2);
+ mDefaultController.removeNotification(mNotificationView);
+ assertThat(mDefaultController.isVisible()).isTrue();
+ }
+
+ @Test
+ public void testDisplayNotification_userSetupInProgress_isInvisible() {
+ when(mCarDeviceProvisionedController.isCurrentUserSetupInProgress()).thenReturn(true);
+ mDefaultController.displayNotification(mNotificationView);
+ assertThat(mDefaultController.isVisible()).isFalse();
+
+ }
+
+ @Test
+ public void testDisplayNotification_userSetupIncomplete_isInvisible() {
+ when(mCarDeviceProvisionedController.isCurrentUserSetup()).thenReturn(false);
+ mDefaultController.displayNotification(mNotificationView);
+ assertThat(mDefaultController.isVisible()).isFalse();
+ }
+
+ @Test
+ public void testDisplayNotification_notificationPanelExpanded_isInvisible() {
+ when(mCarStatusBar.isPanelExpanded()).thenReturn(true);
+ mDefaultController.displayNotification(mNotificationView);
+ assertThat(mDefaultController.isVisible()).isFalse();
+ }
+
+ @Test
+ public void testDisplayNotification_notificationPanelExpandedEnabledHUNWhenOpen_isVisible() {
+ when(mCarStatusBar.isPanelExpanded()).thenReturn(true);
+ mOverrideEnabledController.displayNotification(mNotificationView);
+ assertThat(mOverrideEnabledController.isVisible()).isTrue();
+ }
+}
diff --git a/packages/CarSystemUI/tests/src/com/android/systemui/navigationbar/car/CarNavigationBarTest.java b/packages/CarSystemUI/tests/src/com/android/systemui/navigationbar/car/CarNavigationBarTest.java
index c04e47f..f2748b8 100644
--- a/packages/CarSystemUI/tests/src/com/android/systemui/navigationbar/car/CarNavigationBarTest.java
+++ b/packages/CarSystemUI/tests/src/com/android/systemui/navigationbar/car/CarNavigationBarTest.java
@@ -46,8 +46,6 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import dagger.Lazy;
-
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@SmallTest
@@ -68,12 +66,8 @@
@Mock
private ButtonSelectionStateListener mButtonSelectionStateListener;
@Mock
- private Lazy<KeyguardStateController> mKeyguardStateControllerLazy;
- @Mock
private KeyguardStateController mKeyguardStateController;
@Mock
- private Lazy<NavigationBarController> mNavigationBarControllerLazy;
- @Mock
private NavigationBarController mNavigationBarController;
@Mock
private SuperStatusBarViewFactory mSuperStatusBarViewFactory;
@@ -89,13 +83,11 @@
mCarNavigationBar = new CarNavigationBar(mContext, mCarNavigationBarController,
mWindowManager, mDeviceProvisionedController, new CommandQueue(mContext),
mAutoHideController, mButtonSelectionStateListener, mHandler,
- mKeyguardStateControllerLazy, mNavigationBarControllerLazy,
+ () -> mKeyguardStateController, () -> mNavigationBarController,
mSuperStatusBarViewFactory, mButtonSelectionStateController);
StatusBarWindowView statusBarWindowView = (StatusBarWindowView) LayoutInflater.from(
mContext).inflate(R.layout.super_status_bar, /* root= */ null);
when(mSuperStatusBarViewFactory.getStatusBarWindowView()).thenReturn(statusBarWindowView);
- when(mNavigationBarControllerLazy.get()).thenReturn(mNavigationBarController);
- when(mKeyguardStateControllerLazy.get()).thenReturn(mKeyguardStateController);
when(mKeyguardStateController.isShowing()).thenReturn(false);
mDependency.injectMockDependency(WindowManager.class);
// Needed to inflate top navigation bar.
@@ -119,4 +111,44 @@
verify(mButtonSelectionStateListener).onTaskStackChanged();
}
+
+ @Test
+ public void restartNavBars_newUserNotSetupWithKeyguardShowing_showsKeyguardButtons() {
+ ArgumentCaptor<CarDeviceProvisionedController.DeviceProvisionedListener>
+ deviceProvisionedCallbackCaptor = ArgumentCaptor.forClass(
+ CarDeviceProvisionedController.DeviceProvisionedListener.class);
+ when(mDeviceProvisionedController.isCurrentUserSetup()).thenReturn(true);
+ mCarNavigationBar.start();
+ when(mKeyguardStateController.isShowing()).thenReturn(true);
+ // switching the currentUserSetup value to force restart the navbars.
+ when(mDeviceProvisionedController.isCurrentUserSetup()).thenReturn(false);
+ verify(mDeviceProvisionedController).addCallback(deviceProvisionedCallbackCaptor.capture());
+
+ deviceProvisionedCallbackCaptor.getValue().onUserSwitched();
+ waitForIdleSync(mHandler);
+
+ verify(mCarNavigationBarController).showAllKeyguardButtons(false);
+ }
+
+ @Test
+ public void restartNavbars_newUserIsSetupWithKeyguardHidden_hidesKeyguardButtons() {
+ ArgumentCaptor<CarDeviceProvisionedController.DeviceProvisionedListener>
+ deviceProvisionedCallbackCaptor = ArgumentCaptor.forClass(
+ CarDeviceProvisionedController.DeviceProvisionedListener.class);
+ when(mDeviceProvisionedController.isCurrentUserSetup()).thenReturn(true);
+ mCarNavigationBar.start();
+ when(mKeyguardStateController.isShowing()).thenReturn(true);
+ // switching the currentUserSetup value to force restart the navbars.
+ when(mDeviceProvisionedController.isCurrentUserSetup()).thenReturn(false);
+ verify(mDeviceProvisionedController).addCallback(deviceProvisionedCallbackCaptor.capture());
+ deviceProvisionedCallbackCaptor.getValue().onUserSwitched();
+ waitForIdleSync(mHandler);
+ when(mDeviceProvisionedController.isCurrentUserSetup()).thenReturn(true);
+ when(mKeyguardStateController.isShowing()).thenReturn(false);
+
+ deviceProvisionedCallbackCaptor.getValue().onUserSetupChanged();
+ waitForIdleSync(mHandler);
+
+ verify(mCarNavigationBarController).hideAllKeyguardButtons(true);
+ }
}
diff --git a/packages/SettingsLib/Android.bp b/packages/SettingsLib/Android.bp
index 3f42ad4..4ea1047 100644
--- a/packages/SettingsLib/Android.bp
+++ b/packages/SettingsLib/Android.bp
@@ -2,6 +2,30 @@
name: "SettingsLib",
+ defaults: [
+ "SettingsLibDependenciesWithoutWifiTracker",
+ ],
+
+ // TODO(b/149540986): revert this change.
+ static_libs: [
+ // All other dependent components should be put in
+ // "SettingsLibDependenciesWithoutWifiTracker".
+ "WifiTrackerLib",
+ ],
+
+ // ANDROIDMK TRANSLATION ERROR: unsupported assignment to LOCAL_SHARED_JAVA_LIBRARIES
+ // LOCAL_SHARED_JAVA_LIBRARIES := androidx.lifecycle_lifecycle-common
+
+ resource_dirs: ["res"],
+
+ srcs: ["src/**/*.java", "src/**/*.kt"],
+
+ min_sdk_version: "21",
+
+}
+
+java_defaults {
+ name: "SettingsLibDependenciesWithoutWifiTracker",
static_libs: [
"androidx.annotation_annotation",
"androidx.legacy_legacy-support-v4",
@@ -25,20 +49,9 @@
"SettingsLibProgressBar",
"SettingsLibAdaptiveIcon",
"SettingsLibRadioButtonPreference",
- "WifiTrackerLib",
"SettingsLibDisplayDensityUtils",
"SettingsLibSchedulesProvider",
],
-
- // ANDROIDMK TRANSLATION ERROR: unsupported assignment to LOCAL_SHARED_JAVA_LIBRARIES
- // LOCAL_SHARED_JAVA_LIBRARIES := androidx.lifecycle_lifecycle-common
-
- resource_dirs: ["res"],
-
- srcs: ["src/**/*.java", "src/**/*.kt"],
-
- min_sdk_version: "21",
-
}
// NOTE: Keep this module in sync with ./common.mk
diff --git a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
index f93faeb..ace50f3 100644
--- a/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
+++ b/packages/SettingsLib/Tile/src/com/android/settingslib/drawer/TileUtils.java
@@ -545,7 +545,7 @@
bundle.putString(META_DATA_PREFERENCE_KEYHINT, key);
}
try {
- return provider.call(context.getPackageName(), context.getFeatureId(),
+ return provider.call(context.getPackageName(), context.getAttributionTag(),
uri.getAuthority(), method, uri.toString(), bundle);
} catch (RemoteException e) {
return null;
diff --git a/packages/SettingsLib/res/values-as/strings.xml b/packages/SettingsLib/res/values-as/strings.xml
index ce967a3..48af12a 100644
--- a/packages/SettingsLib/res/values-as/strings.xml
+++ b/packages/SettingsLib/res/values-as/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"জিপিইউ ডিবাগ স্তৰবোৰ সক্ষম কৰক"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ডিবাগ এপসমূহৰ বাবে জিপিইউ ডিবাগ তৰপ ল\'ড কৰিবলৈ অনুমতি দিয়ক"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"বিক্ৰেতাৰ ভাৰ্ব’ছ লগিং সক্ষম কৰক"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"বাগ ৰিপ’ৰ্টসমূহত অতিৰিক্ত ডিভাইচ নিৰ্দিষ্ট বিক্ৰেতাৰ লগসমূহ অন্তৰ্ভুক্ত কৰক, য’ত ব্যক্তিগত তথ্য থাকিব পাৰে, যি অধিক বেটাৰী আৰু/অথবা ষ্ট’ৰেজ ব্যৱহাৰ কৰিব পাৰে।"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"ৱিণ্ড\' এনিমেশ্বন স্কেল"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ট্ৰাঞ্জিশ্বন এনিমেশ্বন স্কেল"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"এনিমেটৰ কালদৈৰ্ঘ্য স্কেল"</string>
diff --git a/packages/SettingsLib/res/values-bn/strings.xml b/packages/SettingsLib/res/values-bn/strings.xml
index 6c459fc..c06100e 100644
--- a/packages/SettingsLib/res/values-bn/strings.xml
+++ b/packages/SettingsLib/res/values-bn/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ডিবাগ স্তর চালু করুন"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ডিবাগ অ্যাপের জন্য GPU ডিবাগ স্তর লোড হতে দিন"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"ভারবোস ভেন্ডর লগ-ইন চালু করুন"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"সমস্যা সংক্রান্ত রিপোর্টগুলিতে অতিরিক্ত ডিভাইস-নির্দিষ্ট ভেন্ডরের লগগুলি অন্তর্ভুক্ত করুন, যার মধ্যে ব্যক্তিগত তথ্য থাকতে পারে, আরও বেশি ব্যাটারি ব্যবহার করতে পারে, এবং/অথবা আরও স্টোরেজ ব্যবহার করতে পারে।"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"উইন্ডো অ্যানিমেশন স্কেল"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ট্র্যানজিশন অ্যানিমেশন স্কেল"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"অ্যানিমেটর সময়কাল স্কেল"</string>
diff --git a/packages/SettingsLib/res/values-de/strings.xml b/packages/SettingsLib/res/values-de/strings.xml
index b388686..721163b 100644
--- a/packages/SettingsLib/res/values-de/strings.xml
+++ b/packages/SettingsLib/res/values-de/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU-Debug-Ebenen zulassen"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"Debug-Apps das Laden von GPU-Debug-Ebenen erlauben"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"Ausführliche Protokollierung aktivieren"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"Schließt zusätzliche gerätespezifische Anbieterprotokolle in Fehlerberichten ein, die private Informationen enthalten, den Akkuverbrauch erhöhen und/oder zusätzlichen Speicher benötigen können."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"Fensteranimationsfaktor"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"Übergangsanimationsfaktor"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"Animationsdauerfaktor"</string>
diff --git a/packages/SettingsLib/res/values-eu/strings.xml b/packages/SettingsLib/res/values-eu/strings.xml
index 95ed7f0..e035a81 100644
--- a/packages/SettingsLib/res/values-eu/strings.xml
+++ b/packages/SettingsLib/res/values-eu/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"Gaitu GPUaren arazketa-geruzak"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"Eman GPUaren arazketa-geruzak kargatzeko baimena arazketa-aplikazioei"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"Gaitu saltzaileen erregistro xehatuak"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"Sartu gailuaren berariazko saltzaileen erregistro gehigarriak akatsen txostenetan; baliteke haiek informazio pribatua izatea, bateria gehiago erabiltzea edo biltegiratzeko toki gehiago hartzea."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"Leihoen animazio-eskala"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"Trantsizioen animazio-eskala"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"Animatzailearen iraupena"</string>
diff --git a/packages/SettingsLib/res/values-fr-rCA/strings.xml b/packages/SettingsLib/res/values-fr-rCA/strings.xml
index 8ee44ac..e1ff83f 100644
--- a/packages/SettingsLib/res/values-fr-rCA/strings.xml
+++ b/packages/SettingsLib/res/values-fr-rCA/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"Activer couches débogage GPU"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"Autoriser couches débogage GPU pour applis de débogage"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"Activer le journal détaillé des fournisseurs"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"Incluez les journaux supplémentaires du fournisseur propres à l\'appareil dans les rapports de bogue. Ils peuvent contenir des données personnelles, épuiser la pile plus rapidement et/ou utiliser plus d\'espace de stockage."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"Échelle animation fenêtres"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"Échelle animination transitions"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"Échelle durée animation"</string>
diff --git a/packages/SettingsLib/res/values-gu/strings.xml b/packages/SettingsLib/res/values-gu/strings.xml
index 00c7b37..b81eba3 100644
--- a/packages/SettingsLib/res/values-gu/strings.xml
+++ b/packages/SettingsLib/res/values-gu/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ડિબગ સ્તરોને સક્ષમ કરો"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ડિબગ ઍપ માટે GPU ડિબગ સ્તરો લોડ કરવાની મંજૂરી આપો"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"વર્બોઝ વેન્ડર લૉગિંગ ચાલુ કરો"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"ખામીની જાણકારીમાં ડિવાઇસથી જોડાયેલા ચોક્કસ વેન્ડર લૉગ શામેલ કરો, જેમાં ખાનગી માહિતી શામેલ હોઈ શકે છે, તે વધુ બૅટરીનો ઉપયોગ કરી શકે છે અને/અથવા વધુ સ્ટોરેજનો ઉપયોગ કરી શકે છે."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"વિંડો એનિમેશન સ્કેલ"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"સંક્રમણ એનિમેશન સ્કેલ"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"એનિમેટર અવધિ સ્કેલ"</string>
diff --git a/packages/SettingsLib/res/values-hi/strings.xml b/packages/SettingsLib/res/values-hi/strings.xml
index b382234..414b876 100644
--- a/packages/SettingsLib/res/values-hi/strings.xml
+++ b/packages/SettingsLib/res/values-hi/strings.xml
@@ -358,8 +358,7 @@
<string name="track_frame_time" msgid="522674651937771106">"प्रोफ़ाइल HWUI रेंडरिंग"</string>
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"जीपीयू डीबग लेयर चालू करें"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"डीबग ऐप के लिए जीपीयू डीबग लेयर लोड करने दें"</string>
- <!-- no translation found for enable_verbose_vendor_logging (1196698788267682072) -->
- <skip />
+ <string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"वर्बोस वेंडर लॉगिंग चालू करें"</string>
<string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"गड़बड़ियों की रिपोर्ट में खास डिवाइस से जुड़े वेंडर लॉग शामिल करें. इन लॉग में निजी जानकारी, बैटरी का ज़्यादा इस्तेमाल, और/या डिवाइस की मेमोरी ज़्यादा इस्तेमाल करने की जानकारी हो सकती है."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"विंडो एनिमेशन स्केल"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ट्रांज़िशन एनिमेशन स्केल"</string>
@@ -508,9 +507,7 @@
<string name="zen_mode_duration_always_prompt_title" msgid="3212996860498119555">"हर बार पूछें"</string>
<string name="zen_mode_forever" msgid="3339224497605461291">"जब तक आप इसे बंद नहीं करते"</string>
<string name="time_unit_just_now" msgid="3006134267292728099">"अभी-अभी"</string>
- <!-- no translation found for media_transfer_this_device_name (2716555073132169240) -->
- <skip />
+ <string name="media_transfer_this_device_name" msgid="2716555073132169240">"फ़ोन का स्पीकर"</string>
<string name="profile_connect_timeout_subtext" msgid="4043408193005851761">"कनेक्ट करने में समस्या हो रही है. डिवाइस को बंद करके चालू करें"</string>
- <!-- no translation found for media_transfer_wired_device_name (4447880899964056007) -->
- <skip />
+ <string name="media_transfer_wired_device_name" msgid="4447880899964056007">"वायर वाला ऑडियो डिवाइस"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-is/strings.xml b/packages/SettingsLib/res/values-is/strings.xml
index 7a7ba4c..002709c 100644
--- a/packages/SettingsLib/res/values-is/strings.xml
+++ b/packages/SettingsLib/res/values-is/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"Virkja villuleit skják."</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"Leyfa villuleit skjákorts fyrir villuleit forrita"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"Nákvæm skráning söluaðila"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"Taka með viðbótarannála söluaðila fyrir tiltekin tæki í villutilkynningum, sem gætu innihaldið viðkvæmar upplýsingar, notað meiri rafhlöðuorku og/eða þurft meira geymslupláss."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"Kvarði gluggahreyfinga"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"Lengd hreyfiumbreytinga"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"Tímalengd hreyfiáhrifa"</string>
diff --git a/packages/SettingsLib/res/values-iw/strings.xml b/packages/SettingsLib/res/values-iw/strings.xml
index 49929d4..975ccdc 100644
--- a/packages/SettingsLib/res/values-iw/strings.xml
+++ b/packages/SettingsLib/res/values-iw/strings.xml
@@ -357,7 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"הפעלת שכבות לניפוי באגים ב-GPU"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"טעינת שכבות לניפוי באגים ב-GPU לאפליקציות ניפוי באגים"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"הפעלת רישום ספקים מפורט ביומן"</string>
- <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"הכללת יומני ספקים נוספים, ספציפיים למכשירים, בדוחות על באגים, שעשויים להכיל מידע פרטי, לצרוך יותר מהסוללה ו/או להשתמש ביותר אחסון."</string>
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"הוספת רישומי יומן של יצרנים למכשירים ספציפיים בדוחות על באגים. דוחות אלה עשויים להכיל מידע פרטי, להגביר את צריכת הסוללה ולצרוך שטח אחסון גדול יותר."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"קנה מידה לאנימציה של חלון"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"קנה מידה לאנימציית מעבר"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"קנה מידה למשך זמן אנימציה"</string>
diff --git a/packages/SettingsLib/res/values-km/strings.xml b/packages/SettingsLib/res/values-km/strings.xml
index 337bb8b..0ceda18 100644
--- a/packages/SettingsLib/res/values-km/strings.xml
+++ b/packages/SettingsLib/res/values-km/strings.xml
@@ -357,7 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"បើកស្រទាប់ជួសជុល GPU"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"អនុញ្ញាតឱ្យផ្ទុកស្រទាប់ជួសជុល GPU សម្រាប់កម្មវិធីជួសជុល"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"បើកកំណត់ហេតុរៀបរាប់អំពីអ្នកលក់"</string>
- <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"រួមមានកំណត់ហេតុបន្ថែមអំពីអ្នកលក់ឧបករណ៍ជាក់លាក់នៅក្នុងរបាយការណ៍អំពីបញ្ហា ដែលអាចមានព័ត៌មានឯកជន ប្រើប្រាស់ថ្មច្រើនជាងមុន និង/ឬប្រើប្រាស់ទំហំផ្ទុកច្រើនជាងមុន។"</string>
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"រួមមានកំណត់ហេតុបន្ថែមអំពីអ្នកផ្គត់ផ្គង់សម្រាប់ឧបករណ៍ជាក់លាក់នៅក្នុងរបាយការណ៍អំពីបញ្ហា ដែលអាចមានព័ត៌មានឯកជន ប្រើប្រាស់ថ្មច្រើនជាងមុន និង/ឬប្រើប្រាស់ទំហំផ្ទុកច្រើនជាងមុន។"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"មាត្រដ្ឋានចលនាវិនដូ"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"មាត្រដ្ឋានដំណើរផ្លាស់ប្ដូរចលនា"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"មាត្រដ្ឋានរយៈពេលនៃកម្មវិធីចលនា"</string>
diff --git a/packages/SettingsLib/res/values-kn/strings.xml b/packages/SettingsLib/res/values-kn/strings.xml
index 926c98a..d23aeff 100644
--- a/packages/SettingsLib/res/values-kn/strings.xml
+++ b/packages/SettingsLib/res/values-kn/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ಡೀಬಗ್ ಲೇಯರ್ಗಳನ್ನು ಸಕ್ರಿಯಗೊಳಿಸಿ"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ಡೀಬಗ್ ಅಪ್ಲಿಕೇಶನ್ಗಳಿಗಾಗಿ GPU ಡೀಬಗ್ ಲೇಯರ್ಗಳನ್ನು ಲೋಡ್ ಮಾಡುವುದನ್ನು ಅನುಮತಿಸಿ"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"ವೆರ್ಬೋಸ್ ವೆಂಡರ್ ಲಾಗಿಂಗ್ ಆನ್"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"ಬಗ್ ವರದಿಗಳಲ್ಲಿ ಹೆಚ್ಚುವರಿ ಸಾಧನ ನಿರ್ದಿಷ್ಟ ವೆಂಡರ್ ಲಾಗ್ಗಳು ಒಳಗೊಂಡಿದೆ, ಇದು ಖಾಸಗಿ ಮಾಹಿತಿ, ಹೆಚ್ಚಿನ ಬ್ಯಾಟರಿ ಬಳಕೆ ಮತ್ತು/ಅಥವಾ ಹೆಚ್ಚಿನ ಸಂಗ್ರಹಣೆಯ ಬಳಕೆಯನ್ನು ಒಳಗೊಂಡಿರಬಹುದು."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"Window ಅನಿಮೇಶನ್ ಸ್ಕೇಲ್"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ಪರಿವರ್ತನೆ ಅನಿಮೇಶನ್ ಸ್ಕೇಲ್"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"ಅನಿಮೇಟರ್ ಅವಧಿಯ ಪ್ರಮಾಣ"</string>
diff --git a/packages/SettingsLib/res/values-ml/strings.xml b/packages/SettingsLib/res/values-ml/strings.xml
index a360fcd..06ee219 100644
--- a/packages/SettingsLib/res/values-ml/strings.xml
+++ b/packages/SettingsLib/res/values-ml/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ഡീബഗ് ലെയറുകൾ പ്രവർത്തനക്ഷമമാക്കൂ"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ഡീബഗ് ആപ്പുകൾക്കായി GPU ഡീബഗ് ലെയറുകൾ ലോഡ് ചെയ്യാൻ അനുവദിക്കുക"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"വെർബോസ് വെണ്ടർ ലോഗ് ചെയ്യൽ പ്രവർത്തനക്ഷമമാക്കൂ"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"ബഗ് റിപ്പോർട്ടുകളിൽ ഉപകരണ-നിർദ്ദിഷ്ട വെണ്ടർ അധിക ലോഗുകൾ ഉൾപ്പെടുത്തുക, അതിൽ സ്വകാര്യ വിവരങ്ങൾ അടങ്ങിയിരിക്കാം, കൂടുതൽ ബാറ്ററി ഉപയോഗിക്കാം കൂടാതെ/അല്ലെങ്കിൽ കൂടുതൽ സ്റ്റോറേജ് ഇടം ഉപയോഗിക്കാം."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"വിൻഡോ ആനിമേഷൻ സ്കെയിൽ"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"സംക്രമണ ആനിമേഷൻ സ്കെയിൽ"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"ആനിമേറ്റർ ദൈർഘ്യ സ്കെയിൽ"</string>
diff --git a/packages/SettingsLib/res/values-mr/strings.xml b/packages/SettingsLib/res/values-mr/strings.xml
index afb88de..543152a 100644
--- a/packages/SettingsLib/res/values-mr/strings.xml
+++ b/packages/SettingsLib/res/values-mr/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU डीबग स्तर सुरू करा"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"डीबग अॅप्ससाठी GPU डीबग स्तर लोड करण्याची अनुमती द्या"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"व्हर्बोझ विक्रेता लॉगिंग सुरू करा"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"बग रिपोर्टमध्ये अतिरिक्त डिव्हाइस-विशिष्ट विक्रेता लॉगचा समावेश करा ज्यामध्ये खाजगी माहिती असू शकते, अधिक बॅटरी आणि/किंवा अधिक स्टोरेज वापरले जाईल."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"विंडो ॲनिमेशन स्केल"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ट्रांझिशन ॲनिमेशन स्केल"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"ॲनिमेटर कालावधी स्केल"</string>
diff --git a/packages/SettingsLib/res/values-ne/strings.xml b/packages/SettingsLib/res/values-ne/strings.xml
index e78e8fa..89d66ab 100644
--- a/packages/SettingsLib/res/values-ne/strings.xml
+++ b/packages/SettingsLib/res/values-ne/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU का डिबग तहहरूलाई सक्षम पार्नुहोस्"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"डिबगसम्बन्धी अनुप्रयोगहरूका लागि GPU का डिबग तहहरूलाई लोड गर्न दिनुहोस्"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"भर्वस भेन्डर लगिङ सक्षम पार्नु…"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"बग रिपोर्टहरूमा यन्त्र विशेष विक्रेताका अतिरिक्त लगहरू समावेश गर्नुहोस्। यी लगमा निजी जानकारी समावेश हुन सक्छन्, यिनले ब्याट्रीको खपत बढाउन र/वा थप भण्डारण प्रयोग गर्न सक्छन्।"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"विन्डो सजीविकरण स्केल"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"संक्रमण सजीविकरण मापन"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"सजीविकरण अवधि मापन"</string>
diff --git a/packages/SettingsLib/res/values-or/strings.xml b/packages/SettingsLib/res/values-or/strings.xml
index 65c44cb..b475846de 100644
--- a/packages/SettingsLib/res/values-or/strings.xml
+++ b/packages/SettingsLib/res/values-or/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ଡିବଗ୍ ଲେୟର୍ ସକ୍ଷମ କରନ୍ତୁ"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ଡିବଗ୍ ଆପ୍ଗୁଡ଼ିକ ପାଇଁ GPU ଡିବଗ୍ ଲେୟର୍ ଲୋଡ୍ କରିବାର ଅନୁମତି ଦିଅନ୍ତୁ"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"ଭର୍ବୋସ ଭେଣ୍ଡର୍ ଲଗିଂ ସକ୍ଷମ କରନ୍ତୁ"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"ବଗ୍ ରିପୋର୍ଟଗୁଡ଼ିକରେ ଅତିରିକ୍ତ ଡିଭାଇସ୍-ନିର୍ଦ୍ଦିଷ୍ଟ ଲଗଗୁଡ଼ିକ ସାମିଲ କରନ୍ତୁ, ଯେଉଁଥିରେ ବ୍ୟକ୍ତିଗତ ସୂଚନା ଥାଇପାରେ, ଯାହା ଅଧିକ ବ୍ୟାଟେରୀ ଏବଂ/କିମ୍ବା ଅଧିକ ଷ୍ଟୋରେଜ୍ ବ୍ୟବହାର କରିପାରେ।"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"ୱିଣ୍ଡୋ ଆନିମେସନ୍ ସ୍କେଲ୍"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ଟ୍ରାଞ୍ଜିସନ୍ ଆନିମେସନ୍ ସ୍କେଲ୍"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"ଆନିମେଟର୍ ଅବଧି ସ୍କେଲ୍"</string>
diff --git a/packages/SettingsLib/res/values-pa/strings.xml b/packages/SettingsLib/res/values-pa/strings.xml
index ed020e8..6cd3d84 100644
--- a/packages/SettingsLib/res/values-pa/strings.xml
+++ b/packages/SettingsLib/res/values-pa/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ਡੀਬੱਗ ਲੇਅਰਾਂ ਚਾਲੂ ਕਰੋ"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ਡੀਬੱਗ ਐਪਾਂ ਲਈ GPU ਡੀਬੱਗ ਲੇਅਰਾਂ ਨੂੰ ਲੋਡ ਹੋਣ ਦਿਓ"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"ਵਰਬੋਸ ਵਿਕਰੇਤਾ ਲੌਗਿੰਗ ਚਾਲੂ ਕਰੋ"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"ਬੱਗ ਰਿਪੋਰਟਾਂ ਵਿੱਚ ਵਧੀਕ ਡੀਵਾਈਸ ਨਾਲ ਸੰਬੰਧਿਤ ਵਿਕਰੇਤਾ ਲੌਗ ਸ਼ਾਮਲ ਕਰੋ, ਜਿਨ੍ਹਾਂ ਵਿੱਚ ਨਿੱਜੀ ਜਾਣਕਾਰੀ, ਬੈਟਰੀ ਦੀ ਵਧੇਰੇ ਵਰਤੋਂ, ਅਤੇ/ਜਾਂ ਵਧੇਰੀ ਸਟੋਰੇਜ ਸ਼ਾਮਲ ਹੋ ਸਕਦੀ ਹੈ।"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"ਵਿੰਡੋ ਐਨੀਮੇਸ਼ਨ ਸਕੇਲ"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ਟ੍ਰਾਂਜਿਸ਼ਨ ਐਨੀਮੇਸ਼ਨ ਸਕੇਲ"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"ਐਨੀਮੇਟਰ ਮਿਆਦ ਸਕੇਲ"</string>
diff --git a/packages/SettingsLib/res/values-ta/strings.xml b/packages/SettingsLib/res/values-ta/strings.xml
index 18ab23d..ce4d72d 100644
--- a/packages/SettingsLib/res/values-ta/strings.xml
+++ b/packages/SettingsLib/res/values-ta/strings.xml
@@ -255,8 +255,7 @@
<string name="bluetooth_show_devices_without_names" msgid="923584526471885819">"பெயர்கள் இல்லாத புளூடூத் சாதனங்களைக் காட்டு"</string>
<string name="bluetooth_disable_absolute_volume" msgid="1452342324349203434">"அப்சல்யூட் ஒலியளவு அம்சத்தை முடக்கு"</string>
<string name="bluetooth_enable_gabeldorsche" msgid="9131730396242883416">"Gabeldorscheவை இயக்கு"</string>
- <!-- no translation found for enhanced_connectivity (7201127377781666804) -->
- <skip />
+ <string name="enhanced_connectivity" msgid="7201127377781666804">"மேம்படுத்தப்பட்ட இணைப்புநிலை"</string>
<string name="bluetooth_select_avrcp_version_string" msgid="1710571610177659127">"புளூடூத் AVRCP பதிப்பு"</string>
<string name="bluetooth_select_avrcp_version_dialog_title" msgid="7846922290083709633">"புளூடூத் AVRCP பதிப்பைத் தேர்ந்தெடு"</string>
<string name="bluetooth_select_map_version_string" msgid="526308145174175327">"புளூடூத்தின் MAP பதிப்பு"</string>
@@ -310,8 +309,7 @@
<string name="bluetooth_show_devices_without_names_summary" msgid="780964354377854507">"பெயர்கள் இல்லாத புளூடூத் சாதனங்கள் (MAC முகவரிகள் மட்டும்) காட்டப்படும்"</string>
<string name="bluetooth_disable_absolute_volume_summary" msgid="2006309932135547681">"மிகவும் அதிகமான ஒலியளவு அல்லது கட்டுப்பாடு இழப்பு போன்ற தொலைநிலைச் சாதனங்களில் ஏற்படும் ஒலி தொடர்பான சிக்கல்கள் இருக்கும் சமயங்களில், புளூடூத் அப்சல்யூட் ஒலியளவு அம்சத்தை முடக்கும்."</string>
<string name="bluetooth_enable_gabeldorsche_summary" msgid="2054730331770712629">"புளூடூத்தின் Gabeldorsche அம்சங்களை இயக்கும்."</string>
- <!-- no translation found for enhanced_connectivity_summary (1576414159820676330) -->
- <skip />
+ <string name="enhanced_connectivity_summary" msgid="1576414159820676330">"மேம்படுத்தப்பட்ட இணைப்புநிலை அம்சத்தை இயக்கும்."</string>
<string name="enable_terminal_title" msgid="3834790541986303654">"அக முனையம்"</string>
<string name="enable_terminal_summary" msgid="2481074834856064500">"அக ஷெல் அணுகலை வழங்கும் இறுதிப் ஆப்ஸை இயக்கு"</string>
<string name="hdcp_checking_title" msgid="3155692785074095986">"HDCP சரிபார்ப்பு"</string>
@@ -358,8 +356,7 @@
<string name="track_frame_time" msgid="522674651937771106">"சுயவிவர HWUI ரெண்டரிங்"</string>
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU பிழைத்திருத்த லேயர்களை இயக்கு"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"பிழைத்திருத்த ஆப்ஸிற்கு, GPU பிழைத்திருத்த லேயர்களை ஏற்றுவதற்கு அனுமதி"</string>
- <!-- no translation found for enable_verbose_vendor_logging (1196698788267682072) -->
- <skip />
+ <string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"வெர்போஸ் வெண்டார் பதிவை இயக்கு"</string>
<!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
<skip />
<string name="window_animation_scale_title" msgid="5236381298376812508">"சாளர அனிமேஷன் வேகம்"</string>
@@ -509,9 +506,7 @@
<string name="zen_mode_duration_always_prompt_title" msgid="3212996860498119555">"ஒவ்வொரு முறையும் கேள்"</string>
<string name="zen_mode_forever" msgid="3339224497605461291">"ஆஃப் செய்யும் வரை"</string>
<string name="time_unit_just_now" msgid="3006134267292728099">"சற்றுமுன்"</string>
- <!-- no translation found for media_transfer_this_device_name (2716555073132169240) -->
- <skip />
+ <string name="media_transfer_this_device_name" msgid="2716555073132169240">"மொபைல் ஸ்பீக்கர்"</string>
<string name="profile_connect_timeout_subtext" msgid="4043408193005851761">"இணைப்பதில் சிக்கல். சாதனத்தை ஆஃப் செய்து மீண்டும் ஆன் செய்யவும்"</string>
- <!-- no translation found for media_transfer_wired_device_name (4447880899964056007) -->
- <skip />
+ <string name="media_transfer_wired_device_name" msgid="4447880899964056007">"வயருடன்கூடிய ஆடியோ சாதனம்"</string>
</resources>
diff --git a/packages/SettingsLib/res/values-te/strings.xml b/packages/SettingsLib/res/values-te/strings.xml
index 74739ee..2508d74 100644
--- a/packages/SettingsLib/res/values-te/strings.xml
+++ b/packages/SettingsLib/res/values-te/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU డీబగ్ లేయర్లను ప్రారంభించండి"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"డీబగ్ యాప్ల కోసం GPU డీబగ్ లేయర్లను లోడ్ చేయడాన్ని అనుమతించండి"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"వివరణాత్మక విక్రేత లాగింగ్ను ఎనేబుల్ చేయండి"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"బగ్ నివేదికలలో అదనపు పరికర-నిర్దిష్ట వెండార్ లాగ్లను చేర్చండి, అవి ప్రైవేట్ సమాచారాన్ని కలిగి ఉండవచ్చు, మరింత బ్యాటరీని, మరియు/లేదా మరింత స్టోరేజ్ను ఉపయోగించవచ్చు."</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"విండో యానిమేషన్ ప్రమాణం"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"పరివర్తన యానిమేషన్ ప్రమాణం"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"యానిమేటర్ వ్యవధి ప్రమాణం"</string>
diff --git a/packages/SettingsLib/res/values-ur/strings.xml b/packages/SettingsLib/res/values-ur/strings.xml
index 10bce1b..56f4f06 100644
--- a/packages/SettingsLib/res/values-ur/strings.xml
+++ b/packages/SettingsLib/res/values-ur/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"GPU ڈیبگ پرتیں فعال کریں"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"ڈیبگ ایپس کیلئے GPU ڈیبگ پرتوں کو لوڈ کرنے دیں"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"وربوس وینڈر لاگنگ فعال کریں"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"اضافی آلہ کے مخصوص وینڈر لاگز کو بگ رپورٹس میں شامل کریں، جن میں نجی معلومات، بیٹری کا زیادہ استعمال اور/یا اسٹوریج کا زیادہ استعمال شامل ہوسکتے ہیں۔"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"ونڈو اینیمیشن اسکیل"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"ٹرانزیشن اینیمیشن اسکیل"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"اینیمیٹر دورانیے کا اسکیل"</string>
diff --git a/packages/SettingsLib/res/values-zh-rCN/strings.xml b/packages/SettingsLib/res/values-zh-rCN/strings.xml
index b2b9dc7..b83469b 100644
--- a/packages/SettingsLib/res/values-zh-rCN/strings.xml
+++ b/packages/SettingsLib/res/values-zh-rCN/strings.xml
@@ -357,8 +357,7 @@
<string name="enable_gpu_debug_layers" msgid="4986675516188740397">"启用 GPU 调试层"</string>
<string name="enable_gpu_debug_layers_summary" msgid="4921521407377170481">"允许为调试应用加载 GPU 调试层"</string>
<string name="enable_verbose_vendor_logging" msgid="1196698788267682072">"启用详细供应商日志记录"</string>
- <!-- no translation found for enable_verbose_vendor_logging_summary (5426292185780393708) -->
- <skip />
+ <string name="enable_verbose_vendor_logging_summary" msgid="5426292185780393708">"在错误报告中包含其他设备特定的供应商日志,这些日志可能会含有隐私信息、消耗更多电量和/或使用更多存储空间。"</string>
<string name="window_animation_scale_title" msgid="5236381298376812508">"窗口动画缩放"</string>
<string name="transition_animation_scale_title" msgid="1278477690695439337">"过渡动画缩放"</string>
<string name="animator_duration_scale_title" msgid="7082913931326085176">"Animator 时长缩放"</string>
diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml
index e8e1d0b..00f6bcb 100644
--- a/packages/SettingsLib/res/values/strings.xml
+++ b/packages/SettingsLib/res/values/strings.xml
@@ -1039,7 +1039,7 @@
<!-- Title for the accessibility preference to configure display color space correction. [CHAR LIMIT=NONE] -->
<string name="accessibility_display_daltonizer_preference_title">Color correction</string>
<!-- Subtitle for the accessibility preference to configure display color space correction. [CHAR LIMIT=NONE] -->
- <string name="accessibility_display_daltonizer_preference_subtitle">Color correction helps people with colorblindness see more accurate colors</string>
+ <string name="accessibility_display_daltonizer_preference_subtitle">Color correction helps the device display more accurate colors. Color correction may be helpful for people with colorblindness.</string>
<!-- Summary shown for color space correction preference when its value is overridden by another preference [CHAR LIMIT=35] -->
<string name="daltonizer_type_overridden">Overridden by <xliff:g id="title" example="Simulate color space">%1$s</xliff:g></string>
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java
index 18eb187..3c78560 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/A2dpProfile.java
@@ -218,7 +218,7 @@
}
public boolean supportsHighQualityAudio(BluetoothDevice device) {
- BluetoothDevice bluetoothDevice = (device == null) ? device : mService.getActiveDevice();
+ BluetoothDevice bluetoothDevice = (device != null) ? device : mService.getActiveDevice();
if (bluetoothDevice == null) {
return false;
}
@@ -227,7 +227,7 @@
}
public boolean isHighQualityAudioEnabled(BluetoothDevice device) {
- BluetoothDevice bluetoothDevice = (device == null) ? device : mService.getActiveDevice();
+ BluetoothDevice bluetoothDevice = (device != null) ? device : mService.getActiveDevice();
if (bluetoothDevice == null) {
return false;
}
@@ -253,7 +253,7 @@
}
public void setHighQualityAudioEnabled(BluetoothDevice device, boolean enabled) {
- BluetoothDevice bluetoothDevice = (device == null) ? device : mService.getActiveDevice();
+ BluetoothDevice bluetoothDevice = (device != null) ? device : mService.getActiveDevice();
if (bluetoothDevice == null) {
return;
}
@@ -272,7 +272,7 @@
}
public String getHighQualityAudioOptionLabel(BluetoothDevice device) {
- BluetoothDevice bluetoothDevice = (device == null) ? device : mService.getActiveDevice();
+ BluetoothDevice bluetoothDevice = (device != null) ? device : mService.getActiveDevice();
int unknownCodecId = R.string.bluetooth_profile_a2dp_high_quality_unknown_codec;
if (bluetoothDevice == null || !supportsHighQualityAudio(device)
|| getConnectionStatus(device) != BluetoothProfile.STATE_CONNECTED) {
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
index 7e78a78..eb0ddfb 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
@@ -24,6 +24,7 @@
import static android.media.MediaRoute2Info.TYPE_UNKNOWN;
import static android.media.MediaRoute2Info.TYPE_WIRED_HEADPHONES;
import static android.media.MediaRoute2Info.TYPE_WIRED_HEADSET;
+import static android.media.MediaRoute2ProviderService.REASON_UNKNOWN_ERROR;
import android.app.Notification;
import android.bluetooth.BluetoothAdapter;
@@ -50,6 +51,7 @@
public class InfoMediaManager extends MediaManager {
private static final String TAG = "InfoMediaManager";
+ private static final boolean DEBUG = false;
@VisibleForTesting
final RouterManagerCallback mMediaRouterCallback = new RouterManagerCallback();
@@ -339,6 +341,9 @@
private void buildAllRoutes() {
for (MediaRoute2Info route : mRouterManager.getAllRoutes()) {
+ if (DEBUG) {
+ Log.d(TAG, "buildAllRoutes() route : " + route.getName());
+ }
if (route.isSystemRoute()) {
addMediaDevice(route);
}
@@ -347,6 +352,9 @@
private void buildAvailableRoutes() {
for (MediaRoute2Info route : mRouterManager.getAvailableRoutes(mPackageName)) {
+ if (DEBUG) {
+ Log.d(TAG, "buildAvailableRoutes() route : " + route.getName());
+ }
addMediaDevice(route);
}
}
@@ -363,7 +371,8 @@
mediaDevice = new InfoMediaDevice(mContext, mRouterManager, route,
mPackageName);
if (!TextUtils.isEmpty(mPackageName)
- && TextUtils.equals(route.getClientPackageName(), mPackageName)) {
+ && TextUtils.equals(route.getClientPackageName(), mPackageName)
+ && mCurrentConnectedDevice == null) {
mCurrentConnectedDevice = mediaDevice;
}
break;
@@ -409,12 +418,41 @@
@Override
public void onRoutesChanged(List<MediaRoute2Info> routes) {
- refreshDevices();
+ mMediaDevices.clear();
+ mCurrentConnectedDevice = null;
+ if (TextUtils.isEmpty(mPackageName)) {
+ buildAllRoutes();
+ } else {
+ buildAvailableRoutes();
+ }
+
+ final String id = mCurrentConnectedDevice != null
+ ? mCurrentConnectedDevice.getId()
+ : null;
+ dispatchConnectedDeviceChanged(id);
}
@Override
public void onRoutesRemoved(List<MediaRoute2Info> routes) {
refreshDevices();
}
+
+ @Override
+ public void onTransferred(RoutingSessionInfo oldSession, RoutingSessionInfo newSession) {
+ if (DEBUG) {
+ Log.d(TAG, "onTransferred() oldSession : " + oldSession.getName()
+ + ", newSession : " + newSession.getName());
+ }
+ }
+
+ @Override
+ public void onTransferFailed(RoutingSessionInfo session, MediaRoute2Info route) {
+ dispatchOnRequestFailed(REASON_UNKNOWN_ERROR);
+ }
+
+ @Override
+ public void onRequestFailed(int reason) {
+ dispatchOnRequestFailed(reason);
+ }
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
index adb3c11..44b481d 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
@@ -49,11 +49,13 @@
@Retention(RetentionPolicy.SOURCE)
@IntDef({MediaDeviceState.STATE_CONNECTED,
MediaDeviceState.STATE_CONNECTING,
- MediaDeviceState.STATE_DISCONNECTED})
+ MediaDeviceState.STATE_DISCONNECTED,
+ MediaDeviceState.STATE_CONNECTING_FAILED})
public @interface MediaDeviceState {
- int STATE_CONNECTED = 1;
- int STATE_CONNECTING = 2;
- int STATE_DISCONNECTED = 3;
+ int STATE_CONNECTED = 0;
+ int STATE_CONNECTING = 1;
+ int STATE_DISCONNECTED = 2;
+ int STATE_CONNECTING_FAILED = 3;
}
private final Collection<DeviceCallback> mCallbacks = new CopyOnWriteArrayList<>();
@@ -108,14 +110,12 @@
new InfoMediaManager(context, packageName, notification, mLocalBluetoothManager);
}
- @VisibleForTesting
- LocalMediaManager(Context context, LocalBluetoothManager localBluetoothManager,
+ public LocalMediaManager(Context context, LocalBluetoothManager localBluetoothManager,
InfoMediaManager infoMediaManager, String packageName) {
mContext = context;
mLocalBluetoothManager = localBluetoothManager;
mInfoMediaManager = infoMediaManager;
mPackageName = packageName;
-
}
/**
@@ -128,6 +128,7 @@
final CachedBluetoothDevice cachedDevice =
((BluetoothMediaDevice) device).getCachedDevice();
if (!cachedDevice.isConnected() && !cachedDevice.isBusy()) {
+ device.setState(MediaDeviceState.STATE_CONNECTING);
cachedDevice.connect();
return;
}
@@ -142,20 +143,12 @@
mCurrentConnectedDevice.disconnect();
}
- boolean isConnected = false;
+ device.setState(MediaDeviceState.STATE_CONNECTING);
if (TextUtils.isEmpty(mPackageName)) {
- isConnected = mInfoMediaManager.connectDeviceWithoutPackageName(device);
+ mInfoMediaManager.connectDeviceWithoutPackageName(device);
} else {
- isConnected = device.connect();
+ device.connect();
}
- if (isConnected) {
- mCurrentConnectedDevice = device;
- }
-
- final int state = isConnected
- ? MediaDeviceState.STATE_CONNECTED
- : MediaDeviceState.STATE_DISCONNECTED;
- dispatchSelectedDeviceStateChanged(device, state);
}
void dispatchSelectedDeviceStateChanged(MediaDevice device, @MediaDeviceState int state) {
@@ -186,6 +179,12 @@
}
}
+ void dispatchOnRequestFailed(int reason) {
+ for (DeviceCallback callback : getCallbacks()) {
+ callback.onRequestFailed(reason);
+ }
+ }
+
/**
* Stop scan MediaDevice
*/
@@ -337,7 +336,7 @@
MediaDevice phoneMediaDevice = null;
for (MediaDevice device : mMediaDevices) {
if (device instanceof BluetoothMediaDevice) {
- if (isConnected(((BluetoothMediaDevice) device).getCachedDevice())) {
+ if (isActiveDevice(((BluetoothMediaDevice) device).getCachedDevice())) {
return device;
}
} else if (device instanceof PhoneMediaDevice) {
@@ -347,7 +346,7 @@
return mMediaDevices.contains(phoneMediaDevice) ? phoneMediaDevice : null;
}
- private boolean isConnected(CachedBluetoothDevice device) {
+ private boolean isActiveDevice(CachedBluetoothDevice device) {
return device.isActiveDevice(BluetoothProfile.A2DP)
|| device.isActiveDevice(BluetoothProfile.HEARING_AID);
}
@@ -423,20 +422,34 @@
@Override
public void onConnectedDeviceChanged(String id) {
- final MediaDevice connectDevice = getMediaDeviceById(mMediaDevices, id);
+ MediaDevice connectDevice = getMediaDeviceById(mMediaDevices, id);
+ connectDevice = connectDevice != null
+ ? connectDevice : updateCurrentConnectedDevice();
+ connectDevice.setState(MediaDeviceState.STATE_CONNECTED);
if (connectDevice == mCurrentConnectedDevice) {
Log.d(TAG, "onConnectedDeviceChanged() this device all ready connected!");
return;
}
mCurrentConnectedDevice = connectDevice;
- dispatchDeviceAttributesChanged();
+ dispatchSelectedDeviceStateChanged(mCurrentConnectedDevice,
+ MediaDeviceState.STATE_CONNECTED);
}
@Override
public void onDeviceAttributesChanged() {
dispatchDeviceAttributesChanged();
}
+
+ @Override
+ public void onRequestFailed(int reason) {
+ for (MediaDevice device : mMediaDevices) {
+ if (device.getState() == MediaDeviceState.STATE_CONNECTING) {
+ device.setState(MediaDeviceState.STATE_CONNECTING_FAILED);
+ }
+ }
+ dispatchOnRequestFailed(reason);
+ }
}
@@ -467,6 +480,18 @@
* Callback for notifying the device attributes is changed.
*/
default void onDeviceAttributesChanged() {};
+
+ /**
+ * Callback for notifying that transferring is failed.
+ *
+ * @param reason the reason that the request has failed. Can be one of followings:
+ * {@link android.media.MediaRoute2ProviderService#REASON_UNKNOWN_ERROR},
+ * {@link android.media.MediaRoute2ProviderService#REASON_REJECTED},
+ * {@link android.media.MediaRoute2ProviderService#REASON_NETWORK_ERROR},
+ * {@link android.media.MediaRoute2ProviderService#REASON_ROUTE_NOT_AVAILABLE},
+ * {@link android.media.MediaRoute2ProviderService#REASON_INVALID_COMMAND},
+ */
+ default void onRequestFailed(int reason){};
}
/**
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java b/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java
index 33c3d7e..39e6a12 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/MediaDevice.java
@@ -51,6 +51,7 @@
int mType;
private int mConnectedRecord;
+ private int mState;
protected final Context mContext;
protected final MediaRoute2Info mRouteInfo;
@@ -200,6 +201,22 @@
}
/**
+ * Set current device's state
+ */
+ public void setState(@LocalMediaManager.MediaDeviceState int state) {
+ mState = state;
+ }
+
+ /**
+ * Get current device's state
+ *
+ * @return state of device
+ */
+ public @LocalMediaManager.MediaDeviceState int getState() {
+ return mState;
+ }
+
+ /**
* Rules:
* 1. If there is one of the connected devices identified as a carkit, this carkit will
* be always on the top of the device list. Rule 2 and Rule 3 can’t overrule this rule.
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
index 73551f6..e8cbab8 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
@@ -110,6 +110,12 @@
}
}
+ protected void dispatchOnRequestFailed(int reason) {
+ for (MediaDeviceCallback callback : getCallbacks()) {
+ callback.onRequestFailed(reason);
+ }
+ }
+
private Collection<MediaDeviceCallback> getCallbacks() {
return new CopyOnWriteArrayList<>(mCallbacks);
}
@@ -158,5 +164,17 @@
* (e.g: device name, connection state, subtitle) is changed.
*/
void onDeviceAttributesChanged();
+
+ /**
+ * Callback for notifying that transferring is failed.
+ *
+ * @param reason the reason that the request has failed. Can be one of followings:
+ * {@link android.media.MediaRoute2ProviderService#REASON_UNKNOWN_ERROR},
+ * {@link android.media.MediaRoute2ProviderService#REASON_REJECTED},
+ * {@link android.media.MediaRoute2ProviderService#REASON_NETWORK_ERROR},
+ * {@link android.media.MediaRoute2ProviderService#REASON_ROUTE_NOT_AVAILABLE},
+ * {@link android.media.MediaRoute2ProviderService#REASON_INVALID_COMMAND},
+ */
+ void onRequestFailed(int reason);
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java
index 4ebb102..6a7000e 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiEntryPreference.java
@@ -43,10 +43,6 @@
R.attr.state_encrypted
};
- private static final int[] STATE_METERED = {
- R.attr.state_metered
- };
-
private static final int[] FRICTION_ATTRS = {
R.attr.wifi_friction
};
@@ -201,8 +197,6 @@
if ((mWifiEntry.getSecurity() != WifiEntry.SECURITY_NONE)
&& (mWifiEntry.getSecurity() != WifiEntry.SECURITY_OWE)) {
mFrictionSld.setState(STATE_SECURED);
- } else if (mWifiEntry.isMetered()) {
- mFrictionSld.setState(STATE_METERED);
}
frictionImageView.setImageDrawable(mFrictionSld.getCurrent());
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAccessesTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAccessesTest.java
index 68a3729..245b7843 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAccessesTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAccessesTest.java
@@ -8,7 +8,6 @@
import android.app.AppOpsManager;
import android.app.AppOpsManager.OpEntry;
-import android.app.AppOpsManager.OpFeatureEntry;
import android.app.AppOpsManager.PackageOps;
import android.content.Context;
import android.content.pm.ApplicationInfo;
@@ -163,6 +162,6 @@
AppOpsManager.OP_FLAG_SELF), new AppOpsManager.NoteOpEvent(time, -1, null));
return new OpEntry(op, AppOpsManager.MODE_ALLOWED, Collections.singletonMap(null,
- new OpFeatureEntry(op, false, accessEvents, null)));
+ new AppOpsManager.AttributedOpEntry(op, false, accessEvents, null)));
}
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAppsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAppsTest.java
index 3f8d758..cc9b931 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAppsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/location/RecentLocationAppsTest.java
@@ -7,7 +7,7 @@
import android.app.AppOpsManager;
import android.app.AppOpsManager.OpEntry;
-import android.app.AppOpsManager.OpFeatureEntry;
+import android.app.AppOpsManager.AttributedOpEntry;
import android.app.AppOpsManager.PackageOps;
import android.content.Context;
import android.content.pm.ApplicationInfo;
@@ -18,8 +18,6 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.util.LongSparseArray;
-import android.util.LongSparseLongArray;
-import android.util.Pair;
import org.junit.Before;
import org.junit.Test;
@@ -164,6 +162,6 @@
AppOpsManager.OP_FLAG_SELF), new AppOpsManager.NoteOpEvent(time, duration, null));
return new OpEntry(op, AppOpsManager.MODE_ALLOWED, Collections.singletonMap(null,
- new OpFeatureEntry(op, false, accessEvents, null)));
+ new AttributedOpEntry(op, false, accessEvents, null)));
}
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java
index 7cd0a7c..7f93f69 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java
@@ -16,6 +16,9 @@
package com.android.settingslib.media;
+import static android.media.MediaRoute2ProviderService.REASON_NETWORK_ERROR;
+import static android.media.MediaRoute2ProviderService.REASON_UNKNOWN_ERROR;
+
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
@@ -54,6 +57,8 @@
private MediaRouter2Manager mRouterManager;
@Mock
private LocalBluetoothManager mLocalBluetoothManager;
+ @Mock
+ private MediaManager.MediaDeviceCallback mCallback;
private InfoMediaManager mInfoMediaManager;
private Context mContext;
@@ -144,6 +149,8 @@
@Test
public void onRoutesChanged_getAvailableRoutes_shouldAddMediaDevice() {
final MediaRoute2Info info = mock(MediaRoute2Info.class);
+ mInfoMediaManager.registerCallback(mCallback);
+
when(info.getId()).thenReturn(TEST_ID);
when(info.getClientPackageName()).thenReturn(TEST_PACKAGE_NAME);
@@ -160,11 +167,14 @@
assertThat(infoDevice.getId()).isEqualTo(TEST_ID);
assertThat(mInfoMediaManager.getCurrentConnectedDevice()).isEqualTo(infoDevice);
assertThat(mInfoMediaManager.mMediaDevices).hasSize(routes.size());
+ verify(mCallback).onConnectedDeviceChanged(TEST_ID);
}
@Test
public void onRoutesChanged_buildAllRoutes_shouldAddMediaDevice() {
final MediaRoute2Info info = mock(MediaRoute2Info.class);
+ mInfoMediaManager.registerCallback(mCallback);
+
when(info.getId()).thenReturn(TEST_ID);
when(info.getClientPackageName()).thenReturn(TEST_PACKAGE_NAME);
when(info.isSystemRoute()).thenReturn(true);
@@ -182,6 +192,7 @@
final MediaDevice infoDevice = mInfoMediaManager.mMediaDevices.get(0);
assertThat(infoDevice.getId()).isEqualTo(TEST_ID);
assertThat(mInfoMediaManager.mMediaDevices).hasSize(routes.size());
+ verify(mCallback).onConnectedDeviceChanged(null);
}
@Test
@@ -493,4 +504,22 @@
assertThat(mInfoMediaManager.getSessionName()).isEqualTo(TEST_NAME);
}
+
+ @Test
+ public void onTransferFailed_shouldDispatchOnRequestFailed() {
+ mInfoMediaManager.registerCallback(mCallback);
+
+ mInfoMediaManager.mMediaRouterCallback.onTransferFailed(null, null);
+
+ verify(mCallback).onRequestFailed(REASON_UNKNOWN_ERROR);
+ }
+
+ @Test
+ public void onRequestFailed_shouldDispatchOnRequestFailed() {
+ mInfoMediaManager.registerCallback(mCallback);
+
+ mInfoMediaManager.mMediaRouterCallback.onRequestFailed(REASON_NETWORK_ERROR);
+
+ verify(mCallback).onRequestFailed(REASON_NETWORK_ERROR);
+ }
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/LocalMediaManagerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/LocalMediaManagerTest.java
index 3611dfe..f825ec5 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/LocalMediaManagerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/LocalMediaManagerTest.java
@@ -16,10 +16,11 @@
package com.android.settingslib.media;
+import static android.media.MediaRoute2ProviderService.REASON_UNKNOWN_ERROR;
+
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -28,6 +29,8 @@
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
+import android.media.MediaRoute2Info;
+import android.media.MediaRouter2Manager;
import com.android.settingslib.bluetooth.A2dpProfile;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
@@ -54,10 +57,13 @@
@Config(shadows = {ShadowBluetoothAdapter.class})
public class LocalMediaManagerTest {
+ private static final String TEST_DEVICE_NAME_1 = "device_name_1";
+ private static final String TEST_DEVICE_NAME_2 = "device_name_2";
private static final String TEST_DEVICE_ID_1 = "device_id_1";
private static final String TEST_DEVICE_ID_2 = "device_id_2";
private static final String TEST_DEVICE_ID_3 = "device_id_3";
private static final String TEST_CURRENT_DEVICE_ID = "currentDevice_id";
+ private static final String TEST_PACKAGE_NAME = "com.test.playmusic";
@Mock
private BluetoothMediaManager mBluetoothMediaManager;
@@ -73,10 +79,18 @@
private A2dpProfile mA2dpProfile;
@Mock
private LocalBluetoothProfileManager mLocalProfileManager;
+ @Mock
+ private MediaRouter2Manager mMediaRouter2Manager;
+ @Mock
+ private MediaRoute2Info mRouteInfo1;
+ @Mock
+ private MediaRoute2Info mRouteInfo2;
private Context mContext;
private LocalMediaManager mLocalMediaManager;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
+ private InfoMediaDevice mInfoMediaDevice1;
+ private InfoMediaDevice mInfoMediaDevice2;
@Before
public void setUp() {
@@ -85,11 +99,18 @@
final List<BluetoothDevice> bluetoothDevices = new ArrayList<>();
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setMostRecentlyConnectedDevices(bluetoothDevices);
-
+ when(mRouteInfo1.getName()).thenReturn(TEST_DEVICE_NAME_1);
+ when(mRouteInfo1.getId()).thenReturn(TEST_DEVICE_ID_1);
+ when(mRouteInfo2.getName()).thenReturn(TEST_DEVICE_NAME_2);
+ when(mRouteInfo2.getId()).thenReturn(TEST_DEVICE_ID_2);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mLocalProfileManager);
when(mLocalProfileManager.getA2dpProfile()).thenReturn(mA2dpProfile);
when(mLocalProfileManager.getHearingAidProfile()).thenReturn(mHapProfile);
+ mInfoMediaDevice1 = new InfoMediaDevice(mContext, mMediaRouter2Manager, mRouteInfo1,
+ TEST_PACKAGE_NAME);
+ mInfoMediaDevice2 = new InfoMediaDevice(mContext, mMediaRouter2Manager, mRouteInfo2,
+ TEST_PACKAGE_NAME);
mLocalMediaManager = new LocalMediaManager(mContext, mLocalBluetoothManager,
mInfoMediaManager, "com.test.packagename");
mLocalMediaManager.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -121,8 +142,32 @@
verify(currentDevice).disconnect();
verify(device).connect();
- verify(mCallback).onSelectedDeviceStateChanged(any(),
- eq(LocalMediaManager.MediaDeviceState.STATE_DISCONNECTED));
+ }
+
+ @Test
+ public void connectDevice_deviceNotEqualCurrentConnectedDevice_isConnectingState() {
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice1);
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice2);
+ mLocalMediaManager.mCurrentConnectedDevice = mInfoMediaDevice1;
+
+ mLocalMediaManager.registerCallback(mCallback);
+ mLocalMediaManager.connectDevice(mInfoMediaDevice2);
+
+ assertThat(mInfoMediaDevice2.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTING);
+ }
+
+ @Test
+ public void connectDevice_deviceEqualCurrentConnectedDevice_notConnectingState() {
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice1);
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice2);
+ mLocalMediaManager.mCurrentConnectedDevice = mInfoMediaDevice1;
+
+ mLocalMediaManager.registerCallback(mCallback);
+ mLocalMediaManager.connectDevice(mInfoMediaDevice1);
+
+ assertThat(mInfoMediaDevice1.getState()).isNotEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTING);
}
@Test
@@ -368,7 +413,8 @@
mLocalMediaManager.mMediaDeviceCallback.onConnectedDeviceChanged(TEST_DEVICE_ID_2);
assertThat(mLocalMediaManager.getCurrentConnectedDevice()).isEqualTo(device2);
- verify(mCallback).onDeviceAttributesChanged();
+ verify(mCallback).onSelectedDeviceStateChanged(device2,
+ LocalMediaManager.MediaDeviceState.STATE_CONNECTED);
}
@Test
@@ -390,6 +436,21 @@
}
@Test
+ public void onConnectedDeviceChanged_isConnectedState() {
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice1);
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice2);
+ mInfoMediaDevice1.setState(LocalMediaManager.MediaDeviceState.STATE_DISCONNECTED);
+
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_DISCONNECTED);
+ mLocalMediaManager.registerCallback(mCallback);
+ mLocalMediaManager.mMediaDeviceCallback.onConnectedDeviceChanged(TEST_DEVICE_ID_1);
+
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTED);
+ }
+
+ @Test
public void onDeviceAttributesChanged_shouldDispatchDeviceListUpdate() {
mLocalMediaManager.registerCallback(mCallback);
@@ -399,6 +460,26 @@
}
@Test
+ public void onRequestFailed_checkDevicesState() {
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice1);
+ mLocalMediaManager.mMediaDevices.add(mInfoMediaDevice2);
+ mInfoMediaDevice1.setState(LocalMediaManager.MediaDeviceState.STATE_CONNECTING);
+ mInfoMediaDevice2.setState(LocalMediaManager.MediaDeviceState.STATE_CONNECTED);
+
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTING);
+ assertThat(mInfoMediaDevice2.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTED);
+ mLocalMediaManager.registerCallback(mCallback);
+ mLocalMediaManager.mMediaDeviceCallback.onRequestFailed(REASON_UNKNOWN_ERROR);
+
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTING_FAILED);
+ assertThat(mInfoMediaDevice2.getState()).isEqualTo(LocalMediaManager.MediaDeviceState
+ .STATE_CONNECTED);
+ }
+
+ @Test
public void getActiveMediaDevice_checkList() {
final List<MediaDevice> devices = new ArrayList<>();
final MediaDevice device1 = mock(MediaDevice.class);
@@ -477,4 +558,13 @@
assertThat(mLocalMediaManager.mMediaDevices).hasSize(3);
verify(mCallback).onDeviceListUpdate(any());
}
+
+ @Test
+ public void onRequestFailed_shouldDispatchOnRequestFailed() {
+ mLocalMediaManager.registerCallback(mCallback);
+
+ mLocalMediaManager.mMediaDeviceCallback.onRequestFailed(1);
+
+ verify(mCallback).onRequestFailed(1);
+ }
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaDeviceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaDeviceTest.java
index 3f29b72..4b08387 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaDeviceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaDeviceTest.java
@@ -448,4 +448,23 @@
assertThat(mInfoMediaDevice1.getClientAppLabel()).isEqualTo(
mContext.getResources().getString(R.string.unknown));
}
+
+ @Test
+ public void setState_verifyGetState() {
+ mInfoMediaDevice1.setState(LocalMediaManager.MediaDeviceState.STATE_CONNECTED);
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(
+ LocalMediaManager.MediaDeviceState.STATE_CONNECTED);
+
+ mInfoMediaDevice1.setState(LocalMediaManager.MediaDeviceState.STATE_CONNECTING);
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(
+ LocalMediaManager.MediaDeviceState.STATE_CONNECTING);
+
+ mInfoMediaDevice1.setState(LocalMediaManager.MediaDeviceState.STATE_DISCONNECTED);
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(
+ LocalMediaManager.MediaDeviceState.STATE_DISCONNECTED);
+
+ mInfoMediaDevice1.setState(LocalMediaManager.MediaDeviceState.STATE_CONNECTING_FAILED);
+ assertThat(mInfoMediaDevice1.getState()).isEqualTo(
+ LocalMediaManager.MediaDeviceState.STATE_CONNECTING_FAILED);
+ }
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
index ead2be4..a50965a 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
@@ -136,4 +136,14 @@
assertThat(device).isNull();
}
+
+ @Test
+ public void dispatchOnRequestFailed_registerCallback_shouldDispatchCallback() {
+ mMediaManager.registerCallback(mCallback);
+
+ mMediaManager.dispatchOnRequestFailed(1);
+
+ verify(mCallback).onRequestFailed(1);
+ }
+
}
diff --git a/packages/SettingsProvider/res/values-ta/strings.xml b/packages/SettingsProvider/res/values-ta/strings.xml
index fa6b8cd..54d2242 100644
--- a/packages/SettingsProvider/res/values-ta/strings.xml
+++ b/packages/SettingsProvider/res/values-ta/strings.xml
@@ -20,8 +20,6 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_label" msgid="4567566098528588863">"அமைப்புகளின் சேமிப்பிடம்"</string>
- <!-- no translation found for wifi_softap_config_change (5688373762357941645) -->
- <skip />
- <!-- no translation found for wifi_softap_config_change_summary (8946397286141531087) -->
- <skip />
+ <string name="wifi_softap_config_change" msgid="5688373762357941645">"ஹாட்ஸ்பாட் அமைப்புகள் மாற்றப்பட்டன"</string>
+ <string name="wifi_softap_config_change_summary" msgid="8946397286141531087">"விவரங்களைப் பார்க்க, தட்டவும்"</string>
</resources>
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
index 8fa98c8..d350d9d 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
@@ -141,6 +141,8 @@
Settings.Secure.NOTIFICATION_NEW_INTERRUPTION_MODEL,
Settings.Secure.TRUST_AGENTS_EXTEND_UNLOCK,
Settings.Secure.UI_NIGHT_MODE,
+ Settings.Secure.DARK_THEME_CUSTOM_START_TIME,
+ Settings.Secure.DARK_THEME_CUSTOM_END_TIME,
Settings.Secure.LOCK_SCREEN_WHEN_TRUST_LOST,
Settings.Secure.SKIP_DIRECTION,
Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES,
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
index 75c5f95..4d33b62 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
@@ -28,6 +28,7 @@
import static android.provider.settings.validators.SettingsValidators.NON_NEGATIVE_INTEGER_VALIDATOR;
import static android.provider.settings.validators.SettingsValidators.NULLABLE_COMPONENT_NAME_VALIDATOR;
import static android.provider.settings.validators.SettingsValidators.PACKAGE_NAME_VALIDATOR;
+import static android.provider.settings.validators.SettingsValidators.NONE_NEGATIVE_LONG_VALIDATOR;
import static android.provider.settings.validators.SettingsValidators.TILE_LIST_VALIDATOR;
import static android.provider.settings.validators.SettingsValidators.TTS_LIST_VALIDATOR;
@@ -235,7 +236,9 @@
VALIDATORS.put(Secure.AWARE_TAP_PAUSE_TOUCH_COUNT, NON_NEGATIVE_INTEGER_VALIDATOR);
VALIDATORS.put(Secure.ODI_CAPTIONS_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.DARK_MODE_DIALOG_SEEN, BOOLEAN_VALIDATOR);
- VALIDATORS.put(Secure.UI_NIGHT_MODE, new InclusiveIntegerRangeValidator(0, 2));
+ VALIDATORS.put(Secure.UI_NIGHT_MODE, NON_NEGATIVE_INTEGER_VALIDATOR);
+ VALIDATORS.put(Secure.DARK_THEME_CUSTOM_START_TIME, NONE_NEGATIVE_LONG_VALIDATOR);
+ VALIDATORS.put(Secure.DARK_THEME_CUSTOM_END_TIME, NONE_NEGATIVE_LONG_VALIDATOR);
VALIDATORS.put(Secure.GLOBAL_ACTIONS_PANEL_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.AWARE_LOCK_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(Secure.DISPLAY_DENSITY_FORCED, NON_NEGATIVE_INTEGER_VALIDATOR);
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SettingsValidators.java
index 71c7544..8d5c6e6 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SettingsValidators.java
@@ -207,4 +207,15 @@
static final Validator ACCESSIBILITY_SHORTCUT_TARGET_LIST_VALIDATOR =
new AccessibilityShortcutTargetListValidator();
+
+ static final Validator NONE_NEGATIVE_LONG_VALIDATOR = new Validator() {
+ @Override
+ public boolean validate(String value) {
+ try {
+ return Long.parseLong(value) >= 0;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+ };
}
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
index 36bb8ef..b6e31d2 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
@@ -75,6 +75,9 @@
sBroadcastOnRestore.add(Settings.Secure.ENABLED_VR_LISTENERS);
sBroadcastOnRestore.add(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
sBroadcastOnRestore.add(Settings.Global.BLUETOOTH_ON);
+ sBroadcastOnRestore.add(Settings.Secure.UI_NIGHT_MODE);
+ sBroadcastOnRestore.add(Settings.Secure.DARK_THEME_CUSTOM_START_TIME);
+ sBroadcastOnRestore.add(Settings.Secure.DARK_THEME_CUSTOM_END_TIME);
}
private interface SettingsLookup {
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index 8789a5c..af74121 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -52,6 +52,8 @@
ConfigSettingsProto.APP_COMPAT_SETTINGS);
namespaceToFieldMap.put(DeviceConfig.NAMESPACE_AUTOFILL,
ConfigSettingsProto.AUTOFILL_SETTINGS);
+ namespaceToFieldMap.put(DeviceConfig.NAMESPACE_BLOBSTORE,
+ ConfigSettingsProto.BLOBSTORE_SETTINGS);
namespaceToFieldMap.put(DeviceConfig.NAMESPACE_CONNECTIVITY,
ConfigSettingsProto.CONNECTIVITY_SETTINGS);
namespaceToFieldMap.put(DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 2dc6f39..5a9d749 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -2778,6 +2778,11 @@
public boolean insertSettingLocked(int type, int userId, String name, String value,
String tag, boolean makeDefault, boolean forceNonSystemPackage, String packageName,
boolean forceNotify, Set<String> criticalSettings, boolean overrideableByRestore) {
+ if (overrideableByRestore != Settings.DEFAULT_OVERRIDEABLE_BY_RESTORE) {
+ getContext().enforceCallingOrSelfPermission(
+ Manifest.permission.MODIFY_SETTINGS_OVERRIDEABLE_BY_RESTORE,
+ "Caller is not allowed to modify settings overrideable by restore");
+ }
final int key = makeKey(type, userId);
boolean success = false;
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
index cd62420..2d351c7 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java
@@ -1259,7 +1259,8 @@
public boolean reset() {
// overrideableByRestore = true as resetting to default value isn't considered a
// modification.
- return update(this.defaultValue, false, packageName, null, true, true);
+ return update(this.defaultValue, false, packageName, null, true, true,
+ /* resetToDefault */ true);
}
public boolean isTransient() {
@@ -1272,6 +1273,13 @@
public boolean update(String value, boolean setDefault, String packageName, String tag,
boolean forceNonSystemPackage, boolean overrideableByRestore) {
+ return update(value, setDefault, packageName, tag, forceNonSystemPackage,
+ overrideableByRestore, /* resetToDefault */ false);
+ }
+
+ private boolean update(String value, boolean setDefault, String packageName, String tag,
+ boolean forceNonSystemPackage, boolean overrideableByRestore,
+ boolean resetToDefault) {
if (NULL_VALUE.equals(value)) {
value = null;
}
@@ -1305,7 +1313,7 @@
}
// isValuePreservedInRestore shouldn't change back to false if it has been set to true.
- boolean isPreserved = this.isValuePreservedInRestore || !overrideableByRestore;
+ boolean isPreserved = shouldPreserveSetting(overrideableByRestore, resetToDefault);
// Is something gonna change?
if (Objects.equals(value, this.value)
@@ -1329,6 +1337,17 @@
+ " packageName=" + packageName + " tag=" + tag
+ " defaultFromSystem=" + defaultFromSystem + "}";
}
+
+ private boolean shouldPreserveSetting(boolean overrideableByRestore,
+ boolean resetToDefault) {
+ if (resetToDefault) {
+ // By default settings are not marked as preserved.
+ return false;
+ }
+
+ // isValuePreservedInRestore shouldn't change back to false if it has been set to true.
+ return this.isValuePreservedInRestore || !overrideableByRestore;
+ }
}
/**
diff --git a/packages/SettingsProvider/test/src/android/provider/settings/validators/SettingsValidatorsTest.java b/packages/SettingsProvider/test/src/android/provider/settings/validators/SettingsValidatorsTest.java
index bb9e6f6..9134d87 100644
--- a/packages/SettingsProvider/test/src/android/provider/settings/validators/SettingsValidatorsTest.java
+++ b/packages/SettingsProvider/test/src/android/provider/settings/validators/SettingsValidatorsTest.java
@@ -277,6 +277,27 @@
}
@Test
+ public void testPositiveLongValidator_zero() {
+ assertTrue(SettingsValidators.NONE_NEGATIVE_LONG_VALIDATOR.validate("0"));
+ }
+
+ @Test
+ public void testPositiveLongValidator_negative() {
+ assertFalse(SettingsValidators.NONE_NEGATIVE_LONG_VALIDATOR.validate("-5"));
+ }
+
+
+ @Test
+ public void testPositiveLongValidator_positive() {
+ assertTrue(SettingsValidators.NONE_NEGATIVE_LONG_VALIDATOR.validate("5"));
+ }
+
+ @Test
+ public void testPositiveLongValidator_floatFormat() {
+ assertFalse(SettingsValidators.NONE_NEGATIVE_LONG_VALIDATOR.validate("4.4756"));
+ }
+
+ @Test
public void testTTSListValidator_withNullInput_returnsFalse() {
assertFalse(SettingsValidators.TTS_LIST_VALIDATOR.validate(null));
}
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 b855d87..6a3c661 100644
--- a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
+++ b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsStateTest.java
@@ -241,6 +241,18 @@
assertTrue(settingsReader.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
}
+ public void testResetSetting_preservedFlagIsReset() {
+ SettingsState settingsState = getSettingStateObject();
+ // Initialize the setting.
+ settingsState.insertSettingLocked(SETTING_NAME, "1", null, false, TEST_PACKAGE);
+ // Update the setting so that preserved flag is set.
+ settingsState.insertSettingLocked(SETTING_NAME, "2", null, false, TEST_PACKAGE);
+
+ settingsState.resetSettingLocked(SETTING_NAME);
+ assertFalse(settingsState.getSettingLocked(SETTING_NAME).isValuePreservedInRestore());
+
+ }
+
private SettingsState getSettingStateObject() {
SettingsState settingsState = new SettingsState(getContext(), mLock, mSettingsFile, 1,
SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED, Looper.getMainLooper());
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index e13e49f..8f859b2 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -204,7 +204,6 @@
<!-- Permission needed to run network tests in CTS -->
<uses-permission android:name="android.permission.MANAGE_TEST_NETWORKS" />
- <uses-permission android:name="android.permission.NETWORK_STACK" />
<!-- Permission needed to test tcp keepalive offload. -->
<uses-permission android:name="android.permission.PACKET_KEEPALIVE_OFFLOAD" />
@@ -276,6 +275,9 @@
<!-- Permission needed to test registering pull atom callbacks -->
<uses-permission android:name="android.permission.REGISTER_STATS_PULL_ATOM" />
+ <!-- Permission needed to modify settings overrideable by restore in CTS tests -->
+ <uses-permission android:name="android.permission.MODIFY_SETTINGS_OVERRIDEABLE_BY_RESTORE" />
+
<application android:label="@string/app_label"
android:theme="@android:style/Theme.DeviceDefault.DayNight"
android:defaultToDeviceProtectedStorage="true"
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index e066230..0eadcc7 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -46,6 +46,7 @@
"SystemUIPluginLib",
"SystemUISharedLib",
"SettingsLib",
+ "androidx.viewpager2_viewpager2",
"androidx.legacy_legacy-support-v4",
"androidx.recyclerview_recyclerview",
"androidx.preference_preference",
@@ -106,6 +107,7 @@
"SystemUIPluginLib",
"SystemUISharedLib",
"SettingsLib",
+ "androidx.viewpager2_viewpager2",
"androidx.legacy_legacy-support-v4",
"androidx.recyclerview_recyclerview",
"androidx.preference_preference",
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 617ed4e..da93db7 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -147,6 +147,7 @@
<uses-permission android:name="android.permission.CONFIGURE_WIFI_DISPLAY" />
<uses-permission android:name="android.permission.CAMERA" />
+ <uses-permission android:name="android.permission.CAMERA_OPEN_CLOSE_LISTENER" />
<!-- Screen Capturing -->
<uses-permission android:name="android.permission.MANAGE_MEDIA_PROJECTION" />
@@ -180,6 +181,8 @@
<!-- Adding Controls to SystemUI -->
<uses-permission android:name="android.permission.BIND_CONTROLS" />
+ <!-- Check foreground controls applications -->
+ <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
<!-- Quick Settings tile: Night Mode / Dark Theme -->
<uses-permission android:name="android.permission.MODIFY_DAY_NIGHT_MODE" />
@@ -686,6 +689,25 @@
android:visibleToInstantApps="true">
</activity>
+ <receiver android:name=".controls.management.ControlsRequestReceiver">
+ <intent-filter>
+ <action android:name="android.service.controls.action.ADD_CONTROL" />
+ </intent-filter>
+ </receiver>
+
+ <!-- started from ControlsFavoritingActivity -->
+ <activity
+ android:name=".controls.management.ControlsRequestDialog"
+ android:exported="true"
+ android:theme="@style/Theme.ControlsRequestDialog"
+ android:finishOnCloseSystemDialogs="true"
+ android:showForAllUsers="true"
+ android:clearTaskOnLaunch="true"
+ android:launchMode="singleTask"
+ android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation|keyboard|keyboardHidden"
+ android:excludeFromRecents="true"
+ android:visibleToInstantApps="true"/>
+
<!-- Doze with notifications, run in main sysui process for every user -->
<service
android:name=".doze.DozeService"
diff --git a/packages/SystemUI/TEST_MAPPING b/packages/SystemUI/TEST_MAPPING
index cff958f..c036b04 100644
--- a/packages/SystemUI/TEST_MAPPING
+++ b/packages/SystemUI/TEST_MAPPING
@@ -12,6 +12,9 @@
"include-annotation": "android.platform.test.scenario.annotation.Scenario"
},
{
+ "exclude-annotation": "org.junit.Ignore"
+ },
+ {
"exclude-annotation": "androidx.test.filters.FlakyTest"
}
]
@@ -28,6 +31,9 @@
"include-annotation": "android.platform.test.scenario.annotation.Scenario"
},
{
+ "exclude-annotation": "org.junit.Ignore"
+ },
+ {
"exclude-annotation": "androidx.test.filters.FlakyTest"
},
{
diff --git a/packages/SystemUI/res/color/control_background.xml b/packages/SystemUI/res/color/control_background.xml
deleted file mode 100644
index 977310c..0000000
--- a/packages/SystemUI/res/color/control_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_enabled="false"
- android:color="@color/control_default_background" />
- <item android:color="@color/GM2_blue_200"
- android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/color/light_background.xml b/packages/SystemUI/res/color/light_background.xml
deleted file mode 100644
index 1299464..0000000
--- a/packages/SystemUI/res/color/light_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_enabled="false"
- android:color="@color/control_default_background" />
- <item android:color="@color/GM2_yellow_200"
- android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/color/thermo_cool_background.xml b/packages/SystemUI/res/color/thermo_cool_background.xml
deleted file mode 100644
index 977310c..0000000
--- a/packages/SystemUI/res/color/thermo_cool_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_enabled="false"
- android:color="@color/control_default_background" />
- <item android:color="@color/GM2_blue_200"
- android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/color/thermo_heat_background.xml b/packages/SystemUI/res/color/thermo_heat_background.xml
deleted file mode 100644
index 2709ebe..0000000
--- a/packages/SystemUI/res/color/thermo_heat_background.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_enabled="false"
- android:color="@color/control_default_background" />
- <item android:color="@color/GM2_red_200"
- android:alpha="0.2" />
-</selector>
diff --git a/packages/SystemUI/res/drawable/dismiss_circle_background.xml b/packages/SystemUI/res/drawable/dismiss_circle_background.xml
new file mode 100644
index 0000000..e311c52
--- /dev/null
+++ b/packages/SystemUI/res/drawable/dismiss_circle_background.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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.
+ -->
+
+<shape
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="oval">
+
+ <stroke
+ android:width="1dp"
+ android:color="#66FFFFFF" />
+
+ <solid android:color="#B3000000" />
+
+</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/dismiss_target_x.xml b/packages/SystemUI/res/drawable/dismiss_target_x.xml
new file mode 100644
index 0000000..3672eff
--- /dev/null
+++ b/packages/SystemUI/res/drawable/dismiss_target_x.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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.
+ -->
+
+<!-- 'X' icon. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24.0dp"
+ android:height="24.0dp"
+ android:viewportWidth="24.0"
+ android:viewportHeight="24.0">
+ <path
+ android:pathData="M19.000000,6.400000l-1.400000,-1.400000 -5.600000,5.600000 -5.600000,-5.600000 -1.400000,1.400000 5.600000,5.600000 -5.600000,5.600000 1.400000,1.400000 5.600000,-5.600000 5.600000,5.600000 1.400000,-1.400000 -5.600000,-5.600000z"
+ android:fillColor="#FFFFFFFF"
+ android:strokeColor="#FF000000"/>
+</vector>
\ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_bubble_overflow_button.xml b/packages/SystemUI/res/drawable/ic_bubble_overflow_button.xml
index 64b57c5..3acebc1 100644
--- a/packages/SystemUI/res/drawable/ic_bubble_overflow_button.xml
+++ b/packages/SystemUI/res/drawable/ic_bubble_overflow_button.xml
@@ -14,10 +14,11 @@
limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:viewportHeight="24"
- android:viewportWidth="24"
- android:height="52dp"
- android:width="52dp">
- <path android:fillColor="#1A73E8"
- android:pathData="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/>
-</vector>
\ No newline at end of file
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:width="24dp"
+ android:height="24dp">
+ <path
+ android:fillColor="#1A73E8"
+ android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
+</vector>
diff --git a/packages/SystemUI/res/layout-land-television/volume_dialog.xml b/packages/SystemUI/res/layout-land-television/volume_dialog.xml
new file mode 100644
index 0000000..e0d158d
--- /dev/null
+++ b/packages/SystemUI/res/layout-land-television/volume_dialog.xml
@@ -0,0 +1,101 @@
+<!--
+ ~ Copyright (C) 2020 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
+ -->
+<FrameLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:sysui="http://schemas.android.com/apk/res-auto"
+ android:id="@+id/volume_dialog_container"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:background="@android:color/transparent"
+ android:theme="@style/qs_theme">
+
+ <FrameLayout
+ android:id="@+id/volume_dialog"
+ android:minWidth="@dimen/volume_dialog_panel_width"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="right"
+ android:background="@android:color/transparent"
+ android:paddingRight="@dimen/volume_dialog_panel_transparent_padding_right"
+ android:paddingTop="@dimen/volume_dialog_panel_transparent_padding"
+ android:paddingBottom="@dimen/volume_dialog_panel_transparent_padding"
+ android:paddingLeft="@dimen/volume_dialog_panel_transparent_padding"
+ android:clipToPadding="false">
+
+ <LinearLayout
+ android:id="@+id/main"
+ android:layout_width="wrap_content"
+ android:minWidth="@dimen/volume_dialog_panel_width"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="68dp"
+ android:layout_gravity="right"
+ android:orientation="vertical"
+ android:translationZ="@dimen/volume_dialog_elevation"
+ android:clipChildren="false"
+ android:clipToPadding="false"
+ android:background="@drawable/rounded_bg_full">
+
+ <LinearLayout
+ android:id="@+id/volume_dialog_rows"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:minWidth="@dimen/volume_dialog_panel_width"
+ android:gravity="center"
+ android:orientation="horizontal"
+ android:paddingRight="@dimen/volume_dialog_stream_padding"
+ android:paddingLeft="@dimen/volume_dialog_stream_padding">
+ <!-- volume rows added and removed here! :-) -->
+ </LinearLayout>
+
+ </LinearLayout>
+
+ <FrameLayout
+ android:id="@+id/odi_captions"
+ android:layout_width="@dimen/volume_dialog_caption_size"
+ android:layout_height="@dimen/volume_dialog_caption_size"
+ android:layout_marginRight="68dp"
+ android:layout_gravity="right"
+ android:clipToPadding="false"
+ android:translationZ="@dimen/volume_dialog_elevation"
+ android:background="@drawable/rounded_bg_full">
+
+ <com.android.systemui.volume.CaptionsToggleImageButton
+ android:id="@+id/odi_captions_icon"
+ android:src="@drawable/ic_volume_odi_captions_disabled"
+ style="@style/VolumeButtons"
+ android:background="@drawable/rounded_ripple"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:tint="@color/caption_tint_color_selector"
+ android:layout_gravity="center"
+ android:soundEffectsEnabled="false"
+ sysui:optedOut="false"/>
+
+ </FrameLayout>
+
+ <ViewStub
+ android:id="@+id/odi_captions_tooltip_stub"
+ android:inflatedId="@+id/odi_captions_tooltip_view"
+ android:layout="@layout/volume_tool_tip_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginRight="@dimen/volume_tool_tip_right_margin"
+ android:layout_marginTop="@dimen/volume_tool_tip_top_margin"
+ android:layout_gravity="right"/>
+
+ </FrameLayout>
+
+</FrameLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout-land-television/volume_dialog_row.xml b/packages/SystemUI/res/layout-land-television/volume_dialog_row.xml
new file mode 100644
index 0000000..08209ab
--- /dev/null
+++ b/packages/SystemUI/res/layout-land-television/volume_dialog_row.xml
@@ -0,0 +1,69 @@
+<!--
+ Copyright (C) 2015 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.
+-->
+<FrameLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:tag="row"
+ android:layout_width="@dimen/volume_dialog_row_width"
+ android:layout_height="wrap_content"
+ android:background="@android:color/transparent"
+ android:clipChildren="false"
+ android:clipToPadding="false"
+ android:theme="@style/qs_theme">
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="match_parent"
+ android:background="@android:color/transparent"
+ android:gravity="center"
+ android:layout_gravity="center"
+ android:orientation="horizontal" >
+ <com.android.keyguard.AlphaOptimizedImageButton
+ android:id="@+id/volume_row_icon"
+ style="@style/VolumeButtons"
+ android:layout_width="@dimen/volume_dialog_tap_target_size"
+ android:layout_height="@dimen/volume_dialog_tap_target_size"
+ android:background="@drawable/ripple_drawable_20dp"
+ android:tint="@color/accent_tint_color_selector"
+ android:soundEffectsEnabled="false" />
+ <TextView
+ android:id="@+id/volume_row_header"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLength="10"
+ android:maxLines="1"
+ android:visibility="gone"
+ android:textColor="?android:attr/colorControlNormal"
+ android:textAppearance="@style/TextAppearance.Volume.Header" />
+ <FrameLayout
+ android:id="@+id/volume_row_slider_frame"
+ android:layout_height="match_parent"
+ android:layoutDirection="ltr"
+ android:layout_width="@dimen/volume_dialog_row_width">
+ <SeekBar
+ android:id="@+id/volume_row_slider"
+ android:clickable="false"
+ android:layout_width="@dimen/volume_dialog_row_width"
+ android:layout_height="match_parent"
+ android:layoutDirection="ltr"
+ android:layout_gravity="center"
+ android:rotation="0" />
+ </FrameLayout>
+ </LinearLayout>
+
+ <include layout="@layout/volume_dnd_icon"/>
+
+</FrameLayout>
diff --git a/packages/SystemUI/res/layout/controls_base_item.xml b/packages/SystemUI/res/layout/controls_base_item.xml
index 374e3b1..c58f572 100644
--- a/packages/SystemUI/res/layout/controls_base_item.xml
+++ b/packages/SystemUI/res/layout/controls_base_item.xml
@@ -21,8 +21,9 @@
android:layout_weight="1"
android:layout_height="@dimen/control_height"
android:padding="@dimen/control_padding"
- android:clickable="true"
+ android:clickable="false"
android:focusable="true"
+ android:screenReaderFocusable="true"
android:layout_marginLeft="@dimen/control_base_item_margin"
android:layout_marginRight="@dimen/control_base_item_margin"
android:background="@drawable/control_background">
@@ -32,6 +33,8 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/control_padding_adjustment"
+ android:clickable="false"
+ android:focusable="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
@@ -42,6 +45,8 @@
android:textAppearance="@style/TextAppearance.Control.Status"
android:paddingTop="@dimen/control_padding_adjustment"
android:paddingStart="@dimen/control_status_padding"
+ android:clickable="false"
+ android:focusable="false"
app:layout_constraintBottom_toBottomOf="@+id/icon"
app:layout_constraintStart_toEndOf="@+id/icon" />
@@ -52,6 +57,8 @@
android:textAppearance="@style/TextAppearance.Control.Status"
android:paddingTop="@dimen/control_padding_adjustment"
android:paddingStart="@dimen/control_status_padding"
+ android:clickable="false"
+ android:focusable="false"
app:layout_constraintBottom_toBottomOf="@+id/icon"
app:layout_constraintStart_toEndOf="@+id/status" />
@@ -62,6 +69,8 @@
android:textAppearance="@style/TextAppearance.Control.Title"
android:paddingLeft="@dimen/control_padding_adjustment"
android:paddingRight="@dimen/control_padding_adjustment"
+ android:clickable="false"
+ android:focusable="false"
app:layout_constraintBottom_toTopOf="@+id/subtitle"
app:layout_constraintStart_toStartOf="parent" />
@@ -73,6 +82,8 @@
android:paddingLeft="@dimen/control_padding_adjustment"
android:paddingRight="@dimen/control_padding_adjustment"
android:paddingBottom="@dimen/control_padding_adjustment"
+ android:clickable="false"
+ android:focusable="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
diff --git a/packages/SystemUI/res/layout/controls_dialog.xml b/packages/SystemUI/res/layout/controls_dialog.xml
new file mode 100644
index 0000000..3effaf5
--- /dev/null
+++ b/packages/SystemUI/res/layout/controls_dialog.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2020 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.
+-->
+<FrameLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:padding="@dimen/controls_dialog_padding"
+ android:layout_margin="@dimen/controls_dialog_padding"
+ >
+
+ <include
+ android:id="@+id/control"
+ layout="@layout/controls_base_item"
+ android:layout_width="@dimen/controls_dialog_control_width"
+ android:layout_height="@dimen/control_height"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginTop="@dimen/controls_dialog_padding"
+ android:layout_marginBottom="@dimen/controls_dialog_padding"
+ />
+</FrameLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/controls_dialog_pin.xml b/packages/SystemUI/res/layout/controls_dialog_pin.xml
new file mode 100644
index 0000000..b77d6fa
--- /dev/null
+++ b/packages/SystemUI/res/layout/controls_dialog_pin.xml
@@ -0,0 +1,36 @@
+<!--
+ ~ Copyright (C) 2020 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.
+ -->
+
+<LinearLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:paddingLeft="?android:attr/dialogPreferredPadding"
+ android:paddingRight="?android:attr/dialogPreferredPadding">
+ <EditText
+ android:id="@+id/controls_pin_input"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:hint="@string/controls_pin_instructions"
+ android:inputType="numberPassword" />
+ <CheckBox
+ android:id="@+id/controls_pin_use_alpha"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="5dp"
+ android:text="@string/controls_pin_use_alphanumeric" />
+</LinearLayout>
diff --git a/packages/SystemUI/res/layout/controls_management.xml b/packages/SystemUI/res/layout/controls_management.xml
index 6533c18..34a966c 100644
--- a/packages/SystemUI/res/layout/controls_management.xml
+++ b/packages/SystemUI/res/layout/controls_management.xml
@@ -25,13 +25,40 @@
android:paddingStart="@dimen/controls_management_side_padding"
android:paddingEnd="@dimen/controls_management_side_padding" >
- <TextView
- android:id="@+id/title"
+ <LinearLayout
+ android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:textSize="@dimen/controls_title_size"
- android:textAlignment="center" />
+ android:gravity="center_vertical">
+
+ <FrameLayout
+ android:id="@+id/icon_frame"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:gravity="start|center_vertical"
+ android:minWidth="56dp"
+ android:visibility="gone"
+ android:paddingTop="@dimen/controls_app_icon_frame_top_padding"
+ android:paddingBottom="@dimen/controls_app_icon_frame_bottom_padding"
+ android:paddingEnd="@dimen/controls_app_icon_frame_side_padding"
+ android:paddingStart="@dimen/controls_app_icon_frame_side_padding" >
+
+ <ImageView
+ android:id="@android:id/icon"
+ android:layout_width="@dimen/controls_app_icon_size"
+ android:layout_height="@dimen/controls_app_icon_size" />
+ </FrameLayout>
+
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceLarge"
+ android:textSize="@dimen/controls_title_size"
+ android:textAlignment="center" />
+
+ </LinearLayout>
+
<TextView
android:id="@+id/subtitle"
@@ -41,19 +68,11 @@
android:textAppearance="?android:attr/textAppearanceSmall"
android:textAlignment="center" />
- <androidx.core.widget.NestedScrollView
+ <ViewStub
+ android:id="@+id/stub"
android:layout_width="match_parent"
android:layout_height="0dp"
- android:layout_weight="1"
- android:orientation="vertical"
- android:layout_marginTop="@dimen/controls_management_list_margin">
-
- <ViewStub
- android:id="@+id/stub"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
- </androidx.core.widget.NestedScrollView>
+ android:layout_weight="1"/>
<FrameLayout
android:layout_width="match_parent"
diff --git a/packages/SystemUI/res/layout/controls_management_apps.xml b/packages/SystemUI/res/layout/controls_management_apps.xml
index 2bab433..42d73f3 100644
--- a/packages/SystemUI/res/layout/controls_management_apps.xml
+++ b/packages/SystemUI/res/layout/controls_management_apps.xml
@@ -14,12 +14,18 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
-
-<androidx.recyclerview.widget.RecyclerView
+<androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/list"
android:layout_width="match_parent"
- android:layout_height="match_parent"
- >
+ android:layout_height="0dp"
+ android:layout_weight="1"
+ android:orientation="vertical"
+ android:layout_marginTop="@dimen/controls_management_list_margin">
-</androidx.recyclerview.widget.RecyclerView>
\ No newline at end of file
+ <androidx.recyclerview.widget.RecyclerView
+ android:id="@+id/list"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ />
+
+</androidx.core.widget.NestedScrollView>
diff --git a/packages/SystemUI/res/layout/controls_management_favorites.xml b/packages/SystemUI/res/layout/controls_management_favorites.xml
index aab32f4..d2ccfcb 100644
--- a/packages/SystemUI/res/layout/controls_management_favorites.xml
+++ b/packages/SystemUI/res/layout/controls_management_favorites.xml
@@ -17,7 +17,7 @@
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
- android:layout_height="match_parent"
+ android:layout_height="0dp"
android:orientation="vertical">
<TextView
@@ -29,11 +29,17 @@
android:gravity="center_horizontal"
/>
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/listAll"
- android:layout_width="match_parent"
+ <com.android.systemui.controls.management.ManagementPageIndicator
+ android:id="@+id/structure_page_indicator"
+ android:layout_width="wrap_content"
android:layout_height="match_parent"
+ android:layout_gravity="center"
android:layout_marginTop="@dimen/controls_management_list_margin"
- android:nestedScrollingEnabled="false"/>
+ android:visibility="gone" />
+
+ <androidx.viewpager2.widget.ViewPager2
+ android:id="@+id/structure_pager"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"/>
</LinearLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/controls_onboarding.xml b/packages/SystemUI/res/layout/controls_onboarding.xml
new file mode 100644
index 0000000..577a3b4
--- /dev/null
+++ b/packages/SystemUI/res/layout/controls_onboarding.xml
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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.
+ -->
+
+<LinearLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_height="wrap_content"
+ android:layout_width="wrap_content"
+ android:padding="4dp"
+ android:orientation="vertical">
+
+ <View
+ android:id="@+id/arrow"
+ android:elevation="2dp"
+ android:layout_width="10dp"
+ android:layout_height="8dp"
+ android:layout_marginBottom="-2dp"
+ android:layout_gravity="center_horizontal"/>
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingStart="24dp"
+ android:paddingEnd="4dp"
+ android:background="@drawable/recents_onboarding_toast_rounded_background"
+ android:layout_gravity="center_horizontal"
+ android:elevation="2dp"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/onboarding_text"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:layout_gravity="center_vertical"
+ android:textColor="?attr/wallpaperTextColor"
+ android:textSize="16sp"/>
+ <ImageView
+ android:id="@+id/dismiss"
+ android:layout_width="40dp"
+ android:layout_height="40dp"
+ android:layout_gravity="center_vertical"
+ android:padding="10dp"
+ android:layout_marginStart="2dp"
+ android:layout_marginEnd="2dp"
+ android:alpha="0.7"
+ android:src="@drawable/ic_close_white"
+ android:tint="?attr/wallpaperTextColor"
+ android:background="?android:attr/selectableItemBackgroundBorderless"
+ android:contentDescription="@string/accessibility_desc_close"/>
+ </LinearLayout>
+</LinearLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/controls_structure_page.xml b/packages/SystemUI/res/layout/controls_structure_page.xml
new file mode 100644
index 0000000..047ab98
--- /dev/null
+++ b/packages/SystemUI/res/layout/controls_structure_page.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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.
+ -->
+
+<androidx.recyclerview.widget.RecyclerView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/listAll"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:layout_marginTop="@dimen/controls_management_list_margin"/>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/global_actions_grid_v2.xml b/packages/SystemUI/res/layout/global_actions_grid_v2.xml
index ff0c6a7..92ae1b9 100644
--- a/packages/SystemUI/res/layout/global_actions_grid_v2.xml
+++ b/packages/SystemUI/res/layout/global_actions_grid_v2.xml
@@ -1,71 +1,75 @@
<?xml version="1.0" encoding="utf-8"?>
-<ScrollView
+<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/global_actions_container"
android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <androidx.constraintlayout.widget.ConstraintLayout
- android:id="@+id/global_actions_grid_root"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+>
+ <com.android.systemui.globalactions.GlobalActionsFlatLayout
+ android:id="@id/global_actions_view"
android:layout_width="match_parent"
- android:layout_height="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:theme="@style/qs_theme"
+ android:gravity="top | center_horizontal"
android:clipChildren="false"
android:clipToPadding="false"
- android:paddingBottom="@dimen/global_actions_grid_container_shadow_offset"
- android:layout_marginBottom="@dimen/global_actions_grid_container_negative_shadow_offset">
-
- <com.android.systemui.globalactions.GlobalActionsFlatLayout
- android:id="@id/global_actions_view"
- android:layout_width="match_parent"
+ android:layout_marginTop="@dimen/global_actions_top_margin"
+ >
+ <LinearLayout
+ android:id="@android:id/list"
+ android:layout_width="wrap_content"
android:layout_height="wrap_content"
+ android:layout_marginLeft="@dimen/global_actions_grid_side_margin"
+ android:layout_marginRight="@dimen/global_actions_grid_side_margin"
+ android:paddingLeft="@dimen/global_actions_grid_horizontal_padding"
+ android:paddingRight="@dimen/global_actions_grid_horizontal_padding"
+ android:paddingTop="@dimen/global_actions_grid_vertical_padding"
+ android:paddingBottom="@dimen/global_actions_grid_vertical_padding"
android:orientation="horizontal"
- android:theme="@style/qs_theme"
- app:layout_constraintTop_toTopOf="parent"
- app:layout_constraintLeft_toLeftOf="parent"
- app:layout_constraintRight_toRightOf="parent"
- android:gravity="top | center_horizontal"
+ android:gravity="left"
+ android:translationZ="@dimen/global_actions_translate"
+ />
+ </com.android.systemui.globalactions.GlobalActionsFlatLayout>
+
+ <com.android.systemui.globalactions.MinHeightScrollView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:paddingBottom="@dimen/global_actions_grid_container_shadow_offset"
+ android:layout_marginBottom="@dimen/global_actions_grid_container_negative_shadow_offset"
+ android:orientation="vertical"
+ >
+ <LinearLayout
+ android:id="@+id/global_actions_grid_root"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
android:clipChildren="false"
+ android:orientation="vertical"
android:clipToPadding="false"
- android:layout_marginTop="@dimen/global_actions_top_margin">
+ >
<LinearLayout
- android:id="@android:id/list"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="@dimen/global_actions_grid_side_margin"
- android:layout_marginRight="@dimen/global_actions_grid_side_margin"
- android:paddingLeft="@dimen/global_actions_grid_horizontal_padding"
- android:paddingRight="@dimen/global_actions_grid_horizontal_padding"
- android:paddingTop="@dimen/global_actions_grid_vertical_padding"
- android:paddingBottom="@dimen/global_actions_grid_vertical_padding"
- android:orientation="horizontal"
- android:gravity="left"
- android:translationZ="@dimen/global_actions_translate" />
- </com.android.systemui.globalactions.GlobalActionsFlatLayout>
-
- <LinearLayout
- android:id="@+id/global_actions_panel"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- app:layout_constraintLeft_toLeftOf="parent"
- app:layout_constraintRight_toRightOf="parent"
- app:layout_constraintTop_toBottomOf="@id/global_actions_view">
-
- <FrameLayout
- android:id="@+id/global_actions_panel_container"
+ android:id="@+id/global_actions_panel"
android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ >
+ <FrameLayout
+ android:id="@+id/global_actions_panel_container"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ />
+ </LinearLayout>
- <LinearLayout
- android:id="@+id/global_actions_controls"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- app:layout_constraintLeft_toLeftOf="parent"
- app:layout_constraintRight_toRightOf="parent"
- app:layout_constraintTop_toBottomOf="@id/global_actions_panel"
- app:layout_constraintBottom_toBottomOf="parent" />
- </androidx.constraintlayout.widget.ConstraintLayout>
-</ScrollView>
+ <LinearLayout
+ android:id="@+id/global_actions_controls"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:layout_marginRight="@dimen/global_actions_grid_horizontal_padding"
+ android:layout_marginLeft="@dimen/global_actions_grid_horizontal_padding"
+ />
+ </LinearLayout>
+ </com.android.systemui.globalactions.MinHeightScrollView>
+</LinearLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/global_actions_wrapped.xml b/packages/SystemUI/res/layout/global_actions_wrapped.xml
deleted file mode 100644
index d441070..0000000
--- a/packages/SystemUI/res/layout/global_actions_wrapped.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<com.android.systemui.HardwareUiLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@id/global_actions_view"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_gravity="top|right"
- android:layout_marginBottom="0dp"
- android:orientation="vertical"
- android:paddingTop="@dimen/global_actions_top_padding"
- android:clipToPadding="false"
- android:theme="@style/qs_theme"
- android:clipChildren="false">
-
- <!-- Global actions is right-aligned to be physically near power button -->
- <LinearLayout
- android:id="@android:id/list"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="top|right"
- android:gravity="center"
- android:orientation="vertical"
- android:padding="@dimen/global_actions_padding"
- android:translationZ="@dimen/global_actions_translate" />
-
- <!-- For separated button-->
- <FrameLayout
- android:id="@+id/separated_button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="top|right"
- android:layout_marginTop="6dp"
- android:gravity="center"
- android:orientation="vertical"
- android:padding="@dimen/global_actions_padding"
- android:translationZ="@dimen/global_actions_translate" />
-
-</com.android.systemui.HardwareUiLayout>
diff --git a/packages/SystemUI/res/layout/notification_conversation_info.xml b/packages/SystemUI/res/layout/notification_conversation_info.xml
index 8460612..6a7f9e2 100644
--- a/packages/SystemUI/res/layout/notification_conversation_info.xml
+++ b/packages/SystemUI/res/layout/notification_conversation_info.xml
@@ -121,7 +121,6 @@
android:layout_marginEnd="2dp"
android:ellipsize="end"
android:text="@string/notification_delegate_header"
- android:layout_toEndOf="@id/pkg_divider"
android:maxLines="1" />
</LinearLayout>
diff --git a/packages/SystemUI/res/layout/notification_info.xml b/packages/SystemUI/res/layout/notification_info.xml
index 5d03eee..6ab573b 100644
--- a/packages/SystemUI/res/layout/notification_info.xml
+++ b/packages/SystemUI/res/layout/notification_info.xml
@@ -27,51 +27,81 @@
android:paddingStart="@*android:dimen/notification_content_margin_start">
<!-- Package Info -->
- <RelativeLayout
+ <LinearLayout
android:id="@+id/header"
android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ android:layout_height="@dimen/notification_guts_conversation_header_height"
+ android:gravity="center_vertical"
android:clipChildren="false"
android:clipToPadding="false">
<ImageView
- android:id="@+id/pkgicon"
- android:layout_width="@dimen/notification_guts_header_height"
- android:layout_height="@dimen/notification_guts_header_height"
+ android:id="@+id/pkg_icon"
+ android:layout_width="@dimen/notification_guts_conversation_icon_size"
+ android:layout_height="@dimen/notification_guts_conversation_icon_size"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
- android:layout_marginEnd="3dp" />
- <TextView
- android:id="@+id/pkgname"
- android:layout_width="wrap_content"
+ android:layout_marginEnd="15dp" />
+ <LinearLayout
+ android:id="@+id/names"
+ android:layout_weight="1"
+ android:layout_width="0dp"
+ android:orientation="vertical"
+
android:layout_height="wrap_content"
+ android:minHeight="@dimen/notification_guts_conversation_icon_size"
android:layout_centerVertical="true"
- style="@style/TextAppearance.NotificationImportanceHeader"
- android:layout_marginStart="3dp"
- android:layout_marginEnd="2dp"
- android:layout_toEndOf="@id/pkgicon"
- android:singleLine="true" />
- <TextView
- android:id="@+id/pkg_divider"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- style="@style/TextAppearance.NotificationImportanceHeader"
- android:layout_marginStart="2dp"
- android:layout_marginEnd="2dp"
- android:layout_toEndOf="@id/pkgname"
- android:text="@*android:string/notification_header_divider_symbol" />
- <TextView
- android:id="@+id/delegate_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- style="@style/TextAppearance.NotificationImportanceHeader"
- android:layout_marginStart="2dp"
- android:layout_marginEnd="2dp"
- android:ellipsize="end"
- android:text="@string/notification_delegate_header"
- android:layout_toEndOf="@id/pkg_divider"
- android:maxLines="1" />
+ android:gravity="center_vertical"
+ android:layout_alignEnd="@id/pkg_icon"
+ android:layout_toEndOf="@id/pkg_icon"
+ android:layout_alignStart="@id/mute">
+ <TextView
+ android:id="@+id/channel_name"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ style="@style/TextAppearance.NotificationImportanceChannel"/>
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="start"
+ android:orientation="horizontal">
+ <TextView
+ android:id="@+id/pkg_name"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ style="@style/TextAppearance.NotificationImportanceChannelGroup"
+ android:ellipsize="end"
+ android:maxLines="1"/>
+ <TextView
+ android:id="@+id/group_divider"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ style="@style/TextAppearance.NotificationImportanceHeader"
+ android:layout_marginStart="2dp"
+ android:layout_marginEnd="2dp"
+ android:text="@*android:string/notification_header_divider_symbol" />
+ <TextView
+ android:id="@+id/group_name"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ style="@style/TextAppearance.NotificationImportanceChannel"/>
+ </LinearLayout>
+ <TextView
+ android:id="@+id/delegate_name"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_centerVertical="true"
+ style="@style/TextAppearance.NotificationImportanceHeader"
+ android:layout_marginStart="2dp"
+ android:layout_marginEnd="2dp"
+ android:ellipsize="end"
+ android:text="@string/notification_delegate_header"
+ android:maxLines="1" />
+
+ </LinearLayout>
+
+ <!-- end aligned fields -->
<!-- Optional link to app. Only appears if the channel is not disabled and the app
asked for it -->
<ImageButton
@@ -95,91 +125,6 @@
android:src="@drawable/ic_settings"
android:layout_alignParentEnd="true"
android:tint="@color/notification_guts_link_icon_tint"/>
- </RelativeLayout>
-
- <!-- Channel Info Block -->
- <LinearLayout
- android:id="@+id/channel_info"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingEnd="@*android:dimen/notification_content_margin_end"
- android:gravity="center"
- android:orientation="vertical">
- <!-- Channel Name -->
- <TextView
- android:id="@+id/channel_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- style="@style/TextAppearance.NotificationImportanceChannel"/>
- <TextView
- android:id="@+id/group_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@style/TextAppearance.NotificationImportanceChannelGroup"
- android:ellipsize="end"
- android:maxLines="1"/>
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/blocking_helper"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="@dimen/notification_guts_button_spacing"
- android:layout_marginBottom="@dimen/notification_guts_button_spacing"
- android:paddingEnd="@*android:dimen/notification_content_margin_end"
- android:clipChildren="false"
- android:clipToPadding="false"
- android:orientation="vertical">
- <!-- blocking helper text. no need for non-configurable check b/c controls won't be
- activated in that case -->
- <TextView
- android:id="@+id/blocking_helper_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="2dp"
- android:text="@string/inline_blocking_helper"
- style="@*android:style/TextAppearance.DeviceDefault.Notification" />
- <RelativeLayout
- android:id="@+id/block_buttons"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="@dimen/notification_guts_button_spacing">
- <TextView
- android:id="@+id/blocking_helper_turn_off_notifications"
- android:text="@string/inline_turn_off_notifications"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:layout_alignParentStart="true"
- android:width="110dp"
- android:paddingEnd="15dp"
- android:breakStrategy="simple"
- style="@style/TextAppearance.NotificationInfo.Button"/>
- <TextView
- android:id="@+id/deliver_silently"
- android:text="@string/inline_deliver_silently_button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
- android:paddingEnd="15dp"
- android:width="110dp"
- android:breakStrategy="simple"
- android:layout_toStartOf="@+id/keep_showing"
- style="@style/TextAppearance.NotificationInfo.Button"/>
- <TextView
- android:id="@+id/keep_showing"
- android:text="@string/inline_keep_button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:layout_marginStart="@dimen/notification_guts_button_horizontal_spacing"
- android:width="110dp"
- android:breakStrategy="simple"
- android:layout_alignParentEnd="true"
- style="@style/TextAppearance.NotificationInfo.Button"/>
- </RelativeLayout>
</LinearLayout>
@@ -357,34 +302,4 @@
</RelativeLayout>
</LinearLayout>
-
- <com.android.systemui.statusbar.notification.row.NotificationUndoLayout
- android:id="@+id/confirmation"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:visibility="gone"
- android:orientation="horizontal" >
- <TextView
- android:id="@+id/confirmation_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="start|center_vertical"
- android:layout_marginStart="@*android:dimen/notification_content_margin_start"
- android:layout_marginEnd="@*android:dimen/notification_content_margin_start"
- android:text="@string/notification_channel_disabled"
- style="@style/TextAppearance.NotificationInfo.Confirmation"/>
- <TextView
- android:id="@+id/undo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:minWidth="@dimen/notification_importance_toggle_size"
- android:minHeight="@dimen/notification_importance_toggle_size"
- android:layout_marginTop="@dimen/notification_guts_button_spacing"
- android:layout_marginBottom="@dimen/notification_guts_button_spacing"
- android:layout_marginStart="@dimen/notification_guts_button_side_margin"
- android:layout_marginEnd="@dimen/notification_guts_button_side_margin"
- android:layout_gravity="end|center_vertical"
- android:text="@string/inline_undo"
- style="@style/TextAppearance.NotificationInfo.Button"/>
- </com.android.systemui.statusbar.notification.row.NotificationUndoLayout>
</com.android.systemui.statusbar.notification.row.NotificationInfo>
diff --git a/packages/SystemUI/res/layout/qs_media_panel.xml b/packages/SystemUI/res/layout/qs_media_panel.xml
index 22303dc..34bd703 100644
--- a/packages/SystemUI/res/layout/qs_media_panel.xml
+++ b/packages/SystemUI/res/layout/qs_media_panel.xml
@@ -32,7 +32,6 @@
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:id="@+id/header"
android:layout_marginBottom="16dp"
>
@@ -73,7 +72,7 @@
<!-- Song name -->
<TextView
- android:id="@+id/header_text"
+ android:id="@+id/header_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
diff --git a/packages/SystemUI/res/values-af/strings.xml b/packages/SystemUI/res/values-af/strings.xml
index 02104f5..9ba891d 100644
--- a/packages/SystemUI/res/values-af/strings.xml
+++ b/packages/SystemUI/res/values-af/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> bestuur jou werkprofiel. Die profiel is gekoppel aan <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, wat jou netwerkaktiwiteit, insluitend e-posse, programme en webwerwe, kan monitor.\n\nJy is ook gekoppel aan <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, wat jou persoonlike netwerkaktiwiteit kan monitor."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Ontsluit gehou deur TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Toestel sal gesluit bly totdat jy dit handmatig ontsluit"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Kry kennisgewings vinniger"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Sien hulle voordat jy ontsluit"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nee, dankie"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Beweeg na links onder"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Beweeg na regs onder"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Maak toe"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Hou kletse prominent"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nuwe kletse van <xliff:g id="APP_NAME">%1$s</xliff:g> af sal as borrels verskyn. Tik op \'n borrel om dit oop te maak. Sleep om dit te skuif.\n\nTik op die borrel"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Tik op Bestuur om borrels vanaf hierdie program af te skakel"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Stelselnavigasie is opgedateer. Gaan na Instellings toe om veranderinge te maak."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Gaan na Instellings toe om stelselnavigasie op te dateer"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Bystandmodus"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Almal"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Die lys met alle kontroles kon nie gelaai word nie."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Ander"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-am/strings.xml b/packages/SystemUI/res/values-am/strings.xml
index 22df519..a73d48d 100644
--- a/packages/SystemUI/res/values-am/strings.xml
+++ b/packages/SystemUI/res/values-am/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"የእርስዎ የሥራ መገለጫ በ<xliff:g id="ORGANIZATION">%1$s</xliff:g> የሚተዳደር ነው። መገለጫው ኢሜይሎችን፣ መተግበሪያዎችን፣ እና የድር ጣቢያዎችን ጨምሮ የአውታረ መረብ እንቅስቃሴን መቆጣጠር ከሚችለው ከ<xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ጋር ተገናኝቷል።\n\nበተጨማሪ የእርስዎን የግል የአውታረ መረብ እንቅስቃሴ መቆጣጠር ከሚችለው ከ<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ጋር ተገናኝተዋል።"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"በ TrustAgent እንደተከፈተ ቀርቷል"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"እራስዎ እስኪከፍቱት ድረስ መሣሪያ እንደተቆለፈ ይቆያል"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"ማሳወቂያዎችን ፈጥነው ያግኙ"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ከመክፈትዎ በፊት ይመልከቷቸው"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"አይ፣ አመሰግናለሁ"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"የግርጌውን ግራ አንቀሳቅስ"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ታችኛውን ቀኝ ያንቀሳቅሱ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"አሰናብት"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ውይይቶችን ከፊት ያድርጓቸው"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"ከ<xliff:g id="APP_NAME">%1$s</xliff:g> የመጡ አዲስ ውይይቶች እንደ አረፋዎች ሆነው ይታያሉ። አንድ አረፋን ለመክፈት መታ ያድርጉት። እሱን ለማንቀሳቀስ ይጎትቱት።\n\nአረፋውን መታ ያድርጉት"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"የዚህ መተግበሪያ አረፋዎችን ለማጥፋት አቀናብርን መታ ያድርጉ"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"የስርዓት ዳሰሳ ተዘምኗል። ለውጦችን ለማድረግ ወደ ቅንብሮች ይሂዱ።"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"የስርዓት ዳሰሳን ለማዘመን ወደ ቅንብሮች ይሂዱ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ተጠባባቂ"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ሁሉም"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"የሁሉም መቆጣጠሪያዎች ዝርዝር ሊጫን አልተቻለም።"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ሌላ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ar/strings.xml b/packages/SystemUI/res/values-ar/strings.xml
index ee0c65f..37f6911 100644
--- a/packages/SystemUI/res/values-ar/strings.xml
+++ b/packages/SystemUI/res/values-ar/strings.xml
@@ -62,7 +62,7 @@
<string name="usb_debugging_always" msgid="4003121804294739548">"السماح دائمًا من هذا الكمبيوتر"</string>
<string name="usb_debugging_allow" msgid="1722643858015321328">"سماح"</string>
<string name="usb_debugging_secondary_user_title" msgid="7843050591380107998">"لا يُسمح بتصحيح أخطاء USB"</string>
- <string name="usb_debugging_secondary_user_message" msgid="3740347841470403244">"لا يمكن للمستخدم الذي يسجّل دخوله حاليًا إلى هذا الجهاز تشغيل تصحيح أخطاء USB. لاستخدام هذه الميزة، يمكنك التبديل إلى المستخدم الأساسي."</string>
+ <string name="usb_debugging_secondary_user_message" msgid="3740347841470403244">"لا يمكن للمستخدم الذي يسجّل دخوله حاليًا إلى هذا الجهاز تفعيل تصحيح الأخطاء USB. لاستخدام هذه الميزة، يمكنك التبديل إلى المستخدم الأساسي."</string>
<string name="wifi_debugging_title" msgid="7300007687492186076">"هل تريد السماح باستخدام ميزة \"تصحيح الأخطاء عبر شبكة Wi-Fi\" على هذه الشبكة؟"</string>
<string name="wifi_debugging_message" msgid="5461204211731802995">"اسم الشبكة (SSID)\n<xliff:g id="SSID_0">%1$s</xliff:g>\n\nعنوان شبكة Wi‑Fi (BSSID)\n<xliff:g id="BSSID_1">%2$s</xliff:g>"</string>
<string name="wifi_debugging_always" msgid="2968383799517975155">"السماح باستخدام هذه الميزة على هذه الشبكة دائمًا"</string>
@@ -570,12 +570,13 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"يخضع الملف الشخصي للعمل لإدارة <xliff:g id="ORGANIZATION">%1$s</xliff:g>. تم ربط هذا الملف الشخصي بـ <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>، الذي يمكنه مراقبة أنشطة شبكتك، بما في ذلك الرسائل الإلكترونية والتطبيقات ومواقع الويب.\n\nتم ربطك بـ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>، الذي يمكنه مراقبة أنشطة شبكتك الشخصية."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"فتح القفل باستمرار بواسطة TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"سيظل الجهاز مقفلاً إلى أن يتم فتح قفله يدويًا"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"الحصول على الإشعارات بشكل أسرع"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"الاطّلاع عليها قبل فتح القفل"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"لا، شكرًا"</string>
<string name="hidden_notifications_setup" msgid="2064795578526982467">"إعداد"</string>
<string name="zen_mode_and_condition" msgid="5043165189511223718">"<xliff:g id="ZEN_MODE">%1$s</xliff:g>. <xliff:g id="EXIT_CONDITION">%2$s</xliff:g>"</string>
- <string name="volume_zen_end_now" msgid="5901885672973736563">"إيقاف التشغيل الآن"</string>
+ <string name="volume_zen_end_now" msgid="5901885672973736563">"إيقاف التفعيل الآن"</string>
<string name="accessibility_volume_settings" msgid="1458961116951564784">"إعدادات الصوت"</string>
<string name="accessibility_volume_expand" msgid="7653070939304433603">"توسيع"</string>
<string name="accessibility_volume_collapse" msgid="2746845391013829996">"تصغير"</string>
@@ -779,7 +780,7 @@
<string name="keyboard_key_media_stop" msgid="1509943745250377699">"إيقاف"</string>
<string name="keyboard_key_media_next" msgid="8502476691227914952">"التالي"</string>
<string name="keyboard_key_media_previous" msgid="5637875709190955351">"السابق"</string>
- <string name="keyboard_key_media_rewind" msgid="3450387734224327577">"إرجاع"</string>
+ <string name="keyboard_key_media_rewind" msgid="3450387734224327577">"ترجيع"</string>
<string name="keyboard_key_media_fast_forward" msgid="3572444327046911822">"تقديم سريع"</string>
<string name="keyboard_key_page_up" msgid="173914303254199845">"Page Up"</string>
<string name="keyboard_key_page_down" msgid="9035902490071829731">"Page Down"</string>
@@ -999,12 +1000,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"نقل إلى أسفل يمين الشاشة"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"نقل إلى أسفل اليسار"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"تجاهل"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"الاحتفاظ بالمحادثات في المقدمة"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"ستظهر المحادثات الجديدة من <xliff:g id="APP_NAME">%1$s</xliff:g> كفقاقيع. انقر على فقعة لفتحها. اسحبها لنقلها.\n\nانقر على الفقاعة."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"انقر على \"إدارة\" لإيقاف الفقاعات من هذا التطبيق."</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"تم تحديث التنقل داخل النظام. لإجراء التغييرات، يُرجى الانتقال إلى \"الإعدادات\"."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"الانتقال إلى \"الإعدادات\" لتعديل التنقل داخل النظام"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"وضع الاستعداد"</string>
@@ -1028,4 +1026,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"الكل"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"تعذّر تحميل قائمة كل عناصر التحكّم."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"غير ذلك"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-as/strings.xml b/packages/SystemUI/res/values-as/strings.xml
index a1a6ae9..2dc93cd 100644
--- a/packages/SystemUI/res/values-as/strings.xml
+++ b/packages/SystemUI/res/values-as/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g>য়ে আপোনাৰ কৰ্মস্থানৰ প্ৰ\'ফাইল পৰিচালনা কৰে। এই প্ৰ\'ফাইলটো <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>ৰে সংযুক্ত হৈ আছে যি ইমেইল, এপ্ আৰু ৱেবছাইটসমূহকে ধৰি আপোনাৰ কর্মস্থানৰ নেটৱর্কৰ কাৰ্যকলাপ নিৰীক্ষণ কৰিব পাৰিব। \n\nআপুনি <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>ৰ সৈতেও সংযুক্ত হৈ আছে, যি আপোনাৰ ব্য়ক্তিগত নেটৱৰ্কৰ কাৰ্যকলাপ নিৰীক্ষণ কৰিব পাৰে।"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgentএ আনলক কৰি ৰাখিছে"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"আপুনি নিজে আনলক নকৰালৈকে ডিভাইচ লক হৈ থাকিব"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"জাননী ক্ষিপ্ৰতাৰে লাভ কৰক"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"আপুনি আনলক কৰাৰ পূৰ্বে তেওঁলোকক চাওক"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"নালাগে, ধন্যবাদ"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"বুটামটো বাওঁফালে নিয়ক"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"তলৰ সোঁফালে নিয়ক"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"অগ্ৰাহ্য কৰক"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"চাটসমূহ সন্মুখত ৰাখক"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>ৰ নতুন চাটসমূহ বাবল হিচাপে দেখা পোৱা যাব। এইটো খুলিবলৈ এটা বাবলত টিপক। এইটোক আঁতৰাবলৈ টানি আনক।\n\nবাবলটোত টিপক"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"এই এপ্টোৰ পৰা বাবল অফ কৰিবলৈ পৰিচালনা কৰকত টিপক"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"ছিষ্টেম নেভিগেশ্বন আপডে’ট কৰা হ’ল। সলনি কৰিবলৈ ছেটিংসমূহ-লৈ যাওক।"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ছিষ্টেম নেভিগেশ্বন আপডে’ট কৰিবলৈ ছেটিংসমূহ-লৈ যাওক"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ষ্টেণ্ডবাই"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"ক্ষিপ্ৰ নিয়ন্ত্ৰণসমূহ"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"নিয়ন্ত্ৰণসমূহ যোগ দিয়ক"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"এটা এপ্ বাছনি কৰক, যিটোৰ পৰা নিয়ন্ত্ৰণসমূহ যোগ দিয়া হ\'ব"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g> টা নিয়ন্ত্ৰণ যোগ কৰা হ’ল।</item>
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> টা নিয়ন্ত্ৰণ যোগ কৰা হ’ল।</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"নিয়ন্ত্ৰণসমূহ"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"ক্ষিপ্ৰ এক্সেছৰ বাবে নিয়ন্ত্ৰণসমূহ বাছনি কৰক"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"প্ৰিয়সমূহ"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"সকলো"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"নিয়ন্ত্ৰণসমূহৰ সম্পূর্ণ সূচীখন ল’ড কৰিব পৰা নগ’ল।"</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"অন্য"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-az/strings.xml b/packages/SystemUI/res/values-az/strings.xml
index 289838e..f116289 100644
--- a/packages/SystemUI/res/values-az/strings.xml
+++ b/packages/SystemUI/res/values-az/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"İş profili <xliff:g id="ORGANIZATION">%1$s</xliff:g> tərəfindən idarə edilir. Profil e-poçt, tətbiq və veb saytlar da daxil olmaqla şəbəkə fəaliyyətinə nəzarət edən <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> tətbiqinə qoşuludur.\n\nEyni zamanda şəxsi şəbəkə fəaliyyətinə nəzarət edən <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> tətbiqinə qoşulusunuz."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ilə açıq saxlayın"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Bildirişləri daha sürətlə əldə edin"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Kiliddən çıxarmadan öncə onları görün"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Yox, çox sağ olun"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Aşağıya sola köçürün"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Aşağıya sağa köçürün"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Kənarlaşdırın"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Söhbətləri öndə saxlayın"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Yeni <xliff:g id="APP_NAME">%1$s</xliff:g> söhbətləri qabarcıq şəklində görünəcək. Açmaq üçün qabarcığa toxunun. Hərəkət etdirmək üçün onu sürüşdürün.\n\nQabarcığa toxunun"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Bu tətbiqdə qabarcıqları deaktiv etmək üçün \"İdarə edin\" seçiminə toxunun"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Sistem naviqasiyası yeniləndi. Dəyişiklik etmək üçün Ayarlara daxil olun."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Sistem naviqasiyasını yeniləmək üçün Ayarlara keçin"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Gözləmə rejimi"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Hamısı"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Bütün nizamlayıcıların siyahısı yüklənmədi."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Digər"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-b+sr+Latn/strings.xml b/packages/SystemUI/res/values-b+sr+Latn/strings.xml
index b690829..ac8d937 100644
--- a/packages/SystemUI/res/values-b+sr+Latn/strings.xml
+++ b/packages/SystemUI/res/values-b+sr+Latn/strings.xml
@@ -561,6 +561,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Profilom za Work upravlja <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Povezan je sa aplikacijom <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, koja može da nadgleda aktivnosti na poslovnoj mreži, uključujući imejlove, aplikacije i veb-sajtove.\n\nPovezani ste i sa aplikacijom <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, koja može da nadgleda aktivnosti na ličnoj mreži."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Pouzdani agent sprečava zaključavanje"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Uređaj će ostati zaključan dok ga ne otključate ručno"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Brže dobijajte obaveštenja"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Pregledajte ih pre otključavanja"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ne, hvala"</string>
@@ -984,12 +985,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Premesti dole levo"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Premesti dole desno"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Odbaci"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Neka poruke ćaskanja ostanu u prvom planu"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nove poruke ćaskanja iz aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g> će se prikazati kao oblačići. Dodirnite oblačić da biste ga otvorili. Prevucite da biste ga premestili.\n\nDodirnite oblačić"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Dodirnite Upravljajte da biste isključili oblačiće iz ove aplikacije"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigacija sistema je ažurirana. Da biste uneli izmene, idite u Podešavanja."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Idite u Podešavanja da biste ažurirali navigaciju sistema"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Stanje pripravnosti"</string>
@@ -1010,4 +1008,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Sve"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Učitavanje liste svih kontrola nije uspelo."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Drugo"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-be/strings.xml b/packages/SystemUI/res/values-be/strings.xml
index feee6a2..29d76a6 100644
--- a/packages/SystemUI/res/values-be/strings.xml
+++ b/packages/SystemUI/res/values-be/strings.xml
@@ -566,6 +566,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Ваш працоўны профіль знаходзіцца пад кіраваннем <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Ён падключаны да праграмы <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, якая можа сачыць за вашай працоўнай сеткавай актыўнасцю, уключаючы электронную пошту, праграмы і вэб-сайты.\n\nВы таксама падключаны да праграмы <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, якая можа сачыць за вашай асабістай сеткавай актыўнасцю."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Разблакіравана з дапамогай TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Прылада будзе заставацца заблакіраванай, пакуль вы не разблакіруеце яе ўручную"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Атрымлівайце апавяшчэнні хутчэй"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Праглядайце іх перад разблакіроўкай"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Не, дзякуй"</string>
@@ -991,12 +992,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Перамясціць лявей і ніжэй"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Перамясціць правей і ніжэй"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Адхіліць"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Пакідаць чаты на экране"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Новыя чаты з праграмы \"<xliff:g id="APP_NAME">%1$s</xliff:g>\" будуць паказвацца ў выглядзе ўсплывальных апавяшчэнняў. Каб адкрыць усплывальнае апавяшчэнне, націсніце на яго. Каб перамясціць – перацягніце.\n\nНацісніце на ўсплывальнае апавяшчэнне"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Каб выключыць усплывальная апавяшчэнні з гэтай праграмы, націсніце \"Кіраваць\""</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Навігацыя ў сістэме абноўлена. Каб унесці змяненні, перайдзіце ў Налады."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Перайдзіце ў Налады, каб абнавіць параметры навігацыі ў сістэме"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Рэжым чакання"</string>
@@ -1018,4 +1016,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Усе"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Не ўдалося загрузіць спіс усіх сродкаў кіравання."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Іншае"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-bg/strings.xml b/packages/SystemUI/res/values-bg/strings.xml
index fa57d28..efb5b07 100644
--- a/packages/SystemUI/res/values-bg/strings.xml
+++ b/packages/SystemUI/res/values-bg/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Служебният ви потребителски профил се управлява от <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Той е свързан с приложението <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, което може да наблюдава служебната ви активност в мрежата, включително имейли, приложения и уебсайтове.\n\nУстановена е връзка и с приложението <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, което може да наблюдава личната ви активност в мрежата."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Поддържа се отключено от надежден агент"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Устройството ще остане заключено, докато не го отключите ръчно"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Получавайте известия по-бързо"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Вижте известията, преди да отключите"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Няма нужда"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Преместване долу вляво"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Преместване долу вдясно"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Отхвърляне"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Задръжте чатовете на екрана"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Новите чатове от <xliff:g id="APP_NAME">%1$s</xliff:g> ще се показват като балончета. Докоснете някое, за да го отворите. Плъзнете, за да го преместите.\n\nДокоснете балончето"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Докоснете „Управление“, за да изключите балончетата от това приложение"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Режимът за навигиране в системата е актуализиран. За да извършите промени, отворете настройките."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Отворете настройките, за да актуализирате режима за навигиране в системата"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Режим на готовност"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Всички"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Списъкът с всички контроли не бе зареден."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Друго"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-bn/strings.xml b/packages/SystemUI/res/values-bn/strings.xml
index 1f6a377..7c0701f 100644
--- a/packages/SystemUI/res/values-bn/strings.xml
+++ b/packages/SystemUI/res/values-bn/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> আপনার কর্মস্থলের প্রোফাইল পরিচালনা করে। প্রোফাইলটি <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> এর সাথে সংযুক্ত, যেটি ইমেল অ্যাপ, ও ওয়েবসাইট সহ আপনার কর্মস্থলের নেটওয়ার্ক অ্যাক্টিভিটির উপরে নজর রাখতে পারে।\n\n এ ছাড়াও আপনি <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> এর সাথে সংযুক্ত, যেটি আপনার ব্যক্তিগত নেটওয়ার্কে নজর রাখে।"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent দিয়ে আনলক করে রাখা হয়েছে"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"আপনি নিজে আনলক না করা পর্যন্ত ডিভাইসটি লক হয়ে থাকবে"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"বিজ্ঞপ্তিগুলি আরও দ্রুত পান"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"আপনি আনলক করার আগে ওগুলো দেখুন"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"না থাক"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"নিচে বাঁদিকে সরান"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"নিচে ডান দিকে সরান"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"খারিজ করুন"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"চ্যাটগুলি সামনে রাখুন"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>-এর তরফ থেকে নতুন চ্যাট বাবল হিসেবে দেখানো হবে। এটি খোলার জন্য বাবল ট্যাপ করুন। এটি সরানোর জন্য টেনে আনুন।\n\nবাবল ট্যাপ করুন"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"এই অ্যাপ থেকে বাবল বন্ধ করতে ম্যানেজ করুন বিকল্প ট্যাপ করুন"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"সিস্টেম নেভিগেশন আপডেট হয়েছে। পরিবর্তন করার জন্য সেটিংসে যান।"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"সিস্টেম নেভিগেশন আপডেট করতে সেটিংসে যান"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"স্ট্যান্ডবাই"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"দ্রুত নিয়ন্ত্রণ"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"কন্ট্রোল যোগ করুন"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"এমন একটি অ্যাপ বাছুন যেটি থেকে কন্ট্রোল যোগ করা যাবে"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g>টি কন্ট্রোল যোগ করা হয়েছে।</item>
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g>টি কন্ট্রোল যোগ করা হয়েছে।</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"নিয়ন্ত্রণ"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"দ্রুত অ্যাক্সেস করার জন্য কন্ট্রোল বেছে নিন"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"পছন্দসই"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"সব"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"সব কন্ট্রোলের তালিকা লোড করা যায়নি।"</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"অন্য"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-bs/strings.xml b/packages/SystemUI/res/values-bs/strings.xml
index fcc3680..ce6fe52 100644
--- a/packages/SystemUI/res/values-bs/strings.xml
+++ b/packages/SystemUI/res/values-bs/strings.xml
@@ -561,6 +561,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Radnim profilom upravlja <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profil je povezan s aplikacijom <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, koja može pratiti vašu aktivnost na radnoj mreži, uključujući e-poruke, aplikacije i web lokacije.\n\nPovezani ste i sa aplikacijom <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, koja može pratiti vašu aktivnost na privatnoj mreži."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Pouzdani agent sprečava zaključavanje"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Uređaj će ostati zaključan dok ga ručno ne otključate"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Brže primaj obavještenja"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Vidi ih prije otključavanja"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ne, hvala"</string>
@@ -986,12 +987,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Pomjeri dolje lijevo"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Pomjerite dolje desno"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Odbaci"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Zadržite chatove u prvom planu"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Novi chatovi iz aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g> će se prikazati u oblačićima. Dodirnite oblačić da ga otvorite. Prevucite da ga premjestite.\n\nDodirnite oblačić"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Dodirnite Upravljaj da isključite oblačiće iz ove aplikacije"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigiranje sistemom je ažurirano. Da izvršite promjene, idite u Postavke."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Idite u Postavke da ažurirate navigiranje sistemom"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Stanje mirovanja"</string>
@@ -1012,4 +1010,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Sve"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Učitavanje liste svih kontrola nije uspjelo."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Drugo"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ca/strings.xml b/packages/SystemUI/res/values-ca/strings.xml
index 7f7eff1..f6f89fd 100644
--- a/packages/SystemUI/res/values-ca/strings.xml
+++ b/packages/SystemUI/res/values-ca/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> gestiona el teu perfil de treball. El perfil està connectat a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, que pot supervisar la teva activitat a la xarxa de treball, com ara els correus electrònics, les aplicacions i els llocs web.\n\nTambé estàs connectat a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que pot supervisar la teva activitat personal a la xarxa."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Desbloquejat per TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"El dispositiu continuarà bloquejat fins que no el desbloquegis manualment."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Rep notificacions més ràpidament"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Mostra-les abans de desbloquejar"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, gràcies"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mou a baix a l\'esquerra"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mou a baix a la dreta"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Omet"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Mantén els xats a la vista"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Els xats nous de l\'aplicació <xliff:g id="APP_NAME">%1$s</xliff:g> es mostraran en forma de bombolles. Toca una bombolla per obrir-la. Arrossega-la per moure-la.\n\nToca la bombolla"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Toca Gestiona per desactivar les bombolles d\'aquesta aplicació"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"S\'ha actualitzat el sistema de navegació. Per fer canvis, ves a Configuració."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Ves a Configuració per actualitzar el sistema de navegació"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"En espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tots"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"No s\'ha pogut carregar la llista completa de controls."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Altres"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-cs/strings.xml b/packages/SystemUI/res/values-cs/strings.xml
index 8d26c4a..63290521 100644
--- a/packages/SystemUI/res/values-cs/strings.xml
+++ b/packages/SystemUI/res/values-cs/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Váš pracovní profil spravuje organizace <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Je připojen k aplikaci <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, která může sledovat vaši aktivitu v síti, včetně e-mailů, aplikací a webů.\n\nTaké jste připojeni k aplikaci <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, která může sledovat vaši osobní aktivitu v síti."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Odemknutí udržováno funkcí TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Zařízení zůstane uzamčeno, dokud je ručně neodemknete"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Čtěte si oznámení rychleji"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Můžete si je přečíst před odemčením obrazovky."</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ne, děkuji"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Přesunout vlevo dolů"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Přesunout vpravo dolů"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Zavřít"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Zobrazovat chaty v popředí"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nové chaty z aplikace <xliff:g id="APP_NAME">%1$s</xliff:g> se budou zobrazovat jako bubliny. Bublinu otevřete klepnutím. Přetažením ji přemístíte.\n\nKlepnout na bublinu"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Bubliny pro tuto aplikaci můžete vypnout klepnutím na Spravovat"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Systémová navigace byla aktualizována. Chcete-li provést změny, přejděte do Nastavení."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Přejděte do Nastavení a aktualizujte systémovou navigaci"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Pohotovostní režim"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Vše"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Načtení seznamu všech ovládacích prvků se nezdařilo."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Jiné"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-da/strings.xml b/packages/SystemUI/res/values-da/strings.xml
index 1ad3102..bb2f57a 100644
--- a/packages/SystemUI/res/values-da/strings.xml
+++ b/packages/SystemUI/res/values-da/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Din arbejdsprofil administreres af <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profilen har forbindelse til <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, som kan overvåge din netværksaktivitet, bl.a. mails, apps og websites.\n\nDu har også forbindelse til <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, som kan overvåge din personlige netværksaktivitet."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Holdes oplåst af TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Enheden vil forblive låst, indtil du manuelt låser den op"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Modtag notifikationer hurtigere"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Se dem, før du låser op"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nej tak"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Flyt ned til venstre"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Flyt ned til højre"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Afvis"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Hold chatsamtaler i forgrunden"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nye chatsamtaler fra <xliff:g id="APP_NAME">%1$s</xliff:g> vises som bobler. Tryk på en boble for at åbne samtalen. Træk boblen for at flytte den.\n\nTryk på boblen"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Tryk på Administrer for at deaktivere bobler fra denne app"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Systemnavigationen blev opdateret. Gå til Indstillinger for at foretage ændringer."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Gå til Indstillinger for at opdatere systemnavigationen"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Standby"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Alle"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Listen over styringselementer kunne ikke indlæses."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Andre"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-de/strings.xml b/packages/SystemUI/res/values-de/strings.xml
index 4978041..bfbc735 100644
--- a/packages/SystemUI/res/values-de/strings.xml
+++ b/packages/SystemUI/res/values-de/strings.xml
@@ -562,6 +562,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Dein Arbeitsprofil wird von <xliff:g id="ORGANIZATION">%1$s</xliff:g> verwaltet. Das Profil ist mit <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> verknüpft. Diese App kann deine Netzwerkaktivitäten überwachen, einschließlich E-Mails, Apps und Websites.\n\nDu bist auch mit <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> verbunden, die deine persönlichen Netzwerkaktivitäten überwachen kann."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Durch TrustAgent entsperrt"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Das Gerät bleibt gesperrt, bis du es manuell entsperrst."</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"Benachrichtigungen schneller erhalten"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Vor dem Entsperren anzeigen"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nein danke"</string>
@@ -983,12 +985,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Nach unten links verschieben"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Nach unten rechts verschieben"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Schließen"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Chats im Vordergrund behalten"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Neue <xliff:g id="APP_NAME">%1$s</xliff:g>-Chats werden als Bubbles angezeigt. Wenn du eine Bubble öffnen möchtest, tippe sie an. Wenn du sie verschieben möchtest, ziehe an ihr.\n\nTippe die Bubble an."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Tippe auf \"Verwalten\", um Bubbles für diese App zu deaktivieren"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Systemsteuerungseinstellungen wurden angepasst. Änderungen kannst du in den Einstellungen vornehmen."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Gehe zu den Einstellungen, um die Systemsteuerung anzupassen"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Standby"</string>
@@ -1008,4 +1007,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Alle"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Fehler beim Laden der Liste mit Steuerelementen."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Andere"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-el/strings.xml b/packages/SystemUI/res/values-el/strings.xml
index 3eab4dd..f0b0934 100644
--- a/packages/SystemUI/res/values-el/strings.xml
+++ b/packages/SystemUI/res/values-el/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Ο οργανισμός <xliff:g id="ORGANIZATION">%1$s</xliff:g> διαχειρίζεται το προφίλ εργασίας σας. Το προφίλ συνδέεται με την εφαρμογή <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, η οποία μπορεί να παρακολουθεί τη δραστηριότητα του δικτύου της εργασίας σας, συμπεριλαμβανομένων μηνυμάτων ηλεκτρονικού ταχυδρομείου, εφαρμογών και ιστοτόπων.\n\nΕπίσης, είστε συνδεδεμένοι στην εφαρμογή <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, που έχει τη δυνατότητα παρακολούθησης της δραστηριότητας του προσωπικού σας δικτύου."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Διατήρηση ξεκλειδώματος με TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Η συσκευή θα παραμείνει κλειδωμένη μέχρι να την ξεκλειδώσετε μη αυτόματα"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Λάβετε ειδοποιήσεις γρηγορότερα"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Εμφάνιση πριν το ξεκλείδωμα"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Όχι"</string>
@@ -1001,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Όλα"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Ανεπιτυχής φόρτωση λίστας όλων των στοιχ. ελέγχου."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Άλλο"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-en-rAU/strings.xml b/packages/SystemUI/res/values-en-rAU/strings.xml
index 98fcd53..c560b17 100644
--- a/packages/SystemUI/res/values-en-rAU/strings.xml
+++ b/packages/SystemUI/res/values-en-rAU/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Your work profile is managed by <xliff:g id="ORGANIZATION">%1$s</xliff:g>. The profile is connected to <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, which can monitor your work network activity, including emails, apps and websites.\n\nYou\'re also connected to <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, which can monitor your personal network activity."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Kept unlocked by trust agent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Get notifications faster"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"See them before you unlock"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, thanks"</string>
@@ -1001,4 +1002,7 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"All"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"The list of all controls could not be loaded."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Other"</string>
+ <string name="controls_dialog_title" msgid="8806193219278278442">"Add to Quick Controls"</string>
+ <string name="controls_dialog_ok" msgid="7011816381344485651">"Add to favourites"</string>
+ <string name="controls_dialog_message" msgid="6292099631702047540">"<xliff:g id="APP">%s</xliff:g> suggested this control to add to your favourites."</string>
</resources>
diff --git a/packages/SystemUI/res/values-en-rCA/strings.xml b/packages/SystemUI/res/values-en-rCA/strings.xml
index dbdff59..91d0d74 100644
--- a/packages/SystemUI/res/values-en-rCA/strings.xml
+++ b/packages/SystemUI/res/values-en-rCA/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Your work profile is managed by <xliff:g id="ORGANIZATION">%1$s</xliff:g>. The profile is connected to <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, which can monitor your work network activity, including emails, apps and websites.\n\nYou\'re also connected to <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, which can monitor your personal network activity."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Kept unlocked by trust agent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Get notifications faster"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"See them before you unlock"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, thanks"</string>
@@ -1001,4 +1002,7 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"All"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"The list of all controls could not be loaded."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Other"</string>
+ <string name="controls_dialog_title" msgid="8806193219278278442">"Add to Quick Controls"</string>
+ <string name="controls_dialog_ok" msgid="7011816381344485651">"Add to favourites"</string>
+ <string name="controls_dialog_message" msgid="6292099631702047540">"<xliff:g id="APP">%s</xliff:g> suggested this control to add to your favourites."</string>
</resources>
diff --git a/packages/SystemUI/res/values-en-rGB/strings.xml b/packages/SystemUI/res/values-en-rGB/strings.xml
index 98fcd53..c560b17 100644
--- a/packages/SystemUI/res/values-en-rGB/strings.xml
+++ b/packages/SystemUI/res/values-en-rGB/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Your work profile is managed by <xliff:g id="ORGANIZATION">%1$s</xliff:g>. The profile is connected to <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, which can monitor your work network activity, including emails, apps and websites.\n\nYou\'re also connected to <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, which can monitor your personal network activity."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Kept unlocked by trust agent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Get notifications faster"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"See them before you unlock"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, thanks"</string>
@@ -1001,4 +1002,7 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"All"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"The list of all controls could not be loaded."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Other"</string>
+ <string name="controls_dialog_title" msgid="8806193219278278442">"Add to Quick Controls"</string>
+ <string name="controls_dialog_ok" msgid="7011816381344485651">"Add to favourites"</string>
+ <string name="controls_dialog_message" msgid="6292099631702047540">"<xliff:g id="APP">%s</xliff:g> suggested this control to add to your favourites."</string>
</resources>
diff --git a/packages/SystemUI/res/values-en-rIN/strings.xml b/packages/SystemUI/res/values-en-rIN/strings.xml
index 98fcd53..c560b17 100644
--- a/packages/SystemUI/res/values-en-rIN/strings.xml
+++ b/packages/SystemUI/res/values-en-rIN/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Your work profile is managed by <xliff:g id="ORGANIZATION">%1$s</xliff:g>. The profile is connected to <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, which can monitor your work network activity, including emails, apps and websites.\n\nYou\'re also connected to <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, which can monitor your personal network activity."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Kept unlocked by trust agent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Get notifications faster"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"See them before you unlock"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, thanks"</string>
@@ -1001,4 +1002,7 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"All"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"The list of all controls could not be loaded."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Other"</string>
+ <string name="controls_dialog_title" msgid="8806193219278278442">"Add to Quick Controls"</string>
+ <string name="controls_dialog_ok" msgid="7011816381344485651">"Add to favourites"</string>
+ <string name="controls_dialog_message" msgid="6292099631702047540">"<xliff:g id="APP">%s</xliff:g> suggested this control to add to your favourites."</string>
</resources>
diff --git a/packages/SystemUI/res/values-en-rXC/strings.xml b/packages/SystemUI/res/values-en-rXC/strings.xml
index 8b6a7eb..4c83c13 100644
--- a/packages/SystemUI/res/values-en-rXC/strings.xml
+++ b/packages/SystemUI/res/values-en-rXC/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Your work profile is managed by <xliff:g id="ORGANIZATION">%1$s</xliff:g>. The profile is connected to <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, which can monitor your work network activity, including emails, apps, and websites.\n\nYou\'re also connected to <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, which can monitor your personal network activity."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Kept unlocked by TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Get notifications faster"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"See them before you unlock"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No thanks"</string>
@@ -1001,4 +1002,7 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"All"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"The list of all controls could not be loaded."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Other"</string>
+ <string name="controls_dialog_title" msgid="8806193219278278442">"Add to Quick Controls"</string>
+ <string name="controls_dialog_ok" msgid="7011816381344485651">"Add to favorites"</string>
+ <string name="controls_dialog_message" msgid="6292099631702047540">"<xliff:g id="APP">%s</xliff:g> suggested this control to add to your favorites."</string>
</resources>
diff --git a/packages/SystemUI/res/values-es-rUS/strings.xml b/packages/SystemUI/res/values-es-rUS/strings.xml
index f5c7808..979e4ab 100644
--- a/packages/SystemUI/res/values-es-rUS/strings.xml
+++ b/packages/SystemUI/res/values-es-rUS/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> administra tu perfil de red. El perfil está conectado a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, que puede controlar tu actividad de red de trabajo, incluidos los correos electrónicos, las apps y los sitios web.\n\nTambién estás conectado a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que puede controlar tu actividad de red personal."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent lo mantiene desbloqueado"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"El dispositivo permanecerá bloqueado hasta que lo desbloquees manualmente."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Recibe notificaciones más rápido"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Ver antes de desbloquear"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, gracias"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Ubicar abajo a la izquierda"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Ubicar abajo a la derecha"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ignorar"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Mantener los chats a la vista"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Los chats nuevos de <xliff:g id="APP_NAME">%1$s</xliff:g> se mostrarán como burbujas. Presiona una burbuja para abrirla. Arrástrala para moverla.\n\nPresiona la burbuja"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Presiona Administrar para desactivar las burbujas de esta app"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Se actualizó el sistema de navegación. Para hacer cambios, ve a Configuración."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Ve a Configuración para actualizar la navegación del sistema"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"En espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Todo"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"No se cargó la lista completa de controles."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Otros"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-es/strings.xml b/packages/SystemUI/res/values-es/strings.xml
index 85af824..c58ec87 100644
--- a/packages/SystemUI/res/values-es/strings.xml
+++ b/packages/SystemUI/res/values-es/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> gestiona tu perfil de trabajo. El perfil está conectado a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, que puede supervisar tu actividad de red profesional, como los correos electrónicos, las aplicaciones y los sitios web.\n\nTambién te has conectado a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que puede supervisar tu actividad de red personal."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Desbloqueado por TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"El dispositivo permanecerá bloqueado hasta que se desbloquee manualmente"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Recibe notificaciones más rápido"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Ver antes de desbloquear"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, gracias"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mover abajo a la izquierda."</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mover abajo a la derecha"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Cerrar"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Mantén los chats a la vista"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Los nuevos chats de <xliff:g id="APP_NAME">%1$s</xliff:g> se mostrarán como burbujas. Toca una burbuja para abrirla. Arrástrala para moverla.\n\nToca la burbuja"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Toca Gestionar para desactivar las burbujas de esta aplicación"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Se ha actualizado la navegación del sistema. Para hacer cambios, ve a Ajustes."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Ve a Ajustes para actualizar la navegación del sistema"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"En espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Todos"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"No se ha podido cargar la lista de los controles."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Otros"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-et/strings.xml b/packages/SystemUI/res/values-et/strings.xml
index 548076d..bb15e29 100644
--- a/packages/SystemUI/res/values-et/strings.xml
+++ b/packages/SystemUI/res/values-et/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Teie tööprofiili haldab <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profiil on ühendatud rakendusega <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, mis saab jälgida teie töökoha võrgutegevusi, sh meile, rakendusi ja veebisaite.\n\nOlete ühendatud ka rakendusega <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, mis saab jälgida teie isiklikke võrgutegevusi."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Avatuna hoiab TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Seade jääb lukku, kuni selle käsitsi avate"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Saate märguandeid kiiremini"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Näete neid enne avamist"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Tänan, ei"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Teisalda alla vasakule"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Teisalda alla paremale"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Loobu"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Hoia vestlused esiplaanil"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Uued vestlused rakendusest <xliff:g id="APP_NAME">%1$s</xliff:g> kuvatakse mullidena. Selle avamiseks puudutage mulli. Teisaldamiseks lohistage.\n\nPuudutage mulli"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Selle rakenduse puhul mullide väljalülitamiseks puudutage valikut Haldamine"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Süsteemis navigeerimine on värskendatud. Muutmiseks avage jaotis Seaded."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Süsteemi navigeerimise värskendamiseks avage jaotis Seaded"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Ooterežiim"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Kõik"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Kõikide juhtelementide loendit ei saanud laadida."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Muu"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-eu/strings.xml b/packages/SystemUI/res/values-eu/strings.xml
index 380b752..5961e52 100644
--- a/packages/SystemUI/res/values-eu/strings.xml
+++ b/packages/SystemUI/res/values-eu/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> erakundeak kudeatzen dizu laneko profila. <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> aplikaziora dago konektatuta profila, eta aplikazio horrek sarean egiten dituzun jarduerak kontrola ditzake, mezu elektronikoak, aplikazioak eta webguneak barne. \n\n<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> aplikaziora ere zaude konektatuta, eta hark sare pertsonalean egiten dituzun jarduerak kontrola ditzake."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent bidez desblokeatuta"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Gailua blokeatuta egongo da eskuz desblokeatu arte"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Eskuratu jakinarazpenak azkarrago"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Ikusi desblokeatu baino lehen"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ez, eskerrik asko"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Eraman behealdera, ezkerretara"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Eraman behealdera, eskuinetara"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Baztertu"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Utzi txatak aurrealdean"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> aplikazioaren txat berriak burbuila gisa agertuko dira. Burbuilak irekitzeko, saka itzazu. Mugitzeko, berriz, arrasta itzazu.\n\nSakatu burbuila"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Aplikazioaren burbuilak desaktibatzeko, sakatu Kudeatu"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Eguneratu da sistemaren nabigazioa. Aldaketak egiteko, joan Ezarpenak atalera."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Sistemaren nabigazioa eguneratzeko, joan Ezarpenak atalera"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Egonean"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Guztiak"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Ezin izan da kargatu kontrol guztien zerrenda."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Beste bat"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-fa/strings.xml b/packages/SystemUI/res/values-fa/strings.xml
index c7c0336..b2c0d2e 100644
--- a/packages/SystemUI/res/values-fa/strings.xml
+++ b/packages/SystemUI/res/values-fa/strings.xml
@@ -498,7 +498,7 @@
<string name="notification_section_header_conversations" msgid="821834744538345661">"مکالمهها"</string>
<string name="accessibility_notification_section_header_gentle_clear_all" msgid="6490207897764933919">"پاک کردن همه اعلانهای بیصدا"</string>
<string name="dnd_suppressing_shade_text" msgid="5588252250634464042">"اعلانها توسط «مزاحم نشوید» موقتاً متوقف شدند"</string>
- <string name="media_projection_action_text" msgid="3634906766918186440">"اکنون شروع شود"</string>
+ <string name="media_projection_action_text" msgid="3634906766918186440">"اکنون شروع کنید"</string>
<string name="empty_shade_text" msgid="8935967157319717412">"اعلانی موجود نیست"</string>
<string name="profile_owned_footer" msgid="2756770645766113964">"شاید نمایه کنترل شود"</string>
<string name="vpn_footer" msgid="3457155078010607471">"ممکن است شبکه کنترل شود"</string>
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"نمایه کاریتان توسط <xliff:g id="ORGANIZATION">%1$s</xliff:g> مدیریت میشود. این نمایه به <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> متصل است که میتواند تنظیمات، دسترسی شرکتی، برنامهها، دادههای مرتبط با دستگاه و اطلاعات مکان دستگاه شما را پایش کند.\n\nشما همچنین به <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> متصل هستید که میتواند فعالیت خصوصی شما را در شبکه پایش کند."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"با TrustAgent قفل را باز نگهدارید"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"دستگاه قفل باقی میماند تا زمانی که قفل آن را به صورت دستی باز کنید"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"دریافت سریعتر اعلانها"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"قبل از باز کردن قفل آنها را مشاهده کنید"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"نه متشکرم"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"انتقال به پایین سمت راست"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"انتقال به پایین سمت چپ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"رد کردن"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"نگه داشتن گپها در جلو"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"گپهای جدید از <xliff:g id="APP_NAME">%1$s</xliff:g> بهصورت «حباب» نمایش داده میشوند. روی «حباب» ضربه بزنید تا باز شود. آن را بکشید تا جابهجا شود.\n\nروی «حباب» ضربه بزنید"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"برای خاموش کردن «حبابها» از این برنامه، روی «مدیریت» ضربه بزنید"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"پیمایش سیستم بهروزرسانی شد. برای انجام تغییرات به «تنظیمات» بروید."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"برای بهروزرسانی پیمایش سیستم، به «تنظیمات» بروید"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"آمادهبهکار"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"همه"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"فهرست همه کنترلها را نمیتوان بارگیری کرد."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"موارد دیگر"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-fi/strings.xml b/packages/SystemUI/res/values-fi/strings.xml
index 0daab9e..86c6e7c 100644
--- a/packages/SystemUI/res/values-fi/strings.xml
+++ b/packages/SystemUI/res/values-fi/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> hallinnoi työprofiiliasi. Se on yhteydessä sovellukseen <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, joka voi valvoa toimintaasi verkossa, esimerkiksi sähköposteja, sovelluksia ja verkkosivustoja.\n\nLisäksi olet yhteydessä sovellukseen <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, joka voi valvoa henkilökohtaista toimintaasi verkossa."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent pitää lukitusta avattuna"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Laite pysyy lukittuna, kunnes se avataan käsin"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Näe ilmoitukset nopeammin"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Näytä ennen lukituksen avaamista"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ei kiitos"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Siirrä vasempaan alareunaan"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Siirrä oikeaan alareunaan"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ohita"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Säilytä chatit etualalla"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Sovelluksen <xliff:g id="APP_NAME">%1$s</xliff:g> uudet chatit näkyvät ohjekuplina. Kosketa ohjekuplaa avataksesi sen. Siirrä sitä vetämällä.\n\n Kosketa ohjekuplaa."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Valitse Hallinnoi, jos haluat poistaa ohjekuplat käytöstä tästä sovelluksesta"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Järjestelmän navigointitapa vaihdettu. Voit muuttaa sitä asetuksista."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Vaihda järjestelmän navigointitapaa asetuksista"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Virransäästötila"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Kaikki"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Kaikkien säätimien luetteloa ei voitu ladata."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Muu"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-fr-rCA/strings.xml b/packages/SystemUI/res/values-fr-rCA/strings.xml
index cc9b7c2..2c5da71 100644
--- a/packages/SystemUI/res/values-fr-rCA/strings.xml
+++ b/packages/SystemUI/res/values-fr-rCA/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Votre profil professionnel est géré par <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Ce profil est connecté à <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, qui peut contrôler votre activité professionnelle sur le réseau, y compris l\'activité relative aux courriels, aux applications et aux sites Web.\n\nVous êtes également connecté à <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, qui peut contrôler votre activité personnelle sur le réseau."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Maintenu déverrouillé par TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"L\'appareil restera verrouillé jusqu\'à ce que vous le déverrouilliez manuellement"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Voir les notifications plus rapidement"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Afficher les notifications avant de déverrouiller l\'appareil"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Non, merci"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Déplacer dans coin inf. gauche"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Déplacer dans coin inf. droit"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Fermer"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Garder les messages de clavardage à l\'avant"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Les nouveaux messages de clavardage de <xliff:g id="APP_NAME">%1$s</xliff:g> s\'afficheront sous forme de bulles. Pour ouvrir une bulle, touchez-la. Pour la déplacer, faites-la glisser.\n\nTouchez la bulle"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Toucher Gérer pour désactiver les bulles de cette application"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"La navigation système a été mise à jour. Pour apporter des modifications, accédez au menu Paramètres."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Accédez au menu Paramètres pour mettre à jour la navigation système"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Veille"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tous"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Impossible de charger la liste des commandes."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Autre"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-fr/strings.xml b/packages/SystemUI/res/values-fr/strings.xml
index 26a4010..aebb52b 100644
--- a/packages/SystemUI/res/values-fr/strings.xml
+++ b/packages/SystemUI/res/values-fr/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Votre profil professionnel est géré par <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Ce profil est connecté à <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, qui peut contrôler votre activité professionnelle sur le réseau, y compris l\'activité relative aux e-mails, aux applications et aux sites Web.\n\nVous êtes également connecté à <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, qui peut contrôler votre activité personnelle sur le réseau."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Maintenu déverrouillé par TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"L\'appareil restera verrouillé jusqu\'à ce que vous le déverrouilliez manuellement."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Recevoir les notifications plus vite"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Afficher les notifications avant de déverrouiller l\'appareil"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Non, merci"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Déplacer en bas à gauche"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Déplacer en bas à droite"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ignorer"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Accédez rapidement à vos chats"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Les nouveaux chats <xliff:g id="APP_NAME">%1$s</xliff:g> s\'afficheront sous forme de bulles. Appuyez sur une bulle pour l\'ouvrir. Faites-la glisser pour la déplacer.\n\nAppuyez sur la bulle"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Appuyez sur \"Gérer\" pour désactiver les bulles pour cette application"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigation système mise à jour. Pour apporter des modifications, accédez aux paramètres."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Accédez aux paramètres pour mettre à jour la navigation système"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Mode Veille imminent"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tout"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Impossible de charger toutes les commandes."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Autre"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-gl/strings.xml b/packages/SystemUI/res/values-gl/strings.xml
index e1e8c76..7711742 100644
--- a/packages/SystemUI/res/values-gl/strings.xml
+++ b/packages/SystemUI/res/values-gl/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> xestiona o teu perfil de traballo, que está conectado a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>. Esta aplicación pode controlar a túa actividade na rede, mesmo os correos electrónicos, as aplicacións e os sitios web.\n\nTamén estás conectado a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que pode controlar a túa actividade persoal na rede."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Desbloqueado por un axente de confianza"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"O dispositivo permanecerá bloqueado ata que o desbloquees manualmente"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Recibir notificacións máis rápido"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Consúltaas antes de desbloquear"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Non, grazas"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mover á parte infer. esquerda"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mover á parte inferior dereita"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ignorar"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Manter os chats á vista"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Os chats novos de <xliff:g id="APP_NAME">%1$s</xliff:g> mostraranse como burbullas. Toca unha para abrila ou arrástraa para movela.\n\nToca a burbulla"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Para desactivar as burbullas nesta aplicación, toca Xestionar"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Actualizouse a navegación do sistema. Para facer cambios, vai a Configuración."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Para actualizar a navegación do sistema, vai a Configuración"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Modo de espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Todo"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Non se puido cargar a lista de todos os controis."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Outra"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-gu/strings.xml b/packages/SystemUI/res/values-gu/strings.xml
index b16362b..cb09ac9 100644
--- a/packages/SystemUI/res/values-gu/strings.xml
+++ b/packages/SystemUI/res/values-gu/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"તમારી કાર્યાલયની પ્રોફાઇલ <xliff:g id="ORGANIZATION">%1$s</xliff:g> દ્વારા સંચાલિત થાય છે. આ પ્રોફાઇલ <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> સાથે કનેક્ટ કરેલ છે, જે ઇમેઇલ, ઍપ્લિકેશનો અને વેબસાઇટો સહિતની તમારી નેટવર્ક પ્રવૃત્તિનું નિયમન કરી શકે છે.\n\nતમે <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> સાથે પણ કનેક્ટ કરેલું છે, જે તમારી વ્યક્તિગત નેટવર્ક પ્રવૃત્તિનું નિયમન કરી શકે છે."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent દ્વારા અનલૉક રાખેલું"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"તમે ઉપકરણને મેન્યુઅલી અનલૉક કરશો નહીં ત્યાં સુધી તે લૉક રહેશે"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"વધુ ઝડપથી સૂચનાઓ મેળવો"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"તમે અનલૉક કરો તે પહેલાં તેમને જુઓ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ના, આભાર"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"નીચે ડાબે ખસેડો"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"નીચે જમણે ખસેડો"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"છોડી દો"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ચૅટને સૌથી પહેલાં રાખો"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>ની નવી ચૅટ બબલ તરીકે દેખાશે. બબલને ખોલવા માટે તેને ટૅપ કરો. તેને ખસેડવા માટે ખેંચો.\n\nબબલને ટૅપ કરો"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"આ ઍપમાંથી બબલને બંધ કરવા માટે મેનેજ કરો પર ટૅપ કરો"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"સિસ્ટમ નૅવિગેશન અપડેટ કર્યું. ફેરફારો કરવા માટે, સેટિંગ પર જાઓ."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"સિસ્ટમ નૅવિગેશનને અપડેટ કરવા માટે સેટિંગ પર જાઓ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"સ્ટૅન્ડબાય"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"ઝડપી નિયંત્રણો"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"નિયંત્રણો ઉમેરો"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"જેમાંથી નિયંત્રણો ઉમેરવા હોય તે ઍપ પસંદ કરો"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g> નિયંત્રણ ઉમેર્યું.</item>
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> નિયંત્રણો ઉમેર્યા.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"નિયંત્રણો"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"ઝડપી ઍક્સેસ માટેનાં નિયંત્રણો પસંદ કરો"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"મનપસંદ"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"તમામ"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"બધા નિયંત્રણોની સૂચિ લોડ કરી શકાઈ નથી."</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"અન્ય"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-hi/strings.xml b/packages/SystemUI/res/values-hi/strings.xml
index 3cb4c6f..4fd8310 100644
--- a/packages/SystemUI/res/values-hi/strings.xml
+++ b/packages/SystemUI/res/values-hi/strings.xml
@@ -92,7 +92,7 @@
<string name="screenrecord_description" msgid="1123231719680353736">"रिकॉर्ड करते समय, Android सिस्टम आपकी स्क्रीन पर दिखने वाली या चलाई जाने वाली संवेदनशील जानकारी को कैप्चर कर सकता है. इसमें पासवर्ड, पैसे चुकाने से जुड़ी जानकारी, फ़ोटो, मैसेज, और ऑडियो शामिल हैं."</string>
<string name="screenrecord_audio_label" msgid="6183558856175159629">"ऑडियो रिकॉर्ड करें"</string>
<string name="screenrecord_device_audio_label" msgid="9016927171280567791">"डिवाइस ऑडियो"</string>
- <string name="screenrecord_device_audio_description" msgid="4922694220572186193">"आपके डिवाइस से आने वाली आवाज़. जैसे कि संगीत, कॉल, और रिंगटोन"</string>
+ <string name="screenrecord_device_audio_description" msgid="4922694220572186193">"आपके डिवाइस से आने वाली आवाज़ जैसे कि संगीत, कॉल, और रिंगटोन"</string>
<string name="screenrecord_mic_label" msgid="2111264835791332350">"माइक्रोफ़ोन"</string>
<string name="screenrecord_device_audio_and_mic_label" msgid="1831323771978646841">"डिवाइस ऑडियो और माइक्रोफ़ोन"</string>
<string name="screenrecord_start" msgid="330991441575775004">"शुरू करें"</string>
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"आपकी वर्क प्रोफ़ाइल का प्रबंधन <xliff:g id="ORGANIZATION">%1$s</xliff:g> करता है. प्रोफ़ाइल <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> से कनेक्ट है, जो ईमेल, ऐप्लिकेशन और वेबसाइटों सहित आपकी नेटवर्क गतिविधि की निगरानी कर सकता है.\n\nआप <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> से भी कनेक्ट हैं, जो आपकी व्यक्तिगत नेटवर्क गतिविधि की निगरानी कर सकता है."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent की वजह से अनलॉक रखा गया है"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"जब तक कि आप मैन्युअल रूप से अनलॉक नहीं करते तब तक डिवाइस लॉक रहेगा"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"सूचनाएं ज़्यादा तेज़ी से पाएं"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">" उन्हें अनलॉक किए जाने से पहले देखें"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"रहने दें"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"बाईं ओर सबसे नीचे ले जाएं"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"सबसे नीचे दाईं ओर ले जाएं"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"खारिज करें"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"चैट को पहले से तैयार रखें"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> की नई चैट बबल्स की तरह दिखेंगी. इसे खोलने के लिए किसी बबल पर टैप करें. इसे एक जगह से दूसरी जगह ले जाने के लिए, खींचें और छोड़ें.\n\nबबल पर टैप करें"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"इस ऐप्लिकेशन पर बबल्स को बंद करने के लिए \'प्रबंधित करें\' पर टैप करें"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"सिस्टम नेविगेशन अपडेट हो गया. बदलाव करने के लिए \'सेटिंग\' पर जाएं."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"सिस्टम नेविगेशन अपडेट करने के लिए \'सेटिंग\' में जाएं"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"स्टैंडबाई"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"फटाफट नियंत्रण"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"कंट्राेल जोड़ें"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"वह ऐप्लिकेशन चुनें जिससे आप कंट्राेल जोड़ना चाहते हैं"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g> कंट्रोल जोड़ा गया.</item>
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> कंट्रोल जोड़े गए.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"कंट्राेल"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"झटपट ऐक्सेस पाने के लिए कंट्राेल चुनें"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"पसंदीदा"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"सभी"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"सभी कंट्रोल की सूची लोड नहीं हो सकी."</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"अन्य"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-hr/strings.xml b/packages/SystemUI/res/values-hr/strings.xml
index d648aeb..bb53802 100644
--- a/packages/SystemUI/res/values-hr/strings.xml
+++ b/packages/SystemUI/res/values-hr/strings.xml
@@ -561,6 +561,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Vašim radnim profilom upravlja organizacija <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profil je povezan s aplikacijom <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> koja može nadzirati vaše poslovne aktivnosti na mreži, uključujući e-poruke, aplikacije i web-lokacije.\n\nPovezani ste i s aplikacijom <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> koja može nadzirati vaše osobne aktivnosti na mreži."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Otključano održava TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Uređaj će ostati zaključan dok ga ručno ne otključate"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Primajte obavijesti brže"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Pogledajte ih prije otključavanja"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ne, hvala"</string>
@@ -984,12 +985,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Premjesti u donji lijevi kut"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Premjestite u donji desni kut"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Odbaci"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Isticanje chatova"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Novi chatovi iz aplikacije <xliff:g id="APP_NAME">%1$s</xliff:g> prikazat će se kao oblačići. Dodirnite oblačić da biste ga otvorili. Povucite da biste ga premjestili.\n\nDodirnite oblačić"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Dodirnite Upravljanje da biste isključili oblačiće iz ove aplikacije"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Ažurirana je navigacija sustavom. Možete je promijeniti u Postavkama."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Navigaciju sustavom možete ažurirati u Postavkama"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Stanje mirovanja"</string>
@@ -1010,4 +1008,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Sve"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Popis svih kontrola nije se učitao."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Drugo"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-hu/strings.xml b/packages/SystemUI/res/values-hu/strings.xml
index 03151ae..7d1159c 100644
--- a/packages/SystemUI/res/values-hu/strings.xml
+++ b/packages/SystemUI/res/values-hu/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Munkaprofilját a(z) <xliff:g id="ORGANIZATION">%1$s</xliff:g> kezeli. A profil csatlakozik a(z) <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> alkalmazáshoz, amely figyelheti az Ön hálózati tevékenységeit, beleértve az e-maileket, alkalmazásokat és webhelyeket.\n\nCsatlakoztatta továbbá a(z) <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> alkalmazást, amely figyelheti az Ön személyes hálózati tevékenységeit."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Feloldva tartva TrustAgent által"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Az eszköz addig zárolva marad, amíg kézileg fel nem oldja"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Gyorsabban megkaphatja az értesítéseket"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Már a képernyőzár feloldása előtt megtekintheti őket"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nem, köszönöm"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Áthelyezés le és balra"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Áthelyezés le és jobbra"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Elvetés"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"A csevegések előtérben tartása"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"A(z) <xliff:g id="APP_NAME">%1$s</xliff:g> alkalmazásból származó új csevegőüzenetek buborékként jelennek meg. A csevegés megnyitásához koppintson a buborékra. Az áthelyezéséhez húzza a buborékot a kívánt helyre.\n\nKoppintson a buborékra"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"A Kezelés gombra koppintva kapcsolhatja ki az alkalmazásból származó buborékokat"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"A rendszer-navigáció módja megváltozott. Módosításához nyissa meg a Beállításokat."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"A rendszer-navigációs lehetőségeket a Beállításokban módosíthatja"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Készenléti mód"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Összes"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Nem sikerült betölteni az összes vezérlő listáját."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Más"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-hy/strings.xml b/packages/SystemUI/res/values-hy/strings.xml
index d8728f5..3f44736 100644
--- a/packages/SystemUI/res/values-hy/strings.xml
+++ b/packages/SystemUI/res/values-hy/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Ձեր աշխատանքային պրոֆիլի կառավարիչն է <xliff:g id="ORGANIZATION">%1$s</xliff:g> կազմակերպությունը: Այն կապակցված է <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> հավելվածին, որը կարող է վերահսկել աշխատանքային ցանցում կատարած գործունեությունը, այդ թվում նաև էլփոստի հաշիվները, հավելվածները և կայքերը:\n\nԴուք կապակցված եք նաև <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> հավելվածին, որը կարող է վերահսկել անձնական ցանցում կատարած ձեր գործողությունները:"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Ապակողպվում է TrustAgent-ի միջոցով"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Սարքը կմնա արգելափակված՝ մինչև ձեռքով չբացեք"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Ավելի արագ ստացեք ծանուցումները"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Տեսեք դրանք մինչև ապակողպելը"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ոչ"</string>
@@ -1001,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Բոլորը"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Չհաջողվեց բեռնել բոլոր կառավարների ցանկը։"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Այլ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-in/strings.xml b/packages/SystemUI/res/values-in/strings.xml
index 012a16e..18728a1 100644
--- a/packages/SystemUI/res/values-in/strings.xml
+++ b/packages/SystemUI/res/values-in/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Profil kerja Anda dikelola oleh <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profil tersambung ke <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, yang dapat memantau aktivitas jaringan, termasuk email, aplikasi, dan situs.\n\nAnda juga tersambung ke <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, yang dapat memantau aktivitas jaringan pribadi."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Tetap terbuka kuncinya oleh TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Perangkat akan tetap terkunci hingga Anda membukanya secara manual"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Dapatkan pemberitahuan lebih cepat"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Lihat sebelum membuka kunci"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Tidak"</string>
@@ -1001,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Semua"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Daftar semua kontrol tidak dapat dimuat."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Lainnya"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-is/strings.xml b/packages/SystemUI/res/values-is/strings.xml
index 7542e3e..07b0d76 100644
--- a/packages/SystemUI/res/values-is/strings.xml
+++ b/packages/SystemUI/res/values-is/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Vinnusniðinu þínu er stýrt af <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Sniðið er tengt <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, sem getur fylgst með netnotkun þinni, þ. á m. tölvupósti, forritum og vefsvæðum\n\nÞú ert einnig með tengingu við <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, sem getur fylgst með persónulegri netnotkun þinni."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Haldið opnu af TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Tækið verður læst þar til þú opnar það handvirkt"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Fáðu tilkynningar hraðar"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Sjáðu þær áður en þú opnar"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nei, takk"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Færa neðst til vinstri"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Færðu neðst til hægri"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Hunsa"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Halda spjalli fyrir framan"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nýtt spjall úr <xliff:g id="APP_NAME">%1$s</xliff:g> birtist sem blöðrur. Ýttu á blöðru til að opna hana. Dragðu hana til að færa hana.\n\nÝttu á blöðruna"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Ýttu á „Stjórna“ til að slökkva á blöðrum frá þessu forriti"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Kerfisstjórnun uppfærð. Þú getur breytt þessu í stillingunum."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Farðu í stillingar til að uppfæra kerfisstjórnun"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Biðstaða"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Allt"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Ekki tókst að hlaða lista yfir allar stýringar."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Annað"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-it/strings.xml b/packages/SystemUI/res/values-it/strings.xml
index 65dc514..1c8bafd 100644
--- a/packages/SystemUI/res/values-it/strings.xml
+++ b/packages/SystemUI/res/values-it/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Il tuo profilo di lavoro è gestito da <xliff:g id="ORGANIZATION">%1$s</xliff:g> ed è collegato a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, da cui è possibile monitorare la tua attività di rete lavorativa, inclusi siti web, email e app.\n\nSei collegato anche a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, da cui è possibile monitorare la tua attività di rete personale."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Sbloccato da TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Il dispositivo resterà bloccato fino allo sblocco manuale"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Ricevi notifiche più velocemente"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Visualizza prima di sbloccare"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"No, grazie"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Sposta in basso a sinistra"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Sposta in basso a destra"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ignora"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Tieni davanti le chat"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Le nuove chat da <xliff:g id="APP_NAME">%1$s</xliff:g> verranno visualizzate come bolle. Tocca una bolla per aprirla. Trascinala per spostarla.\n\nTocca la bolla"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Tocca Gestisci per disattivare le bolle dall\'app"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigazione del sistema aggiornata. Per apportare modifiche, usa le Impostazioni."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Usa le Impostazioni per aggiornare la navigazione del sistema"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Standby"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tutti"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Impossibile caricare l\'elenco di tutti i controlli."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Altro"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-iw/strings.xml b/packages/SystemUI/res/values-iw/strings.xml
index 2a9d596..a798cfa 100644
--- a/packages/SystemUI/res/values-iw/strings.xml
+++ b/packages/SystemUI/res/values-iw/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"פרופיל העבודה שלך מנוהל על ידי <xliff:g id="ORGANIZATION">%1$s</xliff:g>. הפרופיל מחובר לאפליקציה <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, שיכולה לעקוב אחר הפעילות שלך ברשת, כולל הודעות אימייל, אפליקציות ואתרים.\n\nהפרופיל מחובר גם לאפליקציה <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, שיכולה לעקוב אחר הפעילות שלך ברשת."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"הנעילה נמנעת על ידי סביבה אמינה"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"המכשיר יישאר נעול עד שתבטל את נעילתו באופן ידני"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"קבלה מהירה של התראות"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"צפה בהן לפני שתבטל נעילה"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"לא, תודה"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"העברה לפינה השמאלית התחתונה"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"העברה לפינה הימנית התחתונה"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"סגירה"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"הצ\'אטים תמיד יוצגו מלפנים"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"צ\'אטים חדשים מאפליקציית <xliff:g id="APP_NAME">%1$s</xliff:g> יוצגו כבועות. יש להקיש על בועה כדי לפתוח אותה. יש לגרור אותה כדי להזיז אותה.\n\nיש להקיש על הבועה"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"יש להקיש על \'ניהול\' כדי להשבית את הבועות מהאפליקציה הזו"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"הניווט במערכת עודכן. אפשר לערוך שינויים דרך ההגדרות."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"יש לעבור להגדרות כדי לעדכן את הניווט במערכת"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"המתנה"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"הכול"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"לא ניתן היה לטעון את הרשימה של כל הפקדים."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"אחר"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ja/strings.xml b/packages/SystemUI/res/values-ja/strings.xml
index b4952ff..b62dae6 100644
--- a/packages/SystemUI/res/values-ja/strings.xml
+++ b/packages/SystemUI/res/values-ja/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"この仕事用プロファイルは<xliff:g id="ORGANIZATION">%1$s</xliff:g>によって管理され、<xliff:g id="APPLICATION_WORK">%2$s</xliff:g> に接続しています。このアプリはあなたの仕事のネットワーク アクティビティ(メール、アプリ、ウェブサイトなど)を管理できます。\n\nまた、<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> にも接続しているため、あなたの個人のネットワーク アクティビティも監視できます。"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"信頼エージェントがロック解除を管理"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"手動でロックを解除するまでロックされたままとなります"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"通知をすばやく確認できます"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ロックを解除する前にご確認ください"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"キャンセル"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"左下に移動"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"右下に移動"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"閉じる"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"チャットを常に前面に表示"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> からの新しいチャットがバブルとして表示されます。バブルをタップするとチャットが表示されます。ドラッグすると移動します。\n\nバブルをタップしてください"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"このアプリからのバブルをオフにするには、[管理] をタップしてください"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"システム ナビゲーションを更新しました。変更するには [設定] に移動してください。"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"システム ナビゲーションを更新するには [設定] に移動してください"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"スタンバイ"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"すべて"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"全コントロールの一覧を読み込めませんでした。"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"その他"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ka/strings.xml b/packages/SystemUI/res/values-ka/strings.xml
index 07b9e2a..8365673 100644
--- a/packages/SystemUI/res/values-ka/strings.xml
+++ b/packages/SystemUI/res/values-ka/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"თქვენს სამსახურის პროფილს მართავს <xliff:g id="ORGANIZATION">%1$s</xliff:g>. პროფილი დაკავშირებულია <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>-თან, რომელსაც შეუძლია ქსელში თქვენი სამსახურეობრივი აქტივობის (მათ შორის, ელფოსტის, აპებისა და ვებსაიტების) მონიტორინგი.\n\nგარდა ამისა, თქვენ დაკავშირებული ხართ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>-თან, რომელსაც ქსელში თქვენი პირადი აქტივობის მონიტორინგი შეუძლია."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"განბლოკილია TrustAgent-ის მიერ"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"მოწყობილობის დარჩება ჩაკეტილი, სანამ ხელით არ გახსნით"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"შეტყობინებების უფრო სწრაფად მიღება"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"იხილეთ განბლოკვამდე"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"არა, გმადლობთ"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ქვევით და მარცხნივ გადატანა"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"გადაანაცვ. ქვემოთ და მარჯვნივ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"დახურვა"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ჩეთები წინ იყოს"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>-ის ახალი ჩეთები ბუშტების სახით გამოჩნდება. გასახსნელად შეეხეთ ბუშტს. გადასატანად ჩაავლეთ.\n\nშეეხეთ ბუშტს"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ამ აპის ბუშტების გამოსართავად შეეხეთ „მართვას“"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"სისტემური ნავიგაცია განახლდა. ცვლილებების შესატანად გადადით პარამეტრებზე."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"სისტემური ნავიგაციის გასაახლებლად გადადით პარამეტრებზე"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"მოლოდინის რეჟიმი"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ყველა"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"მართვის ყველა საშუალების სია ვერ ჩაიტვირთა."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"სხვა"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-kk/strings.xml b/packages/SystemUI/res/values-kk/strings.xml
index d6391891..e7ca415 100644
--- a/packages/SystemUI/res/values-kk/strings.xml
+++ b/packages/SystemUI/res/values-kk/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Жұмыс профиліңізді <xliff:g id="ORGANIZATION">%1$s</xliff:g> басқарады. Бұл профиль жұмыс желісіндегі белсенділігіңізді, соның ішінде электрондық хабарларды, қолданбаларды және веб-сайттарды бақылай алатын <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> қолданбасына қосылған.\n\nСондай-ақ сіз жеке желідегі белсенділігіңізді бақылай алатын <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> қолданбасына қосылғансыз."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent арқылы құлпы ашылды."</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Қолмен бекітпесін ашқанша құрылғы бекітілген күйде қалады"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Хабарландыруларды тезірек алу"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Бекітпесін ашу алдында оларды көру"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Жоқ, рақмет"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Төменгі сол жаққа жылжыту"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Төменгі оң жаққа жылжыту"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Жабу"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Чаттарды жоғары жақтан көрсету"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> қолданбасындағы жаңа чаттар қалқымалы анықтамалар түрінде шығады. Қалқымалы анықтаманы ашу үшін оны түртіңіз. Оны сүйреп жылжытыңыз.\n\nҚалқымалы анықтаманы түртіңіз."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Бұл қолданбадан қалқымалы анықтамаларды өшіру үшін \"Басқару\" түймесін түртіңіз."</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Жүйе навигациясы жаңартылды. Өзгерту енгізу үшін \"Параметрлер\" бөліміне өтіңіз."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Жүйе навигациясын жаңарту үшін \"Параметрлер\" бөліміне өтіңіз."</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Күту режимі"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Барлығы"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Барлық басқару элементі тізімі жүктелмеді."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Басқа"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-km/strings.xml b/packages/SystemUI/res/values-km/strings.xml
index 8306dff..d8d300f 100644
--- a/packages/SystemUI/res/values-km/strings.xml
+++ b/packages/SystemUI/res/values-km/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"កម្រងព័ត៌មានការងាររបស់អ្នកស្ថិតក្រោមគ្រប់គ្រងរបស់ <xliff:g id="ORGANIZATION">%1$s</xliff:g> ។ កម្រងព័ត៌មាននេះត្រូវបានភ្ជាប់ទៅ <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ដែលអាចតាមដានសកម្មភាពបណ្តាញរបស់អ្នក រួមទាំងអ៊ីមែល កម្មវិធី និងគេហទំព័រផងដែរ។\n\nអ្នកក៏ត្រូវបានភ្ជាប់ទៅ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ដែលអាចតាមដានសកម្មភាពបណ្តាញផ្ទាល់ខ្លួនរបស់អ្នក។"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"បានដោះសោដោយភ្នាក់ងារទុកចិត្ត"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"ឧបករណ៍នឹងចាក់សោរហូតដល់អ្នកដោះសោដោយដៃ"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"ទទួលបានការជូនដំណឹងកាន់តែលឿន"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ឃើញពួកវាមុនពេលដោះសោ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ទេ អរគុណ!"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ផ្លាស់ទីទៅផ្នែកខាងក្រោមខាងឆ្វេង"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ផ្លាស់ទីទៅផ្នែកខាងក្រោមខាងស្ដាំ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ច្រានចោល"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"រក្សាទុកការជជែកនៅផ្នែកខាងមុខ"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"ការជជែកថ្មីៗពី <xliff:g id="APP_NAME">%1$s</xliff:g> នឹងបង្ហាញជាសារលេចឡើង។ ចុចសារលេចឡើង ដើម្បីបើកវា។ អូសដើម្បីផ្លាស់ទីសារលេចឡើងនេះ។\n\nចុចសារលេចឡើងនេះ"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ចុច \"គ្រប់គ្រង\" ដើម្បីបិទសារលេចឡើងពីកម្មវិធីនេះ"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"បានធ្វើបច្ចុប្បន្នភាពការរុករកក្នុងប្រព័ន្ធ។ ដើម្បីធ្វើការផ្លាស់ប្ដូរ សូមចូលទៅកាន់ការកំណត់។"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ចូលទៅកាន់ការកំណត់ ដើម្បីធ្វើបច្ចុប្បន្នភាពការរុករកក្នុងប្រព័ន្ធ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ផ្អាកដំណើរការ"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ទាំងអស់"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"មិនអាចផ្ទុកបញ្ជីនៃការគ្រប់គ្រងទាំងអស់បានទេ។"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ផ្សេងៗ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-kn/strings.xml b/packages/SystemUI/res/values-kn/strings.xml
index 880e083..0165b08 100644
--- a/packages/SystemUI/res/values-kn/strings.xml
+++ b/packages/SystemUI/res/values-kn/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"ನಿಮ್ಮ ಉದ್ಯೋಗ ಪ್ರೊಫೈಲ್ ಅನ್ನು <xliff:g id="ORGANIZATION">%1$s</xliff:g> ನಿರ್ವಹಿಸುತ್ತಿದೆ. <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ಗೆ ಪ್ರೊಫೈಲ್ ಸಂಪರ್ಕಗೊಂಡಿರುವ ಕಾರಣ, ಅದು ನಿಮ್ಮ ಇಮೇಲ್ಗಳು, ಅಪ್ಲಿಕೇಶನ್ಗಳು ಮತ್ತು ವೆಬ್ಸೈಟ್ಗಳೂ ಸೇರಿದಂತೆ ನೆಟ್ವರ್ಕ್ ಚಟುವಟಿಕೆಯನ್ನು ಮೇಲ್ವಿಚಾರಣೆ ಮಾಡಬಹುದು.\n\nನೀವು <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ಗೆ ಕೂಡಾ ಸಂಪರ್ಕಗೊಂಡಿದ್ದೀರಿ, ಇದು ನಿಮ್ಮ ವೈಯಕ್ತಿಕ ನೆಟ್ವರ್ಕ್ ಚಟುವಟಿಕೆಯನ್ನು ಮೇಲ್ವಿಚಾರಣೆ ಮಾಡಬಹುದು."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ನಿಂದ ಅನ್ಲಾಕ್ ಮಾಡಲಾಗಿದೆ"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"ನೀವಾಗಿಯೇ ಅನ್ಲಾಕ್ ಮಾಡುವವರೆಗೆ ಸಾಧನವು ಲಾಕ್ ಆಗಿಯೇ ಇರುತ್ತದೆ"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"ವೇಗವಾಗಿ ಅಧಿಸೂಚನೆಗಳನ್ನು ಪಡೆದುಕೊಳ್ಳಿ"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ನೀವು ಅನ್ಲಾಕ್ ಮಾಡುವ ಮೊದಲೇ ಅವುಗಳನ್ನು ನೋಡಿ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ಧನ್ಯವಾದಗಳು"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ಸ್ಕ್ರೀನ್ನ ಎಡ ಕೆಳಭಾಗಕ್ಕೆ ಸರಿಸಿ"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ಕೆಳಗಿನ ಬಲಭಾಗಕ್ಕೆ ಸರಿಸಿ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ವಜಾಗೊಳಿಸಿ"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ಚಾಟ್ಗಳನ್ನು ಮುಂಚೂಣಿಯಲ್ಲಿಡಿ"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> ನಿಂದ ಹೊಸ ಚಾಟ್ಗಳು ಬಬಲ್ಗಳಾಗಿ ಕಾಣಿಸುತ್ತದೆ. ಅದನ್ನು ತೆರೆಯಲು ಬಬಲ್ ಅನ್ನು ಟ್ಯಾಪ್ ಮಾಡಿ. ಅದನ್ನು ಸರಿಸಲು ಡ್ರ್ಯಾಗ್ ಮಾಡಿ.\n\nಬಬಲ್ ಅನ್ನು ಟ್ಯಾಪ್ ಮಾಡಿ"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ಈ ಆ್ಯಪ್ನಿಂದ ಬಬಲ್ಗಳನ್ನು ಆಫ್ ಮಾಡಲು ನಿರ್ವಹಿಸಿ ಟ್ಯಾಪ್ ಮಾಡಿ"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"ಸಿಸ್ಟಂ ನ್ಯಾವಿಗೇಷನ ಅಪ್ಡೇಟ್ ಮಾಡಲಾಗಿದೆ ಬದಲಾವಣೆಗಳನ್ನು ಮಾಡಲು, ಸೆಟ್ಟಿಂಗ್ಗಳಿಗೆ ಹೋಗಿ."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ಸಿಸ್ಟಂ ನ್ಯಾವಿಗೇಷನ್ ಅಪ್ಡೇಟ್ ಮಾಡಲು ಸೆಟ್ಟಿಂಗ್ಗಳಿಗೆ ಹೋಗಿ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ಸ್ಟ್ಯಾಂಡ್ಬೈ"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"ತ್ವರಿತ ನಿಯಂತ್ರಣಗಳು"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"ನಿಯಂತ್ರಣಗಳನ್ನು ಸೇರಿಸಿ"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"ನಿಯಂತ್ರಣಗಳನ್ನು ಸೇರಿಸಲು ಆ್ಯಪ್ ಅನ್ನು ಆಯ್ಕೆಮಾಡಿ"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g> ನಿಯಂತ್ರಣಗಳನ್ನು ಸೇರಿಸಲಾಗಿದೆ.</item>
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> ನಿಯಂತ್ರಣಗಳನ್ನು ಸೇರಿಸಲಾಗಿದೆ.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"ನಿಯಂತ್ರಣಗಳು"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"ತ್ವರಿತ ಪ್ರವೇಶಕ್ಕಾಗಿ ನಿಯಂತ್ರಣಗಳನ್ನು ಆಯ್ಕೆಮಾಡಿ"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"ಮೆಚ್ಚಿನವುಗಳು"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ಎಲ್ಲಾ"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"ಎಲ್ಲಾ ನಿಯಂತ್ರಣಗಳ ಪಟ್ಟಿಯನ್ನು ಲೋಡ್ ಮಾಡಲು ಆಗಲಿಲ್ಲ."</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ಇತರ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-ko/strings.xml b/packages/SystemUI/res/values-ko/strings.xml
index ca8cdb0..64f5ff8 100644
--- a/packages/SystemUI/res/values-ko/strings.xml
+++ b/packages/SystemUI/res/values-ko/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"직장 프로필은 <xliff:g id="ORGANIZATION">%1$s</xliff:g>에서 관리합니다. 이 프로필은 <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>에 연결되어 이메일, 앱, 웹사이트와 같은 직장 네트워크 활동을 모니터링할 수 있습니다.\n\n개인 네트워크 활동을 모니터링할 수 있는 <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>에도 연결됩니다."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent가 잠금 해제함"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"수동으로 잠금 해제할 때까지 기기가 잠금 상태로 유지됩니다."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"알림을 더욱 빠르게 받기"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"잠금 해제하기 전에 알림을 봅니다."</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"사용 안함"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"왼쪽 하단으로 이동"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"오른쪽 하단으로 이동"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"닫기"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"채팅을 항상 상단에 표시"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>의 새로운 채팅이 버블로 표시됩니다. 버블을 열려면 탭하세요. 버블을 이동하려면 드래그하세요.\n\n버블을 탭하세요."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"이 앱에서 버블을 사용 중지하려면 관리를 탭하세요."</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"시스템 탐색이 업데이트되었습니다. 변경하려면 설정으로 이동하세요."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"설정으로 이동하여 시스템 탐색을 업데이트하세요."</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"대기"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"전체"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"전체 컨트롤 목록을 로드할 수 없습니다."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"기타"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ky/strings.xml b/packages/SystemUI/res/values-ky/strings.xml
index 719380e..00d6699 100644
--- a/packages/SystemUI/res/values-ky/strings.xml
+++ b/packages/SystemUI/res/values-ky/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Жумуш профилиңизди <xliff:g id="ORGANIZATION">%1$s</xliff:g> башкарат. Ал электрондук почта, колдонмолор жана вебсайттар сыяктуу жумуш тармагыңыздагы аракеттерди көзөмөлдөй турган <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> колдонмосуна туташкан.\n\nМындан тышкары, тармактагы жеке аракеттериңизди көзөмөлдөгөн <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> колдонмосуна туташып турасыз."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Ишеним агенти кулпусун ачты"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Түзмөктүн кулпусу кол менен ачылмайынча кулпуланган бойдон алат"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Эскертмелерди тезирээк алуу"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Аларды кулпудан чыгараардан мурун көрүңүз"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Жок, рахмат"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Төмөнкү сол жакка жылдыруу"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Төмөнкү оң жакка жылдырыңыз"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Жабуу"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Маектерди ар дайым көрүп туруңуз"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> колдонмосундагы жаңы маектер калкып чыкма билдирмелер түрүндө көрүнөт. Аны ачуу үчүн калкып чыкма билдирмени таптап коюңуз. Аны сүйрөп жылдырыңыз.\n\nКалкып чыкма билдирмени таптап коюңуз"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Бул колдонмодогу калкып чыкма билдирмелерди өчүрүү үчүн \"Башкарууну\" басыңыз"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Тутум чабыттоосу жаңырды. Өзгөртүү үчүн, Жөндөөлөргө өтүңүз."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Тутум чабыттоосун жаңыртуу үчүн Жөндөөлөргө өтүңүз"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Көшүү режими"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Баары"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Бардык көзөмөлдөрдүн тизмеси жүктөлгөн жок."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Башка"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-land-television/dimens.xml b/packages/SystemUI/res/values-land-television/dimens.xml
new file mode 100644
index 0000000..499341c
--- /dev/null
+++ b/packages/SystemUI/res/values-land-television/dimens.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<resources>
+ <!-- Width of volume bar -->
+ <dimen name="volume_dialog_row_width">252dp</dimen>
+ <dimen name="volume_dialog_tap_target_size">36dp</dimen>
+</resources>
diff --git a/packages/SystemUI/res/values-lo/strings.xml b/packages/SystemUI/res/values-lo/strings.xml
index 1737e0c..c937001 100644
--- a/packages/SystemUI/res/values-lo/strings.xml
+++ b/packages/SystemUI/res/values-lo/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"ໂປຣໄຟລ໌ບ່ອນເຮັດວຽກຂອງທ່ານແມ່ນຖືກຈັດການໂດຍ <xliff:g id="ORGANIZATION">%1$s</xliff:g>. ໂປຣໄຟລ໌ບ່ອນເຮັດວຽກດັ່ງກ່າວເຊື່ອມຕໍ່ຫາ <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, ເຊິ່ງສາມາດຕິດຕາມການເຄື່ອນໄຫວເຄືອຂ່າຍຂອງທ່ານ, ຮວມທັງອີເມວ, ແອັບ ແລະ ເວັບໄຊໄດ້.\n\nນອກຈາກນັ້ນ, ທ່ານຍັງເຊື່ອມຕໍ່ຫາ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, ເຊິ່ງສາມາດຕິດຕາມການເຄື່ອນໄຫວເຄືອຂ່າຍສ່ວນຕົວຂອງທ່ານໄດ້."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"ປັອດລັອກປະໄວ້ໂດຍ TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Device will stay locked until you manually unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"ຮັບເອົາການແຈ້ງເຕືອນໄວຂຶ້ນ"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ເບິ່ງພວກມັນກ່ອນທ່ານຈະປົດລັອກ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ບໍ່, ຂອບໃຈ"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ຍ້າຍຊ້າຍລຸ່ມ"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ຍ້າຍຂວາລຸ່ມ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ປິດໄວ້"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ສະແດງການສົນທະນາໄວ້ໜ້າສະເໝີ"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"ການສົນທະນາໃໝ່ຈາກ <xliff:g id="APP_NAME">%1$s</xliff:g> ຈະປາກົດເປັນ bubble. ແຕະໃສ່ bubble ເພື່ອເປີດມັນ ລາກເພື່ອເປີດມັນ.\n\nແຕະໃສ່ bubble"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ແຕະຈັດການເພື່ອປິດ bubble ຈາກແອັບນີ້"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"ອັບເດດການນຳທາງລະບົບແລ້ວ. ເພື່ອປ່ຽນແປງ, ກະລຸນາໄປທີ່ການຕັ້ງຄ່າ."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ໄປທີ່ການຕັ້ງຄ່າເພື່ອອັບເດດການນຳທາງລະບົບ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ສະແຕນບາຍ"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ທັງໝົດ"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"ບໍ່ສາມາດໂຫຼດລາຍຊື່ການຄວບຄຸມທັງໝົດໄດ້."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ອື່ນໆ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-lt/strings.xml b/packages/SystemUI/res/values-lt/strings.xml
index 31fd57f..d498878 100644
--- a/packages/SystemUI/res/values-lt/strings.xml
+++ b/packages/SystemUI/res/values-lt/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Jūsų darbo profilį tvarko „<xliff:g id="ORGANIZATION">%1$s</xliff:g>“. Profilis susietas su programa „<xliff:g id="APPLICATION_WORK">%2$s</xliff:g>“, kuri gali stebėti jūsų tinklo veiklą, įskaitant el. laiškus, programas ir svetaines.\n\nTaip pat esate prisijungę prie programos „<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>“, kuri gali stebėti asmeninio tinklo veiklą."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Atrakinta taikant „TrustAgent“"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Įrenginys liks užrakintas, kol neatrakinsite jo neautomatiniu būdu"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Greičiau gaukite pranešimus"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Peržiūrėti prieš atrakinant"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ne, ačiū"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Perkelti į apačią kairėje"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Perkelti į apačią dešinėje"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Atmesti"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Rodyti pokalbius priekyje"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nauji pokalbiai iš programos „<xliff:g id="APP_NAME">%1$s</xliff:g>“ bus rodomi kaip debesėliai. Palieskite debesėlį, kad jį atidarytumėte. Nuvilkite, kad perkeltumėte.\n\nPalieskite debesėlį"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Palieskite „Tvarkyti“, kad išjungtumėte debesėlius šioje programoje"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Sistemos naršymo funkcijos atnaujintos. Jei norite pakeisti, eikite į skiltį „Nustatymai“."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Eikite į skiltį „Nustatymai“, kad atnaujintumėte sistemos naršymo funkcijas"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Budėjimo laikas"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Visi"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Nepavyko įkelti visų valdiklių sąrašo."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Kita"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-lv/strings.xml b/packages/SystemUI/res/values-lv/strings.xml
index 44e15cc..a25ae2a 100644
--- a/packages/SystemUI/res/values-lv/strings.xml
+++ b/packages/SystemUI/res/values-lv/strings.xml
@@ -561,6 +561,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Jūsu darba profilu pārvalda <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profils ir saistīts ar lietotni <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, kura var pārraudzīt jūsu tīklā veiktās darbības, tostarp saņemtos un nosūtītos e-pasta ziņojumus, instalētās lietotnes un apmeklētās tīmekļa vietnes.\n\nIr izveidots savienojums ar lietotni <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, kas var pārraudzīt jūsu tīklā veiktās privātās darbības, tostarp saņemtos un nosūtītos e-pasta ziņojumus, instalētās lietotnes un apmeklētās tīmekļa vietnes."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Bloķēšanu liedzis TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Ierīce būs bloķēta, līdz to manuāli atbloķēsiet."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Saņemiet paziņojumus ātrāk"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Skatiet tos pirms atbloķēšanas."</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nē"</string>
@@ -984,12 +985,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Pārvietot apakšpusē pa kreisi"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Pārvietot apakšpusē pa labi"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Nerādīt"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Sarunas priekšplānā"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Jaunas sarunas no lietotnes <xliff:g id="APP_NAME">%1$s</xliff:g> tiks parādītas kā burbuļi. Pieskarieties kādam burbulim, lai to atvērtu. Velciet, lai to pārvietotu.\n\nPieskarieties burbulim."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Pieskarieties pogai “Pārvaldīt”, lai izslēgtu burbuļus no šīs lietotnes."</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Sistēmas navigācija ir atjaunināta. Lai veiktu izmaiņas, atveriet iestatījumus."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Atveriet iestatījumus, lai atjauninātu sistēmas navigāciju"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Gaidstāve"</string>
@@ -1010,4 +1008,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Visas"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Nevarēja ielādēt sarakstu ar visām vadīklām."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Cita"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ml/strings.xml b/packages/SystemUI/res/values-ml/strings.xml
index 2e6f6f5..47b0558 100644
--- a/packages/SystemUI/res/values-ml/strings.xml
+++ b/packages/SystemUI/res/values-ml/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> ആണ് നിങ്ങളുടെ ഔദ്യോഗിക പ്രൊഫൈൽ മാനേജുചെയ്യുന്നത്. <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ആപ്പിലേക്ക് പ്രൊഫൈൽ കണക്റ്റുചെയ്തിരിക്കുന്നു, അതിന് ഇമെയിലുകൾ, ആപ്പുകൾ, വെബ്സൈറ്റുകൾ എന്നിവ ഉൾപ്പെടെ നിങ്ങളുടെ ഔദ്യോഗിക നെറ്റ്വർക്ക് ആക്റ്റിവിറ്റി നിരീക്ഷിക്കാനാകും.\n\n<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ആപ്പിലേക്കും നിങ്ങൾ കണക്റ്റുചെയ്തിരിക്കുന്നു, അതിന് നിങ്ങളുടെ വ്യക്തിഗത നെറ്റ്വർക്ക് ആക്റ്റിവിറ്റി നിരീക്ഷിക്കാനാകും."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ഉപയോഗിച്ച് അൺലോക്ക് ചെയ്തത്"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"നിങ്ങൾ സ്വമേധയാ അൺലോക്കുചെയ്യുന്നതുവരെ ഉപകരണം ലോക്കുചെയ്തതായി തുടരും"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"അറിയിപ്പുകൾ വേഗത്തിൽ സ്വീകരിക്കുക"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"അൺലോക്കുചെയ്യുന്നതിന് മുമ്പ് അവ കാണുക"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"വേണ്ട, നന്ദി"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ചുവടെ ഇടതുഭാഗത്തേക്ക് നീക്കുക"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ചുവടെ വലതുഭാഗത്തേക്ക് നീക്കുക"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ഡിസ്മിസ് ചെയ്യുക"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ചാറ്റുകൾ ഏറ്റവും ആദ്യം കാണുന്ന രീതിയിൽ വയ്ക്കുക"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> എന്നതിൽ നിന്നുള്ള പുതിയ ചാറ്റുകൾ ബബിളുകളായി ദൃശ്യമാവും. ഇത് തുറക്കാൻ ബബിൾ ടാപ്പ് ചെയ്യുക. ഇത് നീക്കാൻ വലിച്ചിടുക.\n\nബബിൾ ടാപ്പ് ചെയ്യുക"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ഈ ആപ്പിൽ നിന്നുള്ള ബബിളുകൾ ഓഫാക്കാൻ \'മാനേജ് ചെയ്യുക\' ടാപ്പ് ചെയ്യുക"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"സിസ്റ്റം നാവിഗേഷൻ അപ്ഡേറ്റ് ചെയ്തു. മാറ്റങ്ങൾ വരുത്താൻ ക്രമീകരണത്തിലേക്ക് പോവുക."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"സിസ്റ്റം നാവിഗേഷൻ അപ്ഡേറ്റ് ചെയ്യാൻ ക്രമീകരണത്തിലേക്ക് പോവുക"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"സ്റ്റാൻഡ്ബൈ"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"ദ്രുത നിയന്ത്രണങ്ങൾ"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"നിയന്ത്രണങ്ങൾ ചേർക്കുക"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"നിയന്ത്രണങ്ങൾ ചേർക്കാൻ ഒരു ആപ്പ് തിരഞ്ഞെടുക്കുക"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> നിയന്ത്രണങ്ങൾ ചേർത്തു.</item>
+ <item quantity="one"><xliff:g id="NUMBER_0">%s</xliff:g> നിയന്ത്രണം ചേർത്തു.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"നിയന്ത്രണങ്ങൾ"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"അതിവേഗ ആക്സസിനുള്ള നിയന്ത്രണങ്ങൾ തിരഞ്ഞെടുക്കുക"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"പ്രിയപ്പെട്ടവ"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"എല്ലാം"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"എല്ലാ നിയന്ത്രണങ്ങളുടെയും ലിസ്റ്റ് ലോഡ് ചെയ്യാനായില്ല."</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"മറ്റുള്ളവ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-mn/strings.xml b/packages/SystemUI/res/values-mn/strings.xml
index ea93816..247a81d 100644
--- a/packages/SystemUI/res/values-mn/strings.xml
+++ b/packages/SystemUI/res/values-mn/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Таны ажлын профайлыг <xliff:g id="ORGANIZATION">%1$s</xliff:g> удирддаг. Энэ нь таны имэйл, апп, вэб хуудас зэрэг сүлжээний үйл ажиллагааг хянах боломжтой <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>-тай холбогдсон. \n\nМөн таны сүлжээний хувийн үйл ажиллагааг хянах боломжтой <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>-д холбогдсон байна."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent-р түгжээгүй байлгасан"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Таныг гараар нээх хүртэл төхөөрөмж түгжээтэй байх болно"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Мэдэгдлийг хурдан авах"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Түгжээг тайлахын өмнө үзнэ үү"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Үгүй"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Зүүн доош зөөх"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Баруун доош зөөх"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Үл хэрэгсэх"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Чатуудыг дэлгэцийн дээд талд байлгах"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>-н шинэ чатууд нь бөмбөлөг маягаар харагдана. Бөмбөлгийг нээхийн тулд түүнийг товшино уу. Түүнийг зөөхийн тулд чирнэ үү.\n\nБөмбөлгийг товшино уу"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Энэ аппын бөмбөлгүүдийг унтраахын тулд Удирдах дээр товшино уу"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Системийн навигацыг шинэчиллээ. Өөрчлөхийн тулд Тохиргоо руу очно уу."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Системийн навигацыг шинэчлэхийн тулд Тохиргоо руу очно уу"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Зогсолтын горим"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Бүх"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Бүх хяналтын жагсаалтыг ачаалж чадсангүй."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Бусад"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-mr/strings.xml b/packages/SystemUI/res/values-mr/strings.xml
index 3c7e18e..118627a 100644
--- a/packages/SystemUI/res/values-mr/strings.xml
+++ b/packages/SystemUI/res/values-mr/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"तुमचे कार्य प्रोफाइल <xliff:g id="ORGANIZATION">%1$s</xliff:g> द्वारे व्यवस्थापित केले जाते. प्रोफाइल <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> शी कनेक्ट केले आहे, जे ईमेल, अॅप्स आणि वेबसाइटसह आपल्या कार्य नेटवर्क क्रियाकलापाचे परीक्षण करू शकते.\n\nतुम्ही <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> शीदेखील कनेक्ट केले आहे, जे आपल्या वैयक्तिक नेटवर्क क्रियाकलापाचे परीक्षण करू शकते."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ने अनलॉक ठेवले"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"तुम्ही मॅन्युअली अनलॉक करेपर्यंत डिव्हाइस लॉक राहील"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"सूचना अधिक जलद मिळवा"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"तुम्ही अनलॉक करण्यापूर्वी त्यांना पहा"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"नाही, नको"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"तळाशी डावीकडे हलवा"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"तळाशी उजवीकडे हलवा"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"डिसमिस करा"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"चॅट दिसतील असे ठेवा"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> वरील नवीन चॅट बुडबुडे म्हणून दिसतील. बुडबुडे उघडण्यासाठी त्यावर टॅप करा. तो हलवण्यासाठी ड्रॅग करा.\n\nबुडबुड्यावर टॅप करा"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"या अॅपमधून बुडबुडे बंद करण्यासाठी व्यवस्थापित करा वर टॅप करा"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"सिस्टम नेव्हिगेशन अपडेट केले. बदल करण्यासाठी, सेटिंग्जवर जा."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"सिस्टम नेव्हिगेशन अपडेट करण्यासाठी सेटिंग्जवर जा"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"स्टँडबाय"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"क्विक नियंत्रणे"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"नियंत्रणे जोडा"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"ज्यामधून नियंत्रणे जोडायची आहेत ते ॲप निवडा"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> नियंत्रणे जोडली.</item>
+ <item quantity="one"><xliff:g id="NUMBER_0">%s</xliff:g> नियंत्रण जोडले.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"नियंत्रणे"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"झटपट अॅक्सेससाठी नियंत्रणे निवडा"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"आवडते"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"सर्व"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"सर्व नियंत्रणांची सूची लोड करता आली नाही."</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"इतर"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-ms/strings.xml b/packages/SystemUI/res/values-ms/strings.xml
index 6d266737..454ebfb 100644
--- a/packages/SystemUI/res/values-ms/strings.xml
+++ b/packages/SystemUI/res/values-ms/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Profil kerja anda diurus oleh <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profil itu dihubungkan ke <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, yang boleh memantau aktiviti rangkaian kerja anda, termasuk e-mel, apl dan tapak web.\n\nAnda turut dihubungkan ke <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, yang boleh memantau aktiviti rangkaian peribadi anda."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Dibiarkan tidak berkunci oleh TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Peranti akan kekal terkunci sehingga anda membuka kunci secara manual"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Dapatkan pemberitahuan lebih cepat"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Lihat sebelum anda membuka kunci"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Tidak"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Alihkan ke bawah sebelah kiri"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Alihkan ke bawah sebelah kanan"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ketepikan"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Pastikan sembang sentiasa di hadapan"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Sembang baharu daripada <xliff:g id="APP_NAME">%1$s</xliff:g> akan dipaparkan sebagai gelembung. Ketik gelembung untuk membuka. Seret untuk mengalihkan gelembung.\n\nKetik gelembung itu"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Ketik Urus untuk mematikan gelembung daripada apl ini"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigasi sistem dikemas kini. Untuk membuat perubahan, pergi ke Tetapan."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Pergi ke Tetapan untuk mengemas kini navigasi sistem"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Tunggu sedia"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Semua"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Senarai semua kawalan tidak dapat dimuatkan."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Lain-lain"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-my/strings.xml b/packages/SystemUI/res/values-my/strings.xml
index dd3e6c1..c65f949 100644
--- a/packages/SystemUI/res/values-my/strings.xml
+++ b/packages/SystemUI/res/values-my/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"သင်၏ အလုပ်ပရိုဖိုင်ကို <xliff:g id="ORGANIZATION">%1$s</xliff:g> က စီမံခန့်ခွဲထားသည်။ ပရိုဖိုင်သည် အီးမေး၊ အက်ပ်နှင့် ဝဘ်ဆိုက်များအပါအဝင် သင်၏ကွန်ရက် လုပ်ဆောင်ချက်များကို စောင့်ကြည့်နိုင်သည့် <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> သို့ ချိတ်ဆက်ထားပါသည်။\n\nသင်၏ ကိုယ်ရေးကိုယ်တာ ကွန်ရက်လုပ်ဆောင်ချက်များကို စောင့်ကြည့်နိုင်သည့် <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> သို့လည်း ချိတ်ဆက်ထားပါသည်။"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ဖြင့် ဆက်ဖွင့်ထားရန်"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"သင်က လက်ဖြင့် သော့မဖွင့်မချင်း ကိရိယာမှာ သော့ပိတ်လျက် ရှိနေမည်"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"အကြောင်းကြားချက်များ မြန်မြန်ရရန်"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"မဖွင့်ခင် ၎င်းတို့ကို ကြည့်ပါ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"မလိုအပ်ပါ"</string>
@@ -1001,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"အားလုံး"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"ထိန်းချုပ်မှုအားလုံး၏ စာရင်းကို ဖွင့်၍မရပါ။"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"အခြား"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-nb/strings.xml b/packages/SystemUI/res/values-nb/strings.xml
index 5743215..d8f6294 100644
--- a/packages/SystemUI/res/values-nb/strings.xml
+++ b/packages/SystemUI/res/values-nb/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Jobbprofilen din administreres av <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profilen er koblet til <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, som kan overvåke nettverksaktiviteten din på jobben, inkludert e-poster, apper og nettsteder.\n\nDu er også koblet til <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, som kan overvåke den personlige nettverksaktiviteten din."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Holdes opplåst med TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Enheten forblir låst til du låser den opp manuelt"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Motta varsler raskere"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Se dem før du låser opp"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nei takk"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Flytt til nederst til venstre"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Flytt til nederst til høyre"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Avvis"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Ha chatter i forgrunnen"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nye chatter fra <xliff:g id="APP_NAME">%1$s</xliff:g> vises som bobler. Trykk på en boble for å åpne den. Dra for å flytte den.\n\nTrykk på boblen"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Trykk på Administrer for å slå av bobler for denne appen"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Systemnavigeringen er oppdatert. For å gjøre endringer, gå til Innstillinger."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Gå til Innstillinger for å oppdatere systemnavigeringen"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Ventemodus"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Alle"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Listen over alle kontroller kunne ikke lastes inn."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Annet"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ne/strings.xml b/packages/SystemUI/res/values-ne/strings.xml
index ef80cdc..73564a1 100644
--- a/packages/SystemUI/res/values-ne/strings.xml
+++ b/packages/SystemUI/res/values-ne/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> ले तपाईंको कार्य प्रोफाइलको व्यवस्थापन गर्छ। उक्त प्रोफाइल तपाईंका इमेल, अनुप्रयोग र वेवसाइटहरू लगायत तपाईंको नेटवर्कको गतिविधिको अनुगमन गर्नसक्ने <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> मा जडान छ। \n\nतपाईं आफ्नो व्यक्तिगत नेटवर्कको गतिविधिको अनुगमन गर्नसक्ने <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> मा पनि जडान हुनुहुन्छ।"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ले खुला राखेको"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"तपाईँले नखोले सम्म उपकरण बन्द रहनेछ"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"छिटो सूचनाहरू प्राप्त गर्नुहोस्"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"तपाईँले अनलक गर्नअघि तिनीहरूलाई हेर्नुहोस्"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"धन्यवाद पर्दैन"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"पुछारमा बायाँतिर सार्नुहोस्"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"पुछारमा दायाँतिर सार्नुहोस्"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"हटाउनुहोस्"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"कुराकानीलाई अग्रभूमिमा राख्नुहोस्"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> का नयाँ कुराकानीहरू बबलका रूपमा देखा पर्ने छन्। बबल खोल्न त्यसमा ट्याप गर्नुहोस्। बबल सार्न त्यसलाई घिसार्नुहोस्।\n\nबबलमा ट्याप गर्नुहोस्"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"यो अनुप्रयोगमा बबल निष्क्रिय पार्न व्यवस्थापन गर्नुहोस् नामक बटन ट्याप गर्नुहोस्"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"प्रणालीको नेभिगेसन अद्यावधिक गरियो। परिवर्तन गर्न सेटिङमा जानुहोस्।"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"प्रणालीको नेभिगेसन अद्यावधिक गर्न सेटिङमा जानुहोस्"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"स्ट्यान्डबाई"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"द्रुत नियन्त्रणहरू"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"नियन्त्रणहरू थप्नुहोस्"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"नियन्त्रणहरू जुन अनुप्रयोगबाट थप्ने हो त्यो अनुप्रयोग छनौट गर्नुहोस्"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> वटा नियन्त्र थपियो।</item>
+ <item quantity="one"><xliff:g id="NUMBER_0">%s</xliff:g> नियन्त्र थपियो</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"नियन्त्रणहरू"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"द्रुत पहुँचका लागि नियन्त्रणहरू छनौट गर्नुहोस्"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"मन पर्ने कुराहरू"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"सबै"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"सबै नियन्त्रणहरूको सूची लोड गर्न सकिएन।"</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"अन्य"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-nl/strings.xml b/packages/SystemUI/res/values-nl/strings.xml
index ae9b829..86f0f8f 100644
--- a/packages/SystemUI/res/values-nl/strings.xml
+++ b/packages/SystemUI/res/values-nl/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Je werkprofiel wordt beheerd door <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Het profiel is verbonden met <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, waarmee je werkgerelateerde netwerkactiviteit (waaronder e-mails, apps en websites) kan worden bijgehouden.\n\nJe bent ook verbonden met <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, waarmee je persoonlijke netwerkactiviteit kan worden bijgehouden."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Ontgrendeld gehouden door TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Het apparaat blijft vergrendeld totdat u het handmatig ontgrendelt"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Sneller meldingen ontvangen"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Weergeven voordat u ontgrendelt"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nee, bedankt"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Naar linksonder verplaatsen"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Naar rechtsonder verplaatsen"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Sluiten"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Chats op de voorgrond houden"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nieuwe chats van <xliff:g id="APP_NAME">%1$s</xliff:g> worden weergegeven als bubbels. Tik op een bubbel om deze te openen. Sleep om deze te verplaatsen.\n\nTik op de bubbel"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Tik op Beheren om bubbels van deze app uit te schakelen"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Systeemnavigatie geüpdatet. Als je wijzigingen wilt aanbrengen, ga je naar Instellingen."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Ga naar Instellingen om de systeemnavigatie te updaten"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Stand-by"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Alle"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Kan lijst met alle bedieningselementen niet laden."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Overig"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-or/strings.xml b/packages/SystemUI/res/values-or/strings.xml
index 9aad495..f46036e 100644
--- a/packages/SystemUI/res/values-or/strings.xml
+++ b/packages/SystemUI/res/values-or/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"ଆପଣଙ୍କ ୱର୍କ ପ୍ରୋଫାଇଲ୍ <xliff:g id="ORGANIZATION">%1$s</xliff:g> ଦ୍ୱାରା ପରିଚାଳନା କରାଯାଉଛି। ପ୍ରୋଫାଇଲଟି <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ସହ ସଂଯୁକ୍ତ ଅଛି, ଯାହା ଇମେଲ୍, ଆପ୍ ଓ ୱେବସାଇଟ୍ ସମେତ ଆପଣଙ୍କ ନେଟୱର୍କ ଗତିବିଧିକୁ ନିରୀକ୍ଷଣ କରିପାରେ।\n\nଆପଣ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>ରେ ମଧ୍ୟ ସଂଯୁକ୍ତ, ଯାହା ଆପଣଙ୍କ ବ୍ୟକ୍ତିଗତ ନେଟୱର୍କ ଗତିବିଧିକୁ ନିରୀକ୍ଷଣ କରିପାରେ।"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ଦ୍ୱାରା ଅନ୍ଲକ୍ ରହିଛି"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"ଯେତେବେଳ ପର୍ଯ୍ୟନ୍ତ ଆପଣ ମାନୁଆଲୀ ଅନଲକ୍ କରିନାହାନ୍ତି, ସେତେବେଳ ପର୍ଯ୍ୟନ୍ତ ଡିଭାଇସ୍ ଲକ୍ ରହିବ"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"ବିଜ୍ଞପ୍ତିକୁ ଶୀଘ୍ର ପ୍ରାପ୍ତ କରନ୍ତୁ"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ଅନଲକ୍ କରିବା ପୁର୍ବରୁ ସେମାନଙ୍କୁ ଦେଖନ୍ତୁ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ନାହିଁ, ଥାଉ"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ତଳ ବାମକୁ ନିଅନ୍ତୁ"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ତଳ ଡାହାଣକୁ ନିଅନ୍ତୁ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ଖାରଜ କରନ୍ତୁ"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ଚାଟଗୁଡ଼ିକ ଆଗ ପଟେ ରଖନ୍ତୁ"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g>ର ନୂଆ ଚାଟଗୁଡ଼ିକ ବବଲ୍ ଭାବରେ ଦେଖାଯିବ। ଏହାକୁ ଖୋଲିବା ପାଇଁ ଏକ ବବଲରେ ଟାପ୍ କରନ୍ତୁ। ଏହାକୁ ମୁଭ୍ କରିବା ପାଇଁ ଟାଣନ୍ତୁ। \n\nବବଲରେ ଟାପ୍ କରନ୍ତୁ"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ଏହି ଆପର ବବଲଗୁଡ଼ିକ ବନ୍ଦ କରିବା ପାଇଁ \'ପରିଚାଳନା କରନ୍ତୁ\' ବଟନରେ ଟାପ୍ କରନ୍ତୁ"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"ସିଷ୍ଟମ୍ ନାଭିଗେସନ୍ ଅପ୍ଡେଟ୍ ହୋଇଛି। ପରିବର୍ତ୍ତନ କରିବା ପାଇଁ, ସେଟିଂସ୍କୁ ଯାଆନ୍ତୁ।"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ସିଷ୍ଟମ୍ ନାଭିଗେସନ୍ ଅପ୍ଡେଟ୍ କରିବା ପାଇଁ ସେଟିଂସ୍କୁ ଯାଆନ୍ତୁ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ଷ୍ଟାଣ୍ଡବାଏ"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"ଦ୍ରୁତ ନିୟନ୍ତ୍ରଣଗୁଡ଼ିକ"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"ନିୟନ୍ତ୍ରଣଗୁଡ଼ିକ ଯୋଗ କରନ୍ତୁ"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"କେଉଁ ଆପରୁ ନିୟନ୍ତ୍ରଣଗୁଡ଼ିକ ଯୋଗ କରିବେ ତାହା ଚୟନ କରନ୍ତୁ"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g>ଟି ନିୟନ୍ତ୍ରଣ ଯୋଗ କରାଯାଇଛି।</item>
+ <item quantity="one"><xliff:g id="NUMBER_0">%s</xliff:g>ଟି ନିୟନ୍ତ୍ରଣ ଯୋଗ କରାଯାଇଛି।</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"ନିୟନ୍ତ୍ରଣଗୁଡ଼ିକ"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"ଶୀଘ୍ର ଆକ୍ସେସ୍ ପାଇଁ ନିୟନ୍ତ୍ରଣଗୁଡ଼ିକୁ ଚୟନ କରନ୍ତୁ"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"ପସନ୍ଦଗୁଡ଼ିକ"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ସବୁ"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"ସବୁ ନିୟନ୍ତ୍ରଣର ତାଲିକା ଲୋଡ୍ କରିପାରିଲା ନାହିଁ।"</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ଅନ୍ୟ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-pa/strings.xml b/packages/SystemUI/res/values-pa/strings.xml
index cbd278e..3a43f0f 100644
--- a/packages/SystemUI/res/values-pa/strings.xml
+++ b/packages/SystemUI/res/values-pa/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"ਤੁਹਾਡੇ ਕਾਰਜ ਪ੍ਰੋਫਾਈਲ ਦਾ ਪ੍ਰਬੰਧਨ <xliff:g id="ORGANIZATION">%1$s</xliff:g> ਵੱਲੋਂ ਕੀਤਾ ਜਾਂਦਾ ਹੈ। ਪ੍ਰੋਫਾਈਲ <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ਨਾਲ ਕਨੈਕਟ ਕੀਤਾ ਗਿਆ ਹੈ, ਜੋ ਈਮੇਲਾਂ, ਐਪਾਂ, ਅਤੇ ਵੈੱਬਸਾਈਟਾਂ ਸਮੇਤ ਤੁਹਾਡੀ ਕਾਰਜ ਨੈੱਟਵਰਕ ਸਰਗਰਮੀ ਦੀ ਨਿਗਰਾਨੀ ਕਰ ਸਕਦੀ ਹੈ।\n\nਤੁਸੀਂ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ਨਾਲ ਵੀ ਕਨੈਕਟ ਹੋਂ, ਜੋ ਤੁਹਾਡੀ ਨਿੱਜੀ ਨੈੱਟਵਰਕ ਸਰਗਰਮੀ ਦੀ ਨਿਗਰਾਨੀ ਕਰ ਸਕਦੀ ਹੈ।"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"ਟਰੱਸਟ-ਏਜੰਟ ਵੱਲੋਂ ਅਣਲਾਕ ਰੱਖਿਆ ਗਿਆ"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"ਡੀਵਾਈਸ ਲਾਕ ਰਹੇਗਾ ਜਦੋਂ ਤੱਕ ਤੁਸੀਂ ਮੈਨੂਅਲੀ ਅਣਲਾਕ ਨਹੀਂ ਕਰਦੇ"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"ਤੇਜ਼ੀ ਨਾਲ ਸੂਚਨਾਵਾਂ ਪ੍ਰਾਪਤ ਕਰੋ"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ਅਣਲਾਕ ਕਰਨ ਤੋਂ ਪਹਿਲਾਂ ਉਹਨਾਂ ਨੂੰ ਦੇਖੋ"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ਨਹੀਂ ਧੰਨਵਾਦ"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ਹੇਠਾਂ ਵੱਲ ਖੱਬੇ ਲਿਜਾਓ"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ਹੇਠਾਂ ਵੱਲ ਸੱਜੇ ਲਿਜਾਓ"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ਖਾਰਜ ਕਰੋ"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"ਚੈਟਾਂ ਨੂੰ ਪਹਿਲਾਂ ਤੋਂ ਤਿਆਰ ਰੱਖੋ"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> ਦੀਆਂ ਨਵੀਆਂ ਚੈਟਾਂ ਬੁਲਬੁਲਿਆਂ ਵਾਂਗ ਦਿਸਣਗੀਆਂ। ਇਸ ਨੂੰ ਖੋਲ੍ਹਣ ਲਈ ਕਿਸੇ ਬੁਲਬੁਲੇ \'ਤੇ ਟੈਪ ਕਰੋ। ਇਸ ਨੂੰ ਇੱਕ ਥਾਂ ਤੋਂ ਦੂਜੀ ਥਾਂ \'ਤੇ ਲਿਜਾਣ ਲਈ ਘਸੀਟੋ।\n\nਬੁਲਬੁਲੇ \'ਤੇ ਟੈਪ ਕਰੋ"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ਇਸ ਐਪ \'ਤੇ ਬੁਲਬੁਲੇ ਬੰਦ ਕਰਨ ਲਈ \'ਪ੍ਰਬੰਧਨ ਕਰੋ\' \'ਤੇ ਟੈਪ ਕਰੋ"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"ਸਿਸਟਮ ਨੈਵੀਗੇਸ਼ਨ ਅੱਪਡੇਟ ਹੋ ਗਿਆ। ਤਬਦੀਲੀਆਂ ਕਰਨ ਲਈ, ਸੈਟਿੰਗਾਂ \'ਤੇ ਜਾਓ।"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ਸਿਸਟਮ ਨੈਵੀਗੇਸ਼ਨ ਨੂੰ ਅੱਪਡੇਟ ਕਰਨ ਲਈ ਸੈਟਿੰਗਾਂ \'ਤੇ ਜਾਓ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"ਸਟੈਂਡਬਾਈ"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"ਤਤਕਾਲ ਕੰਟਰੋਲ"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"ਕੰਟਰੋਲ ਸ਼ਾਮਲ ਕਰੋ"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"ਉਹ ਐਪ ਚੁਣੋ ਜਿੱਥੋਂ ਕੰਟਰੋਲ ਸ਼ਾਮਲ ਕਰਨੇ ਹਨ"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="one"><xliff:g id="NUMBER_1">%s</xliff:g> ਕੰਟਰੋਲ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ।</item>
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> ਕੰਟਰੋਲ ਸ਼ਾਮਲ ਕੀਤੇ ਗਏ।</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"ਕੰਟਰੋਲ"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"ਤਤਕਾਲ ਪਹੁੰਚ ਲਈ ਕੰਟਰੋਲ ਚੁਣੋ"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"ਮਨਪਸੰਦ"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ਸਭ"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"ਸਾਰੇ ਕੰਟਰੋਲਾਂ ਦੀ ਸੂਚੀ ਨੂੰ ਲੋਡ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਿਆ।"</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ਹੋਰ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-pl/strings.xml b/packages/SystemUI/res/values-pl/strings.xml
index ad54bc9..1bbe80a 100644
--- a/packages/SystemUI/res/values-pl/strings.xml
+++ b/packages/SystemUI/res/values-pl/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Organizacja <xliff:g id="ORGANIZATION">%1$s</xliff:g> zarządza Twoim profilem do pracy. Profil jest połączony z aplikacją <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, która może monitorować Twoją aktywność w sieci, w tym e-maile, aplikacje i strony internetowe.\n\nMasz też połączenie z aplikacją <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, która może monitorować Twoją osobistą aktywność w sieci."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Blokada anulowana przez agenta zaufania"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Urządzenie pozostanie zablokowane, aż odblokujesz je ręcznie"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Szybszy dostęp do powiadomień"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Zobacz powiadomienia, jeszcze zanim odblokujesz ekran"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nie, dziękuję"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Przenieś w lewy dolny róg"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Przenieś w prawy dolny róg"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Zamknij"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Wyświetlaj czaty na wierzchu"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nowe czaty z aplikacji <xliff:g id="APP_NAME">%1$s</xliff:g> będą pojawiać się jako dymki. Kliknij dymek, aby go otworzyć. Przeciągnij dymek, jeśli chcesz go przenieść.\n\nKliknij dymek"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Kliknij Zarządzaj, aby wyłączyć dymki z tej aplikacji"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Nawigacja w systemie została zaktualizowana. Aby wprowadzić zmiany, otwórz Ustawienia."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Otwórz Ustawienia, by zaktualizować nawigację w systemie"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Tryb gotowości"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Wszystko"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Nie udało się wczytać listy elementów sterujących."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Inne"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-pt-rBR/strings.xml b/packages/SystemUI/res/values-pt-rBR/strings.xml
index 300461d..61ac664 100644
--- a/packages/SystemUI/res/values-pt-rBR/strings.xml
+++ b/packages/SystemUI/res/values-pt-rBR/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Seu perfil de trabalho é gerenciado por <xliff:g id="ORGANIZATION">%1$s</xliff:g>. O perfil está conectado a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, que pode monitorar sua atividade profissional de rede, incluindo e-mails, apps e websites.\n\nVocê também está conectado a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que pode monitorar sua atividade pessoal de rede."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Desbloqueado pelo TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"O dispositivo permanecerá bloqueado até que você o desbloqueie manualmente"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Receba notificações mais rápido"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Veja-as antes de desbloquear"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Não, obrigado"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mover para canto inferior esquerdo"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mover para canto inferior direito"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Dispensar"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Manter chats em primeiro plano"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Novos chats do app <xliff:g id="APP_NAME">%1$s</xliff:g> aparecerão como balões. Toque em um balão para abrir o chat. Arraste para mover.\n\nToque no balão"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Toque em \"Gerenciar\" para desativar os balões desse app"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navegação no sistema atualizada. Se quiser alterá-la, acesse as configurações."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Acesse as configurações para atualizar a navegação no sistema"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Em espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Todos"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Não foi possível carregar a lista de controles."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Outro"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-pt-rPT/strings.xml b/packages/SystemUI/res/values-pt-rPT/strings.xml
index 9d7fb35..199da15 100644
--- a/packages/SystemUI/res/values-pt-rPT/strings.xml
+++ b/packages/SystemUI/res/values-pt-rPT/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"O seu perfil de trabalho é gerido pela <xliff:g id="ORGANIZATION">%1$s</xliff:g>. O perfil está associado à aplicação <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, que pode monitorizar a atividade da rede de trabalho, incluindo emails, aplicações e Sites.\n\nTambém está associado à aplicação <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que pode monitorizar a atividade da rede pessoal."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Mantido desbloqueado pelo TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"O dispositivo permanecerá bloqueado até ser desbloqueado manualmente"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Receber notificações mais rapidamente"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Ver antes de desbloquear"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Não, obrigado"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mover p/ parte infer. esquerda"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mover parte inferior direita"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ignorar"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Mantenha os chats em primeiro plano"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Os novos chats da app <xliff:g id="APP_NAME">%1$s</xliff:g> serão apresentados como balões. Toque num balão para o abrir. Arraste para o mover.\n\nToque no balão."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Toque em Gerir para desativar os balões desta app."</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"A navegação no sistema foi atualizada. Para efetuar alterações, aceda às Definições."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Aceda às Definições para atualizar a navegação no sistema."</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Modo de espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tudo"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Não foi possível carregar a lista dos controlos."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Outro"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml
index 300461d..61ac664 100644
--- a/packages/SystemUI/res/values-pt/strings.xml
+++ b/packages/SystemUI/res/values-pt/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Seu perfil de trabalho é gerenciado por <xliff:g id="ORGANIZATION">%1$s</xliff:g>. O perfil está conectado a <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, que pode monitorar sua atividade profissional de rede, incluindo e-mails, apps e websites.\n\nVocê também está conectado a <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, que pode monitorar sua atividade pessoal de rede."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Desbloqueado pelo TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"O dispositivo permanecerá bloqueado até que você o desbloqueie manualmente"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Receba notificações mais rápido"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Veja-as antes de desbloquear"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Não, obrigado"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mover para canto inferior esquerdo"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mover para canto inferior direito"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Dispensar"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Manter chats em primeiro plano"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Novos chats do app <xliff:g id="APP_NAME">%1$s</xliff:g> aparecerão como balões. Toque em um balão para abrir o chat. Arraste para mover.\n\nToque no balão"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Toque em \"Gerenciar\" para desativar os balões desse app"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navegação no sistema atualizada. Se quiser alterá-la, acesse as configurações."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Acesse as configurações para atualizar a navegação no sistema"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Em espera"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Todos"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Não foi possível carregar a lista de controles."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Outro"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ro/strings.xml b/packages/SystemUI/res/values-ro/strings.xml
index 845714e..e72f68c 100644
--- a/packages/SystemUI/res/values-ro/strings.xml
+++ b/packages/SystemUI/res/values-ro/strings.xml
@@ -561,6 +561,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Profilul de serviciu este gestionat de <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profilul este conectat la <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, care vă poate monitoriza activitatea în rețeaua de serviciu, inclusiv e-mailurile, aplicațiile și site-urile accesate.\n\nDe asemenea, v-ați conectat la <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, care vă poate monitoriza activitatea în rețeaua personală."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Deblocat de TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Dispozitivul va rămâne blocat până când îl deblocați manual"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Obțineți notificări mai rapid"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Doresc să se afișeze înainte de deblocare"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nu, mulț."</string>
@@ -984,12 +985,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Mutați în stânga jos"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Mutați în dreapta jos"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Închideți"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Mențineți conversațiile prin chat în prim-plan"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Conversațiile noi prin chat din <xliff:g id="APP_NAME">%1$s</xliff:g> vor apărea sub forma unor baloane. Atingeți un balon pentru a deschide o conversație. Trageți-l pentru a-l muta.\n\nAtingeți balonul."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Atingeți Gestionați pentru a dezactiva baloanele din această aplicație"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigarea în sistem a fost actualizată. Pentru a face modificări, accesați Setările."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Accesați Setările pentru a actualiza navigarea în sistem"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Standby"</string>
@@ -1010,4 +1008,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Toate"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Lista cu toate comenzile nu a putut fi încărcată."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Altul"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ru/strings.xml b/packages/SystemUI/res/values-ru/strings.xml
index c32627d..85b1bb3 100644
--- a/packages/SystemUI/res/values-ru/strings.xml
+++ b/packages/SystemUI/res/values-ru/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Вашим рабочим профилем управляет организация \"<xliff:g id="ORGANIZATION">%1$s</xliff:g>\". Приложение \"<xliff:g id="APPLICATION_WORK">%2$s</xliff:g>\" может отслеживать ваши действия в корпоративной сети, включая работу с электронной почтой, приложениями и веб-сайтами.\n\nТакже запущено приложение \"<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>\", которое может отслеживать ваши действия в сети, выполняемые в личном профиле."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Разблокировано агентом доверия"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Устройство необходимо будет разблокировать вручную"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Быстрый доступ к уведомлениям"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Просматривайте уведомления на заблокированном экране."</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Закрыть"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Перенести в левый нижний угол"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Перенести в правый нижний угол"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Закрыть"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Чаты на первом плане"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Новые чаты из приложения \"<xliff:g id="APP_NAME">%1$s</xliff:g>\" будут появляться в виде всплывающих уведомлений. Чтобы открыть такое уведомление, нажмите на него. Чтобы переместить всплывающее уведомление, перетащите его.\n\nНажмите на всплывающее уведомление"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Чтобы отключить всплывающие уведомления от приложения, нажмите \"Настроить\"."</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Параметры навигации в системе обновлены. Чтобы изменить их, перейдите в настройки."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Чтобы обновить параметры навигации в системе, перейдите в настройки."</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Переход в режим ожидания"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Все"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Не удалось загрузить список элементов управления."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Другое"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-si/strings.xml b/packages/SystemUI/res/values-si/strings.xml
index ec78baa..17db522 100644
--- a/packages/SystemUI/res/values-si/strings.xml
+++ b/packages/SystemUI/res/values-si/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"ඔබේ කාර්යාල පැතිකඩ කළමනාකරණය කරන්නේ <xliff:g id="ORGANIZATION">%1$s</xliff:g> විසිනි. ඊ-තැපැල්, යෙදුම් සහ වෙබ් අඩවි ඇතුළු ඔබේ කාර්යාල ජාල ක්රියාකාරකම් නිරීක්ෂණය කළ හැකි, <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, වෙත පැතිකඩ සම්බන්ධ වී ඇත.\n\nඔබ ඔබේ පෞද්ගලික ජාල ක්රියාකාරකම් නිරීක්ෂණය කළ හැකි, <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> වෙතද සම්බන්ධ වී ඇත."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent මඟින් අඟුලු දමා තබා ගන්න"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"ඔබ අතින් අගුළු අරින තුරු උපකරණය අගුළු වැටි තිබේ"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"දැනුම්දීම් ඉක්මනින් ලබාගන්න"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ඔබ අඟුළු හැරීමට කලින් ඒවා බලන්න"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"එපා ස්තූතියි"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"පහළ වමට ගෙන යන්න"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"පහළ දකුණට ගෙන යන්න"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ඉවතලන්න"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"කල් තියා කතාබස් කර ගෙන යන්න"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> වෙතින් නව කතාබස් බුබුලු ලෙස දිස් වනු ඇත. බුබුලක් විවෘත කිරීමට එය තට්ටු කරන්න. එය ගෙන යාමට අදින්න.\n\nබුබුල තට්ටු කරන්න"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"මෙම යෙදුමෙන් බුබුලු ක්රියාවිරහිත කිරීමට කළමනාකරණය කරන්න තට්ටු කරන්න"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"පද්ධති සංචලනය යාවත්කාලීන කළා. වෙනස්කම් සිදු කිරීමට, සැකසීම් වෙත යන්න."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"පද්ධති සංචලනය යාවත්කාලීන කිරීමට සැකසීම් වෙත යන්න"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"පොරොත්තු"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"සියලු"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"සියලු පාලනවල ලැයිස්තුව පූරණය කළ නොහැකි විය."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"වෙනත්"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-sk/strings.xml b/packages/SystemUI/res/values-sk/strings.xml
index bb6ac46..295e700 100644
--- a/packages/SystemUI/res/values-sk/strings.xml
+++ b/packages/SystemUI/res/values-sk/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Váš pracovný profil spravuje organizácia <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Je pripojený k aplikácii <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, ktorá môže sledovať vašu pracovnú aktivitu v sieti vrátane správ, aplikácií a webových stránok.\n\nPripojili ste sa k aplikácii <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, ktorá môže sledovať vašu osobnú aktivitu v sieti."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Odomknutie udržiava TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Zariadenie zostane uzamknuté, dokým ho ručne neodomknete."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Získavať upozornenia rýchlejšie"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Zobraziť pred odomknutím"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nie, vďaka"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Presunúť doľava nadol"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Presunúť doprava nadol"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Zavrieť"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Zobrazovať čety na popredí"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nové čety z aplikácie <xliff:g id="APP_NAME">%1$s</xliff:g> sa budú zobrazovať ako bubliny. Bubliny otvoríte klepnutím na ne. Premiestnite ich presunutím.\n\nKlepnite na bublinu."</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Klepnutím na Spravovať vypnite bubliny z tejto aplikácie"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigácia v systéme bola aktualizovaná. Ak chcete vykonať zmeny, prejdite do Nastavení."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Prejdite do Nastavení a aktualizujte navigáciu v systéme"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Pohotovostný režim"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Všetko"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Zoznam všetkých ovl. prvkov sa nepodarilo načítať."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Iné"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-sl/strings.xml b/packages/SystemUI/res/values-sl/strings.xml
index 5280f6e..b524749 100644
--- a/packages/SystemUI/res/values-sl/strings.xml
+++ b/packages/SystemUI/res/values-sl/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Delovni profil upravlja organizacija <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profil je povezan z aplikacijo <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, ki lahko nadzira vašo delovno omrežno dejavnost, vključno z e-pošto, aplikacijami in spletnimi mesti.\n\nPovezani ste tudi z aplikacijo <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, ki lahko nadzira vašo osebno omrežno dejavnost."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ohranja odklenjeno"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Naprava bo ostala zaklenjena, dokler je ročno ne odklenete."</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Hitrejše prejemanje obvestil"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Oglejte si jih pred odklepanjem"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ne, hvala"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Premakni spodaj levo"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Premakni spodaj desno"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Opusti"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Klepete obdrži v ospredju"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Novi klepeti v aplikaciji <xliff:g id="APP_NAME">%1$s</xliff:g> bodo prikazani kot oblački. Dotaknite se oblačka, da ga odprete. Povlecite, da ga premaknete.\n\nDotaknite se oblačka"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Dotaknite se »Upravljanje«, da izklopite oblačke iz te aplikacije"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Krmarjenje po sistemu je posodobljeno. Če želite opraviti spremembe, odprite nastavitve."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Če želite posodobiti krmarjenje po sistemu, odprite nastavitve"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Stanje pripravljenosti"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Vse"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Seznama vseh kontrolnikov ni bilo mogoče naložiti."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Drugo"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-sq/strings.xml b/packages/SystemUI/res/values-sq/strings.xml
index c1a32c5..2e83d25 100644
--- a/packages/SystemUI/res/values-sq/strings.xml
+++ b/packages/SystemUI/res/values-sq/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Profili yt i punës menaxhohet nga <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profili është i lidhur me <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, i cili mund të monitorojë aktivitetin tënd të punës në rrjet, duke përfshirë mail-et, aplikacionet dhe sajtet e uebit.\n\nJe lidhur gjithashtu edhe me <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, i cili mund të monitorojë aktivitetin tënd personal në rrjet."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Mbajtur shkyçur nga TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Pajisje do të qëndrojë e kyçur derisa ta shkyçësh manualisht"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Merr njoftime më shpejt"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Shikoji para se t\'i shkyçësh"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Jo, faleminderit!"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Zhvendos poshtë majtas"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Lëvize poshtë djathtas"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Hiq"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Mbaji bisedat në plan të parë"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Bisedat e reja nga <xliff:g id="APP_NAME">%1$s</xliff:g> do të shfaqen si flluska. Trokit mbi një flluskë për ta hapur atë. Zvarrit për ta zhvendosur atë.\n\nTrokit mbi flluskë"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Trokit \"Menaxho\" për të çaktivizuar flluskat nga ky aplikacion"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Navigimi i sistemit u përditësua. Për të bërë ndryshime, shko te \"Cilësimet\"."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Shko te \"Cilësimet\" për të përditësuar navigimin e sistemit"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Në gatishmëri"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Të gjitha"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Lista e të gjitha kontrolleve nuk mund të ngarkohej."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Tjetër"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-sr/strings.xml b/packages/SystemUI/res/values-sr/strings.xml
index 87c9d3f..f77d4a2 100644
--- a/packages/SystemUI/res/values-sr/strings.xml
+++ b/packages/SystemUI/res/values-sr/strings.xml
@@ -561,6 +561,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Профилом за Work управља <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Повезан је са апликацијом <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, која може да надгледа активности на пословној мрежи, укључујући имејлове, апликације и веб-сајтове.\n\nПовезани сте и са апликацијом <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, која може да надгледа активности на личној мрежи."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Поуздани агент спречава закључавање"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Уређај ће остати закључан док га не откључате ручно"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Брже добијајте обавештења"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Прегледајте их пре откључавања"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Не, хвала"</string>
@@ -984,12 +985,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Премести доле лево"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Премести доле десно"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Одбаци"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Нека поруке ћаскања остану у првом плану"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Нове поруке ћаскања из апликације <xliff:g id="APP_NAME">%1$s</xliff:g> ће се приказати као облачићи. Додирните облачић да бисте га отворили. Превуците да бисте га преместили.\n\nДодирните облачић"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Додирните Управљајте да бисте искључили облачиће из ове апликације"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Навигација система је ажурирана. Да бисте унели измене, идите у Подешавања."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Идите у Подешавања да бисте ажурирали навигацију система"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Стање приправности"</string>
@@ -1010,4 +1008,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Све"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Учитавање листе свих контрола није успело."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Друго"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-sv/strings.xml b/packages/SystemUI/res/values-sv/strings.xml
index c497574..76635ee 100644
--- a/packages/SystemUI/res/values-sv/strings.xml
+++ b/packages/SystemUI/res/values-sv/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Jobbprofilen hanteras av <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Profilen är ansluten till <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> som kan bevaka din nätverksaktivitet på jobbet, exempelvis e-post, appar och webbplatser.\n\nDu är även ansluten till <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> som kan bevaka din privata nätverksaktivitet."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Hålls olåst med TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Enheten förblir låst tills du låser upp den manuellt"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Få aviseringar snabbare"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Visa dem innan du låser upp"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Nej tack"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Flytta längst ned till vänster"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Flytta längst ned till höger"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Stäng"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Håll chattar i förgrunden"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Nya chattar från <xliff:g id="APP_NAME">%1$s</xliff:g> visas som bubblor. Tryck på en bubbla som du vill öppna. Flytta den genom att dra.\n\nTryck på bubblan"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Tryck på Hantera för att stänga av bubblor från den här appen"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Systemnavigeringen har uppdaterats. Öppna inställningarna om du vill ändra något."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Öppna inställningarna och uppdatera systemnavigeringen"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Viloläge"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Alla"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Listan med alla kontroller kunde inte läsas in."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Övrigt"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-sw/strings.xml b/packages/SystemUI/res/values-sw/strings.xml
index 8d2b137..3a5d6ce 100644
--- a/packages/SystemUI/res/values-sw/strings.xml
+++ b/packages/SystemUI/res/values-sw/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Wasifu wako wa kazini unasimamiwa na <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Wasifu umeunganishwa kwenye <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, ambayo inaweza kufuatilia shughuli zako kwenye mtandao wa kazini, ikiwa ni pamoja na barua pepe, programu na tovuti.\n\n Umeunganishwa pia kwenye <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, ambayo inaweza kufuatilia shughuli zako kwenye mtandao wa binafsi."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Imefunguliwa na kipengele cha kutathmini hali ya kuaminika"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Kifaa kitaendelea kuwa katika hali ya kufungwa hadi utakapokifungua mwenyewe"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Pata arifa kwa haraka"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Zitazame kabla hujafungua"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Hapana"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Sogeza chini kushoto"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Sogeza chini kulia"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Ondoa"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Zipe gumzo kipaumbele"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Gumzo mpya kutoka <xliff:g id="APP_NAME">%1$s</xliff:g> zitaonekana kama viputo. Gusa kiputo ili ukifungue. Buruta ili ukisogeze.\n\nGusa kiputo"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Gusa Dhibiti ili uzime viputo kwenye programu hii"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Umesasisha usogezaji kwenye mfumo. Ili ubadilishe, nenda kwenye Mipangilio."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Nenda kwenye mipangilio ili usasishe usogezaji kwenye mfumo"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Hali tuli"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Vyote"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Imeshindwa kupakia orodha ya vidhibiti vyote."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Nyingine"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ta/strings.xml b/packages/SystemUI/res/values-ta/strings.xml
index 3f1ddbd..1583bf8 100644
--- a/packages/SystemUI/res/values-ta/strings.xml
+++ b/packages/SystemUI/res/values-ta/strings.xml
@@ -63,18 +63,12 @@
<string name="usb_debugging_allow" msgid="1722643858015321328">"அனுமதி"</string>
<string name="usb_debugging_secondary_user_title" msgid="7843050591380107998">"USB பிழைதிருத்தம் அனுமதிக்கப்படவில்லை"</string>
<string name="usb_debugging_secondary_user_message" msgid="3740347841470403244">"தற்போது இந்தச் சாதனத்தில் உள்நுழைந்துள்ள பயனரால் USB பிழைதிருத்தத்தை இயக்க முடியாது. இந்த அம்சத்தை இயக்க, முதன்மைப் பயனருக்கு மாறவும்."</string>
- <!-- no translation found for wifi_debugging_title (7300007687492186076) -->
- <skip />
- <!-- no translation found for wifi_debugging_message (5461204211731802995) -->
- <skip />
- <!-- no translation found for wifi_debugging_always (2968383799517975155) -->
- <skip />
- <!-- no translation found for wifi_debugging_allow (4573224609684957886) -->
- <skip />
- <!-- no translation found for wifi_debugging_secondary_user_title (2493201475880517725) -->
- <skip />
- <!-- no translation found for wifi_debugging_secondary_user_message (4492383073970079751) -->
- <skip />
+ <string name="wifi_debugging_title" msgid="7300007687492186076">"இந்த நெட்வொர்க்கில் வயர்லெஸ் பிழைதிருத்தத்தை அனுமதிக்கவா?"</string>
+ <string name="wifi_debugging_message" msgid="5461204211731802995">"நெட்வொர்க் பெயர் (SSID)\n<xliff:g id="SSID_0">%1$s</xliff:g>\n\nவைஃபை முகவரி (BSSID)\n<xliff:g id="BSSID_1">%2$s</xliff:g>"</string>
+ <string name="wifi_debugging_always" msgid="2968383799517975155">"இந்த நெட்வொர்க்கில் எப்போதும் அனுமதி"</string>
+ <string name="wifi_debugging_allow" msgid="4573224609684957886">"அனுமதி"</string>
+ <string name="wifi_debugging_secondary_user_title" msgid="2493201475880517725">"வயர்லெஸ் பிழைதிருத்தம் அனுமதிக்கப்படவில்லை"</string>
+ <string name="wifi_debugging_secondary_user_message" msgid="4492383073970079751">"தற்போது இந்தச் சாதனத்தில் உள்நுழைந்துள்ள பயனரால் வயர்லெஸ் பிழைதிருத்தத்தை இயக்க முடியாது. இந்த அம்சத்தை இயக்க முதன்மைப் பயனருக்கு மாறவும்."</string>
<string name="usb_contaminant_title" msgid="894052515034594113">"USB போர்ட் முடக்கப்பட்டது"</string>
<string name="usb_contaminant_message" msgid="7730476585174719805">"தேவையற்றவையில் இருந்து உங்கள் சாதனத்தைப் பாதுகாக்க USB போர்ட் முடக்கப்பட்டுள்ளது. மேலும் எந்தத் துணைக் கருவிகளையும் அது கண்டறியாது.\n\nUSB போர்ட்டை மீண்டும் எப்போது பயன்படுத்தலாம் என்பதைப் பற்றி உங்களுக்குத் தெரிவிக்கப்படும்."</string>
<string name="usb_port_enabled" msgid="531823867664717018">"சார்ஜர்களையும் துணைக்கருவிகளையும் கண்டறிவதற்காக USB போர்ட் இயக்கப்பட்டுள்ளது"</string>
@@ -500,8 +494,7 @@
<string name="manage_notifications_text" msgid="6885645344647733116">"அறிவிப்புகளை நிர்வகி"</string>
<string name="manage_notifications_history_text" msgid="57055985396576230">"வரலாறு"</string>
<string name="notification_section_header_gentle" msgid="3044910806569985386">"ஒலியில்லாத அறிவிப்புகள்"</string>
- <!-- no translation found for notification_section_header_alerting (3168140660646863240) -->
- <skip />
+ <string name="notification_section_header_alerting" msgid="3168140660646863240">"விழிப்பூட்டல் அறிவிப்புகள்"</string>
<string name="notification_section_header_conversations" msgid="821834744538345661">"உரையாடல்கள்"</string>
<string name="accessibility_notification_section_header_gentle_clear_all" msgid="6490207897764933919">"ஒலியில்லாத அழைப்புகள் அனைத்தையும் அழிக்கும்"</string>
<string name="dnd_suppressing_shade_text" msgid="5588252250634464042">"\'தொந்தரவு செய்ய வேண்டாம்\' அம்சத்தின் மூலம் அறிவிப்புகள் இடைநிறுத்தப்பட்டுள்ளன"</string>
@@ -565,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"உங்கள் பணிக் கணக்கை <xliff:g id="ORGANIZATION">%1$s</xliff:g> நிர்வகிக்கிறது. மின்னஞ்சல்கள், ஆப்ஸ், இணையதளங்கள் உட்பட உங்கள் பணி நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> உடன் அது இணைக்கப்பட்டுள்ளது.\n\nஉங்கள் தனிப்பட்ட நெட்வொர்க் செயல்பாட்டைக் கண்காணிக்கக்கூடிய <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> உடனும் இணைக்கப்பட்டுள்ளீர்கள்."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent இதைத் திறந்தே வைத்துள்ளது"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"நீங்கள் கைமுறையாகத் திறக்கும் வரை, சாதனம் பூட்டப்பட்டிருக்கும்"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"விரைவாக அறிவிப்புகளைப் பெறுதல்"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"திறக்கும் முன் அவற்றைப் பார்க்கவும்"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"வேண்டாம்"</string>
@@ -700,10 +695,8 @@
<string name="notification_channel_summary_low" msgid="7300447764759926720">"ஒலியோ அதிர்வோ இல்லாமல் முழு கவனம் செலுத்த உதவும்."</string>
<string name="notification_channel_summary_default" msgid="3539949463907902037">"ஒலியோ அதிர்வோ ஏற்படுத்தி உங்கள் கவனத்தை ஈர்க்கும்."</string>
<string name="notification_channel_summary_bubble" msgid="7235935211580860537">"இந்த உள்ளடக்கத்திற்கான மிதக்கும் ஷார்ட்கட் மூலம் உங்கள் கவனத்தைப் பெற்றிருக்கும்."</string>
- <!-- no translation found for bubble_overflow_empty_title (3120029421991510842) -->
- <skip />
- <!-- no translation found for bubble_overflow_empty_subtitle (198257239740933131) -->
- <skip />
+ <string name="bubble_overflow_empty_title" msgid="3120029421991510842">"சமீபத்திய குமிழ்கள் இல்லை"</string>
+ <string name="bubble_overflow_empty_subtitle" msgid="198257239740933131">"சமீபத்திய குமிழ்களும் நிராகரிக்கப்பட்ட குமிழ்களும் இங்கே தோன்றும்."</string>
<string name="notification_unblockable_desc" msgid="2073030886006190804">"இந்த அறிவிப்புகளை மாற்ற இயலாது."</string>
<string name="notification_multichannel_desc" msgid="7414593090056236179">"இந்த அறிவுப்புக் குழுக்களை இங்கே உள்ளமைக்க இயலாது"</string>
<string name="notification_delegate_header" msgid="1264510071031479920">"ப்ராக்ஸியான அறிவிப்பு"</string>
@@ -1003,15 +996,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"விரைவுக் கட்டுப்பாடுகள்"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"கட்டுப்பாடுகளைச் சேர்த்தல்"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"எந்த ஆப்ஸிலிருந்து கட்டுப்பாடுகளைச் சேர்க்க வேண்டும் என்பதைத் தேர்ந்தெடுங்கள்"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> கட்டுப்பாடுகள் சேர்க்கப்பட்டன.</item>
+ <item quantity="one"><xliff:g id="NUMBER_0">%s</xliff:g> கட்டுப்பாடு சேர்க்கப்பட்டது.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"கட்டுப்பாடுகள்"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"விரைவு அணுகலுக்கான கட்டுப்பாடுகளைத் தேர்ந்தெடுங்கள்"</string>
- <!-- no translation found for controls_favorite_header_favorites (3118600046217493471) -->
+ <string name="controls_favorite_header_favorites" msgid="3118600046217493471">"பிடித்தவை"</string>
+ <string name="controls_favorite_header_all" msgid="7507855973418969992">"எல்லாம்"</string>
+ <string name="controls_favorite_load_error" msgid="2533215155804455348">"எல்லா கட்டுப்பாடுகளின் பட்டியலை ஏற்ற முடியவில்லை."</string>
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"பிற"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
<skip />
- <!-- no translation found for controls_favorite_header_all (7507855973418969992) -->
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
<skip />
- <!-- no translation found for controls_favorite_load_error (2533215155804455348) -->
- <skip />
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-te/strings.xml b/packages/SystemUI/res/values-te/strings.xml
index dd8dcdf..2442eff 100644
--- a/packages/SystemUI/res/values-te/strings.xml
+++ b/packages/SystemUI/res/values-te/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"మీ కార్యాలయ ప్రొఫైల్ <xliff:g id="ORGANIZATION">%1$s</xliff:g> నిర్వహణలో ఉంది. ఇమెయిల్లు, అనువర్తనాలు మరియు వెబ్సైట్లతో సహా మీ కార్యాలయ నెట్వర్క్ కార్యాచరణను పర్యవేక్షించగల <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>కి ప్రొఫైల్ కనెక్ట్ చేయబడింది.\n\nమీ వ్యక్తిగత నెట్వర్క్ కార్యాచరణను పర్యవేక్షించగల <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>కి కూడా మీరు కనెక్ట్ చేయబడ్డారు."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent ద్వారా అన్లాక్ చేయబడింది"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"మీరు మాన్యువల్గా అన్లాక్ చేస్తే మినహా పరికరం లాక్ చేయబడి ఉంటుంది"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"నోటిఫికేషన్లను వేగంగా పొందండి"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"వీటిని మీరు అన్లాక్ చేయకముందే చూడండి"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"వద్దు, ధన్యవాదాలు"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"దిగువ ఎడమవైపునకు తరలించు"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"దిగవు కుడివైపునకు జరుపు"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"విస్మరించు"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"చాట్లను ముందుగా ఉంచండి"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> నుండి వచ్చే కొత్త చాట్లు బబుల్లుగా కనిపిస్తాయి. దానిని తెరవడానికి బబుల్ను ట్యాప్ చేయండి. దానిని తరలించడానికి లాగండి.\n\nబబుల్ను ట్యాప్ చేయండి"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"ఈ యాప్ నుండి వచ్చే బబుల్లను ఆఫ్ చేయడానికి మేనేజ్ బటన్ను ట్యాప్ చేయండి"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"సిస్టమ్ నావిగేషన్ అప్డేట్ చేయబడింది. మార్పులు చేయడానికి, సెట్టింగ్లకు వెళ్లండి."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"సిస్టమ్ నావిగేషన్ను అప్డేట్ చేయడానికి సెట్టింగ్లకు వెళ్లండి"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"స్టాండ్బై"</string>
@@ -994,12 +993,20 @@
<string name="quick_controls_title" msgid="525285759614231333">"త్వరిత నియంత్రణలు"</string>
<string name="controls_providers_title" msgid="8844124515157926071">"నియంత్రణలను జోడించండి"</string>
<string name="controls_providers_subtitle" msgid="8187768950110836569">"దాని నుండి నియంత్రణలను జోడించేలా ఒక యాప్ను ఎంచుకోండి"</string>
- <!-- no translation found for controls_number_of_favorites (1057347832073807380) -->
+ <plurals name="controls_number_of_favorites" formatted="false" msgid="1057347832073807380">
+ <item quantity="other"><xliff:g id="NUMBER_1">%s</xliff:g> కంట్రోల్లు యాడ్ అయ్యాయి.</item>
+ <item quantity="one"><xliff:g id="NUMBER_0">%s</xliff:g> కంట్రోల్ యాడ్ అయింది.</item>
+ </plurals>
<string name="controls_favorite_default_title" msgid="967742178688938137">"నియంత్రణలు"</string>
<string name="controls_favorite_subtitle" msgid="4049644994401173949">"త్వరిత యాక్సెస్ కోసం నియంత్రణలను ఎంచుకోండి"</string>
<string name="controls_favorite_header_favorites" msgid="3118600046217493471">"ఇష్టమైనవి"</string>
<string name="controls_favorite_header_all" msgid="7507855973418969992">"అన్ని"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"అన్ని నియంత్రణలు గల జాబితాను లోడ్ చేయలేకపోయాము."</string>
- <!-- no translation found for controls_favorite_other_zone_header (9089613266575525252) -->
+ <string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"ఇతరం"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
<skip />
</resources>
diff --git a/packages/SystemUI/res/values-television/integers.xml b/packages/SystemUI/res/values-television/integers.xml
new file mode 100644
index 0000000..91e83cc
--- /dev/null
+++ b/packages/SystemUI/res/values-television/integers.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2020 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
+ -->
+<resources>
+ <!-- The position of the volume dialog on the screen.
+ See com.android.systemui.volume.VolumeDialogImpl.
+ Value 81 corresponds to BOTTOM|CENTER_HORIZONTAL. -->
+ <integer name="volume_dialog_gravity">81</integer>
+</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values-th/strings.xml b/packages/SystemUI/res/values-th/strings.xml
index d45b7dc..866eb59 100644
--- a/packages/SystemUI/res/values-th/strings.xml
+++ b/packages/SystemUI/res/values-th/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"<xliff:g id="ORGANIZATION">%1$s</xliff:g> เป็นผู้จัดการโปรไฟล์งานของคุณ โปรไฟล์ดังกล่าวเชื่อมต่ออยู่กับ <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ซึ่งสามารถตรวจสอบกิจกรรมในเครือข่ายของคุณ รวมถึงอีเมล แอป และเว็บไซต์\n\nคุณยังเชื่อมต่ออยู่กับ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ด้วย ซึ่งสามารถตรวจสอบกิจกรรมในเครือข่ายส่วนตัวของคุณ"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"ปลดล็อกไว้โดย TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"อุปกรณ์จะล็อกจนกว่าคุณจะปลดล็อกด้วยตนเอง"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"รับการแจ้งเตือนเร็วขึ้น"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"ดูก่อนปลดล็อก"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"ไม่เป็นไร"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"ย้ายไปด้านซ้ายล่าง"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"ย้ายไปด้านขาวล่าง"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"ปิด"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"เข้าถึงแชทได้ง่ายๆ"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"แชทใหม่จาก <xliff:g id="APP_NAME">%1$s</xliff:g> จะปรากฏเป็นบับเบิล แตะบับเบิลเพื่อเปิดแชท ลากเพื่อย้ายตำแหน่ง\n\nแตะบับเบิล"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"แตะ \"จัดการ\" เพื่อปิดบับเบิลจากแอปนี้"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"อัปเดตการไปยังส่วนต่างๆ ของระบบแล้ว หากต้องการเปลี่ยนแปลง ให้ไปที่การตั้งค่า"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"ไปที่การตั้งค่าเพื่ออัปเดตการไปยังส่วนต่างๆ ของระบบ"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"สแตนด์บาย"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"ทั้งหมด"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"โหลดรายการตัวควบคุมทั้งหมดไม่ได้"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"อื่นๆ"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-tl/strings.xml b/packages/SystemUI/res/values-tl/strings.xml
index 7cecf13..cdfe732 100644
--- a/packages/SystemUI/res/values-tl/strings.xml
+++ b/packages/SystemUI/res/values-tl/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Pinamamahalaan ng <xliff:g id="ORGANIZATION">%1$s</xliff:g> ang iyong profile sa trabaho. Nakakonekta ang profile sa <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, na maaaring sumubaybay sa aktibidad sa iyong network sa trabaho, kasama ang mga email, app, at website.\n\nNakakonekta ka rin sa <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, na maaaring sumubaybay sa aktibidad sa iyong personal na network."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Pinanatiling naka-unlock ng TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Mananatiling naka-lock ang device hanggang sa manual mong i-unlock"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Kunin ang notification nang mas mabilis"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Tingnan ang mga ito bago ka mag-unlock"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Hindi"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Ilipat sa kaliwa sa ibaba"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Ilipat sa kanan sa ibaba"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"I-dismiss"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Panatilihing nasa harap ang mga chat"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Lalabas ang mga bagong chat mula sa <xliff:g id="APP_NAME">%1$s</xliff:g> bilang mga bubble. I-tap ang isang bubble para buksan ito. I-drag ito para ilipat ito.\n\nI-tap ang bubble"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"I-tap ang Pamahalaan para i-off ang mga bubble mula sa app na ito"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Na-update na ang pag-navigate ng system. Para gumawa ng mga pagbabago, pumunta sa Mga Setting."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Pumunta sa Mga Setting para i-update ang pag-navigate sa system"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Naka-standby"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Lahat"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Hindi ma-load ang listahan ng lahat ng control."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Iba pa"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-tr/strings.xml b/packages/SystemUI/res/values-tr/strings.xml
index 150363e..8d2d98b 100644
--- a/packages/SystemUI/res/values-tr/strings.xml
+++ b/packages/SystemUI/res/values-tr/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"İş profiliniz <xliff:g id="ORGANIZATION">%1$s</xliff:g> tarafından yönetiliyor. Profil; e-postalar, uygulamalar ve web siteleri de dahil olmak üzere iş ağı etkinliğinizi izleyebilen <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> uygulamasına bağlı.\n\nAyrıca, kişisel ağ etkinliğinizi izleyebilen <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> uygulamasına bağlısınız."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent tarafından kilit açık tutuldu"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Cihazınızın kilidini manuel olarak açmadıkça cihaz kilitli kalacak"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Bildirimleri daha hızlı alın"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Kilidi açmadan bildirimleri görün"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Hayır, teşekkürler"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Sol alta taşı"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Sağ alta taşı"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Kapat"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Sohbetleri önde tutma"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> adlı kişi ile yeni sohbetler balon olarak görünür. Açmak için balona dokunun. Taşımak için sürükleyin.\n\nBalona dokunun"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Bu uygulamanın balonlarını kapatmak için Yönet\'e dokunun"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Sistemde gezinme yöntemi güncellendi. Değişiklik yapmak için Ayarlar\'a gidin."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Sistemde gezinme yöntemini güncellemek için Ayarlar\'a gidin"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Beklemeye alınıyor"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tümü"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Tüm kontrollerin listesi yüklenemedi."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Diğer"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-uk/strings.xml b/packages/SystemUI/res/values-uk/strings.xml
index 347532d..c6bec40 100644
--- a/packages/SystemUI/res/values-uk/strings.xml
+++ b/packages/SystemUI/res/values-uk/strings.xml
@@ -564,6 +564,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Вашим робочим профілем керує адміністратор організації <xliff:g id="ORGANIZATION">%1$s</xliff:g>. Цей профіль під’єднано до додатка <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, який може відстежувати вашу активність у мережі, зокрема а електронній пошті, додатках і на веб-сайтах.\n\nВаш профіль також під’єднано до додатка <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, який може відстежувати вашу особисту активність у мережі."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Розблоковує довірчий агент"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Пристрій залишатиметься заблокованим, доки ви не розблокуєте його вручну"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Швидше отримуйте сповіщення"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Переглядайте сповіщення, перш ніж розблокувати екран"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ні, дякую"</string>
@@ -989,12 +990,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Перемістити ліворуч униз"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Перемістити праворуч униз"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Закрити"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Чати завжди під рукою"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Нові чати з додатка <xliff:g id="APP_NAME">%1$s</xliff:g> з\'являтимуться як спливаючі сповіщення. Щоб відкрити чат, натисніть сповіщення. Щоб перемістити сповіщення, потягніть його.\n\nНатисніть спливаюче сповіщення"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Натисніть \"Керувати\", щоб вимкнути спливаючі сповіщення для цього додатка"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Навігацію в системі оновлено. Щоб внести зміни, перейдіть у налаштування."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Перейдіть у налаштування, щоб оновити навігацію в системі"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Режим очікування"</string>
@@ -1016,4 +1014,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Усі"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Не вдалося завантажити список усіх елементів керування."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Інше"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-ur/strings.xml b/packages/SystemUI/res/values-ur/strings.xml
index a1523bf..cc5f3c5 100644
--- a/packages/SystemUI/res/values-ur/strings.xml
+++ b/packages/SystemUI/res/values-ur/strings.xml
@@ -558,6 +558,8 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"آپ کا دفتری پروفائل <xliff:g id="ORGANIZATION">%1$s</xliff:g> کے زیر انتظام ہے۔ پروفائل <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> سے منسلک ہے جو ای میلز، ایپس اور ویب سائٹس سمیت آپ کے دفتری نیٹ ورک کی سرگرمی مانیٹر کر سکتی ہے۔\n\nآپ <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> سے بھی منسلک ہیں، جو آپ کے ذاتی نیٹ ورک کی سرگرمی مانیٹر کر سکتی ہے۔"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"ٹرسٹ ایجنٹ نے غیر مقفل رکھا ہے"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"آلہ اس وقت تک مقفل رہے گا جب تک آپ دستی طور پر اسے غیر مقفل نہ کریں"</string>
+ <!-- no translation found for keyguard_indication_trust_unlocked_plugged_in (2323452175329362855) -->
+ <skip />
<string name="hidden_notifications_title" msgid="1782412844777612795">"تیزی سے اطلاعات حاصل کریں"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"غیر مقفل کرنے سے پہلے انہیں دیکھیں"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"نہیں شکریہ"</string>
@@ -979,12 +981,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"نیچے بائیں جانب لے جائیں"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"نیچے دائیں جانب لے جائیں"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"برخاست کریں"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"چیٹس سامنے رکھیں"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> کی نئی چیٹس بلبلوں کے طور پر ظاہر ہوں گی۔ اسے کھولنے کے لیے کسی بلبلہ کو تھپتھپائیں۔ اسے منتقل کرنے کے لیے گھسیٹیں۔\n\nبلبلہ کو تھپتھپائیں"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"اس ایپ سے بلبلوں کو آف کرنے کے لیے نظم کریں پر تھپتھپائیں"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"سسٹم نیویگیشن اپ ڈیٹ کیا گیا۔ تبدیلیاں کرنے کے لیے، ترتیبات پر جائیں۔"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"سسٹم نیویگیشن اپ ڈیٹ کرنے کے لیے ترتیبات پر جائیں"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"اسٹینڈ بائی"</string>
@@ -1004,4 +1003,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"تمام"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"تمام کنٹرولز کی فہرست لوڈ نہیں کی جا سکی۔"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"دیگر"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-uz/strings.xml b/packages/SystemUI/res/values-uz/strings.xml
index 7192a8e..6ceaeeb 100644
--- a/packages/SystemUI/res/values-uz/strings.xml
+++ b/packages/SystemUI/res/values-uz/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Ishchi profilingiz <xliff:g id="ORGANIZATION">%1$s</xliff:g> tomonidan boshqariladi. <xliff:g id="APPLICATION_WORK">%2$s</xliff:g> ilovasi ish tarmog‘idagi, jumladan, e-pochta, ilova va veb-saytlardagi xatti-harakatlaringizni kuzatishi mumkin.\n\nShuningdek, <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g> ilovasi ham shaxsiy tarmoqdagi harakatlaringizni kuzatishi mumkin."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"TrustAgent tomonidan ochilgan"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Qurilma qo‘lda qulfdan chiqarilmaguncha qulflangan holatda qoladi"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Bildirishnomalarni tezroq oling"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Ularni qulfdan chiqarishdan oldin ko‘ring"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Kerak emas"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Quyi chapga surish"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Quyi oʻngga surish"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Yopish"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Chatlar asosiy planda"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"<xliff:g id="APP_NAME">%1$s</xliff:g> ilovasidan yangi chatlar bulutchalar shaklida chiqadi. Uni ochish uchun bulutchani bosing. Uni surish uchun torting.\n\nBulutchani bosing"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Bu ilova bulutchalarini faolsizlantirish uchun Boshqarish tugmasini bosing"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Tizim navigatsiyasi yangilandi. Buni Sozlamalar orqali oʻzgartirishingiz mumkin."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Tizim navigatsiyasini yangilash uchun Sozlamalarni oching"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Kutib turing"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Hammasi"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Boshqaruv elementlarining barchasi yuklanmadi."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Boshqa"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-vi/strings.xml b/packages/SystemUI/res/values-vi/strings.xml
index a9dd01d..37f71c0 100644
--- a/packages/SystemUI/res/values-vi/strings.xml
+++ b/packages/SystemUI/res/values-vi/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Hồ sơ công việc của bạn do <xliff:g id="ORGANIZATION">%1$s</xliff:g> quản lý. Hồ sơ này được kết nối với <xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, ứng dụng này có thể giám sát hoạt động mạng của bạn, bao gồm email, ứng dụng và trang web.\n\nBạn cũng đang kết nối với <xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, ứng dụng này có thể giám sát hoạt động mạng cá nhân của bạn."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Luôn được TrustAgent mở khóa"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Thiết bị sẽ vẫn bị khóa cho tới khi bạn mở khóa theo cách thủ công"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Nhận thông báo nhanh hơn"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Xem thông báo trước khi bạn mở khóa"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Ko, cảm ơn"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Chuyển tới dưới cùng bên trái"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Chuyển tới dưới cùng bên phải"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Loại bỏ"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Giữ cuộc trò chuyện trên nền trước"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Các cuộc trò chuyện mới từ ứng dụng <xliff:g id="APP_NAME">%1$s</xliff:g> sẽ hiển thị dưới dạng bong bóng. Hãy nhấn vào bong bóng để mở. Kéo để di chuyển cuộc trò chuyện.\n\nNhấn vào bong bóng"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Nhấn vào nút Quản lý để tắt bong bóng từ ứng dụng này"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Đã cập nhật chế độ di chuyển trên hệ thống. Để thay đổi, hãy chuyển đến phần Cài đặt."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Chuyển đến phần Cài đặt để cập nhật chế độ di chuyển trên hệ thống"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Chế độ chờ"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Tất cả"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Không thể tải danh sách tất cả tùy chọn điều khiển."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Khác"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-zh-rCN/strings.xml b/packages/SystemUI/res/values-zh-rCN/strings.xml
index e80a624..119767b 100644
--- a/packages/SystemUI/res/values-zh-rCN/strings.xml
+++ b/packages/SystemUI/res/values-zh-rCN/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"您的工作资料由“<xliff:g id="ORGANIZATION">%1$s</xliff:g>”负责管理,且已连接到“<xliff:g id="APPLICATION_WORK">%2$s</xliff:g>”(该应用能够监控您的工作网络活动,其中包括收发电子邮件、使用应用和浏览网站)。\n\n此外,您还连接到了“<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>”(该应用能够监控您的个人网络活动)。"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"由 TrustAgent 保持解锁状态"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"在您手动解锁之前,设备会保持锁定状态"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"更快捷地查看通知"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"无需解锁即可查看通知"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"不用了"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"移至左下角"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"移至右下角"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"关闭"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"让聊天在前台运行"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"来自<xliff:g id="APP_NAME">%1$s</xliff:g>的新聊天消息会显示为气泡。点按某个气泡可将其打开。拖动即可移动气泡。\n\n点按该气泡"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"点按“管理”按钮,可关闭来自此应用的气泡"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"系统导航已更新。要进行更改,请转到“设置”。"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"转到“设置”即可更新系统导航"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"待机"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"全部"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"无法加载所有控件的列表。"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"其他"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-zh-rHK/strings.xml b/packages/SystemUI/res/values-zh-rHK/strings.xml
index 4787b9b..8a3687f 100644
--- a/packages/SystemUI/res/values-zh-rHK/strings.xml
+++ b/packages/SystemUI/res/values-zh-rHK/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"您的工作設定檔由<xliff:g id="ORGANIZATION">%1$s</xliff:g>管理。設定檔已連結至「<xliff:g id="APPLICATION_WORK">%2$s</xliff:g>」,此應用程式可以監控您的工作網絡活動,包括電郵、應用程式和網站。\n\n您亦已連結至「<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>」,此應用程式可以監控您的個人網絡活動。"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"由信任的代理保持解鎖狀態"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"裝置將保持上鎖,直到您手動解鎖"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"更快取得通知"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"解鎖前顯示"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"不用了,謝謝"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"移去左下角"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"移去右下角"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"關閉"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"保持即時通訊在最前面"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"「<xliff:g id="APP_NAME">%1$s</xliff:g>」的新即時通訊將以小視窗形式顯示。輕按小視窗即可開啟。拖曳即可移動。\n\n輕按小視窗"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"輕按「管理」即可關閉此應用程式的小視窗"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"系統導覽已更新。如需變更,請前往「設定」。"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"前往「設定」更新系統導覽"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"待機"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"全部"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"無法載入完整控制項清單。"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"其他"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-zh-rTW/strings.xml b/packages/SystemUI/res/values-zh-rTW/strings.xml
index 3158a30..16ee960 100644
--- a/packages/SystemUI/res/values-zh-rTW/strings.xml
+++ b/packages/SystemUI/res/values-zh-rTW/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"你的工作資料夾是由「<xliff:g id="ORGANIZATION">%1$s</xliff:g>」所管理。由於該設定檔已連結至「<xliff:g id="APPLICATION_WORK">%2$s</xliff:g>」,因此你的網路活動 (包括收發電子郵件、使用應用程式和瀏覽網站) 可能會受到這個應用程式監控。\n\n此外,你還與「<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>」建立了連結,因此你的個人網路活動也可能會受到該應用程式監控。"</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"由 TrustAgent 維持解鎖狀態"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"在你手動解鎖前,裝置將保持鎖定狀態"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"更快取得通知"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"解鎖前顯示"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"不用了,謝謝"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"移至左下方"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"移至右下方"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"關閉"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"讓即時通訊繼續在前景執行"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"系統會以泡泡形式顯示來自「<xliff:g id="APP_NAME">%1$s</xliff:g>」的新即時通訊。輕觸泡泡即可開啟,拖曳則可移動泡泡。\n\n輕觸泡泡"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"輕觸 [管理] 即可關閉來自這個應用程式的泡泡"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"系統操作機制已更新。如要進行變更,請前往「設定」。"</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"請前往「設定」更新系統操作機制"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"待機"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"全部"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"無法載入完整的控制項清單。"</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"其他"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values-zu/strings.xml b/packages/SystemUI/res/values-zu/strings.xml
index e94a8ab..7e2b53e 100644
--- a/packages/SystemUI/res/values-zu/strings.xml
+++ b/packages/SystemUI/res/values-zu/strings.xml
@@ -558,6 +558,7 @@
<string name="monitoring_description_app_personal_work" msgid="6175816356939166101">"Iphrofayela yakho yomsebenzi iphethwe i-<xliff:g id="ORGANIZATION">%1$s</xliff:g>. Iphrofayela ixhumeke ku-<xliff:g id="APPLICATION_WORK">%2$s</xliff:g>, engaqapha umsebenzi wakho wenethiwekhi, ofaka ama-imeyili, izinhlelo zokusebenza, namawebhusayithi.\n\nFuthi uxhumeke ku-<xliff:g id="APPLICATION_PERSONAL">%3$s</xliff:g>, engaqapha umsebenzi wakho siqu wenethiwekhi."</string>
<string name="keyguard_indication_trust_unlocked" msgid="7395154975733744547">"Igcinwa ivuliwe ngo-TrustAgent"</string>
<string name="keyguard_indication_trust_disabled" msgid="6820793704816727918">"Idivayisi izohlala ikhiyekile uze uyivule ngokwenza"</string>
+ <string name="keyguard_indication_trust_unlocked_plugged_in" msgid="2323452175329362855">"<xliff:g id="KEYGUARD_INDICATION">%1$s</xliff:g>\n<xliff:g id="POWER_INDICATION">%2$s</xliff:g>"</string>
<string name="hidden_notifications_title" msgid="1782412844777612795">"Thola izaziso ngokushesha"</string>
<string name="hidden_notifications_text" msgid="5899627470450792578">"Ibone ngaphambi kokuthi uyivule"</string>
<string name="hidden_notifications_cancel" msgid="4805370226181001278">"Cha ngiyabonga"</string>
@@ -979,12 +980,9 @@
<string name="bubble_accessibility_action_move_bottom_left" msgid="6339015902495504715">"Hambisa inkinobho ngakwesokunxele"</string>
<string name="bubble_accessibility_action_move_bottom_right" msgid="7471571700628346212">"Hambisa inkinobho ngakwesokudla"</string>
<string name="bubble_dismiss_text" msgid="7071770411580452911">"Cashisa"</string>
- <!-- no translation found for bubbles_user_education_title (3385222165904578710) -->
- <skip />
- <!-- no translation found for bubbles_user_education_description (6663205638091146934) -->
- <skip />
- <!-- no translation found for bubbles_user_education_manage (1391639189507036423) -->
- <skip />
+ <string name="bubbles_user_education_title" msgid="3385222165904578710">"Gcina izingxoxo ziphambili"</string>
+ <string name="bubbles_user_education_description" msgid="6663205638091146934">"Izingxoxo ezintsha kusuka ku-<xliff:g id="APP_NAME">%1$s</xliff:g>zizovela njengamabhamuza. Thepha ibhamuza ukuze ulivule. Hudula ukuze ulisuse.\n\nThepha ibhamuza"</string>
+ <string name="bubbles_user_education_manage" msgid="1391639189507036423">"Thepha okuthi Phatha ukuvala amabhamuza kusuka kulolu hlelo lokusebenza"</string>
<string name="notification_content_system_nav_changed" msgid="5077913144844684544">"Ukuzulazula kwesistimu kubuyekeziwe. Ukuze wenze ushintsho, hamba kokuthi Izilungiselelo."</string>
<string name="notification_content_gesture_nav_available" msgid="4431460803004659888">"Hamba kuzilungiselelo ukuze ubuyekeze ukuzulazula kwesistimu"</string>
<string name="inattentive_sleep_warning_title" msgid="3891371591713990373">"Ilindile"</string>
@@ -1004,4 +1002,10 @@
<string name="controls_favorite_header_all" msgid="7507855973418969992">"Konke"</string>
<string name="controls_favorite_load_error" msgid="2533215155804455348">"Uhlu lwazo zonke izilawuli alilayishekanga."</string>
<string name="controls_favorite_other_zone_header" msgid="9089613266575525252">"Okunye"</string>
+ <!-- no translation found for controls_dialog_title (8806193219278278442) -->
+ <skip />
+ <!-- no translation found for controls_dialog_ok (7011816381344485651) -->
+ <skip />
+ <!-- no translation found for controls_dialog_message (6292099631702047540) -->
+ <skip />
</resources>
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index 80c1ac8..56e2b06 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -225,4 +225,8 @@
<color name="control_default_background">@color/GM2_grey_900</color>
<color name="control_list_popup_background">@*android:color/background_floating_material_dark</color>
<color name="control_spinner_dropdown">@*android:color/foreground_material_dark</color>
+ <color name="control_enabled_light_background">@color/GM2_yellow_200</color>
+ <color name="control_enabled_thermo_heat_background">@color/GM2_red_200</color>
+ <color name="control_enabled_thermo_cool_background">@color/GM2_blue_200</color>
+ <color name="control_enabled_default_background">@color/GM2_blue_200</color>
</resources>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index d160829..82224df 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -117,7 +117,7 @@
<!-- Tiles native to System UI. Order should match "quick_settings_tiles_default" -->
<string name="quick_settings_tiles_stock" translatable="false">
- wifi,cell,battery,dnd,flashlight,rotation,bt,airplane,location,hotspot,inversion,saver,dark,work,cast,night,controls,screenrecord
+ wifi,cell,battery,dnd,flashlight,rotation,bt,airplane,location,hotspot,inversion,saver,dark,work,cast,night,screenrecord
</string>
<!-- The tiles to display in QuickSettings -->
@@ -468,12 +468,18 @@
<!-- On debuggable builds, alert the user if SystemUI PSS goes over this number (in kb) -->
<integer name="watch_heap_limit">256000</integer>
+ <!-- Animation duration for resizing of PIP when entering/exiting. -->
+ <integer name="config_pipResizeAnimationDuration">425</integer>
+
<!-- Allow dragging the PIP to a location to close it -->
<bool name="config_pipEnableDismissDragToEdge">true</bool>
<!-- Allow PIP to resize to a slightly bigger state upon touch/showing the menu -->
<bool name="config_pipEnableResizeForMenu">true</bool>
+ <!-- Allow PIP to enable round corner, see also R.dimen.pip_corner_radius -->
+ <bool name="config_pipEnableRoundCorner">false</bool>
+
<!-- SystemUI Plugins that can be loaded on user builds. -->
<string-array name="config_pluginWhitelist" translatable="false">
<item>com.android.systemui</item>
@@ -523,4 +529,7 @@
<!-- Flag to turn on the rendering of the above path or not -->
<bool name="config_enableDisplayCutoutProtection">false</bool>
+ <!-- Respect drawable/rounded.xml intrinsic size for multiple radius corner path customization -->
+ <bool name="config_roundedCornerMultipleRadius">false</bool>
+
</resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 2dc0f5f..e45cbec 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -124,9 +124,6 @@
<!-- Increased height of a collapsed media notification in the status bar -->
<dimen name="notification_min_height_media">160dp</dimen>
- <!-- Increased height of a collapsed messaging notification in the status bar -->
- <dimen name="notification_min_height_messaging">118dp</dimen>
-
<!-- Height of a small notification in the status bar which was used before android N -->
<dimen name="notification_min_height_legacy">64dp</dimen>
@@ -983,6 +980,9 @@
<!-- The touchable/draggable edge size for PIP resize. -->
<dimen name="pip_resize_edge_size">30dp</dimen>
+ <!-- The corner radius for PiP window. -->
+ <dimen name="pip_corner_radius">8dp</dimen>
+
<dimen name="default_gear_space">18dp</dimen>
<dimen name="cell_overlay_padding">18dp</dimen>
@@ -1183,6 +1183,9 @@
<dimen name="bubble_dismiss_target_padding_x">40dp</dimen>
<dimen name="bubble_dismiss_target_padding_y">20dp</dimen>
+ <dimen name="dismiss_circle_size">52dp</dimen>
+ <dimen name="dismiss_target_x_size">24dp</dimen>
+
<!-- Bubbles user education views -->
<dimen name="bubbles_manage_education_width">160dp</dimen>
<!-- The inset from the top bound of the manage button to place the user education. -->
@@ -1228,7 +1231,7 @@
<dimen name="control_height">106dp</dimen>
<dimen name="control_padding">12dp</dimen>
<dimen name="control_padding_adjustment">4dp</dimen>
- <dimen name="control_status_normal">12sp</dimen>
+ <dimen name="control_status_normal">14sp</dimen>
<dimen name="control_status_expanded">18sp</dimen>
<dimen name="control_base_item_margin">2dp</dimen>
<dimen name="control_status_padding">3dp</dimen>
@@ -1243,12 +1246,17 @@
<dimen name="controls_app_icon_size">32dp</dimen>
<dimen name="controls_app_icon_frame_side_padding">8dp</dimen>
<dimen name="controls_app_icon_frame_top_padding">4dp</dimen>
+ <dimen name="controls_app_icon_frame_bottom_padding">@dimen/controls_app_icon_frame_top_padding</dimen>
<dimen name="controls_app_bottom_margin">8dp</dimen>
<dimen name="controls_app_text_padding">8dp</dimen>
<dimen name="controls_app_divider_height">2dp</dimen>
<dimen name="controls_app_divider_side_margin">32dp</dimen>
<dimen name="controls_card_margin">2dp</dimen>
+ <item name="control_card_elevation" type="dimen" format="float">15</item>
+
+ <dimen name="controls_dialog_padding">8dp</dimen>
+ <dimen name="controls_dialog_control_width">200dp</dimen>
<!-- Screen Record -->
<dimen name="screenrecord_dialog_padding">18dp</dimen>
diff --git a/packages/SystemUI/res/values/integers.xml b/packages/SystemUI/res/values/integers.xml
index 4171cd9..f35f351 100644
--- a/packages/SystemUI/res/values/integers.xml
+++ b/packages/SystemUI/res/values/integers.xml
@@ -40,4 +40,8 @@
<integer name="magnification_default_scale">2</integer>
+ <!-- The position of the volume dialog on the screen.
+ See com.android.systemui.volume.VolumeDialogImpl.
+ Value 21 corresponds to RIGHT|CENTER_VERTICAL. -->
+ <integer name="volume_dialog_gravity">21</integer>
</resources>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index bcf3a26..3543073 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -2631,12 +2631,26 @@
<string name="controls_favorite_default_title">Controls</string>
<!-- Controls management controls screen subtitle [CHAR LIMIT=NONE] -->
<string name="controls_favorite_subtitle">Choose controls for quick access</string>
- <!-- Controls management controls screen favorites header [CHAR LIMIT=50] -->
- <string name="controls_favorite_header_favorites">Favorites</string>
- <!-- Controls management controls screen all header [CHAR LIMIT=50] -->
- <string name="controls_favorite_header_all">All</string>
+
<!-- Controls management controls screen error on load message [CHAR LIMIT=60] -->
<string name="controls_favorite_load_error">The list of all controls could not be loaded.</string>
<!-- Controls management controls screen header for Other zone [CHAR LIMIT=60] -->
<string name="controls_favorite_other_zone_header">Other</string>
+
+ <!-- Controls dialog title [CHAR LIMIT=30] -->
+ <string name="controls_dialog_title">Add to Quick Controls</string>
+ <!-- Controls dialog add to favorites [CHAR LIMIT=30] -->
+ <string name="controls_dialog_ok">Add to favorites</string>
+ <!-- Controls dialog message [CHAR LIMIT=NONE] -->
+ <string name="controls_dialog_message"><xliff:g id="app" example="System UI">%s</xliff:g> suggested this control to add to your favorites.</string>
+
+ <!-- Controls PIN entry dialog, switch to alphanumeric keyboard [CHAR LIMIT=100] -->
+ <string name="controls_pin_use_alphanumeric">PIN contains letters or symbols</string>
+ <!-- Controls PIN entry dialog, title [CHAR LIMIT=30] -->
+ <string name="controls_pin_verify">Verify device PIN</string>
+ <!-- Controls PIN entry dialog, text hint [CHAR LIMIT=30] -->
+ <string name="controls_pin_instructions">Enter PIN</string>
+
+ <!-- Tooltip to show in management screen when there are multiple structures [CHAR_LIMIT=50] -->
+ <string name="controls_structure_tooltip">Swipe to see other structures</string>
</resources>
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 2eccf58..20b88a1 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -650,6 +650,7 @@
<!-- Controls styles -->
<style name="Theme.ControlsManagement" parent="@android:style/Theme.DeviceDefault.NoActionBar">
<item name="android:windowIsTranslucent">false</item>
+ <item name="wallpaperTextColor">@*android:color/primary_text_material_dark</item>
</style>
<style name="TextAppearance.Control">
@@ -676,7 +677,7 @@
<style name="TextAppearance.Control.Status">
<item name="android:fontFamily">@*android:string/config_headlineFontFamilyMedium</item>
- <item name="android:textSize">@dimen/control_text_size</item>
+ <item name="android:textSize">@dimen/control_status_normal</item>
<item name="android:textColor">@color/control_primary_text</item>
</style>
@@ -697,4 +698,7 @@
<!-- used to override dark/light theming -->
<item name="*android:colorPopupBackground">@color/control_list_popup_background</item>
</style>
+
+ <style name="Theme.ControlsRequestDialog" parent="@style/Theme.SystemUI.MediaProjectionAlertDialog"/>
+
</resources>
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java
index e554dcd..ebed1fc 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/InputConsumerController.java
@@ -64,7 +64,7 @@
private final class InputEventReceiver extends BatchedInputEventReceiver {
public InputEventReceiver(InputChannel inputChannel, Looper looper) {
- super(inputChannel, looper, Choreographer.getSfInstance());
+ super(inputChannel, looper, Choreographer.getInstance());
}
@Override
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
index 4885ade..07bd3a0 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
@@ -78,6 +78,9 @@
public static final int SYSUI_STATE_QUICK_SETTINGS_EXPANDED = 1 << 11;
// Winscope tracing is enabled
public static final int SYSUI_STATE_TRACING_ENABLED = 1 << 12;
+ // The Assistant gesture should be constrained. It is up to the launcher implementation to
+ // decide how to constrain it
+ public static final int SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED = 1 << 13;
@Retention(RetentionPolicy.SOURCE)
@IntDef({SYSUI_STATE_SCREEN_PINNING,
@@ -92,7 +95,8 @@
SYSUI_STATE_OVERVIEW_DISABLED,
SYSUI_STATE_HOME_DISABLED,
SYSUI_STATE_SEARCH_DISABLED,
- SYSUI_STATE_TRACING_ENABLED
+ SYSUI_STATE_TRACING_ENABLED,
+ SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED
})
public @interface SystemUiStateFlags {}
@@ -112,6 +116,8 @@
str.add((flags & SYSUI_STATE_A11Y_BUTTON_CLICKABLE) != 0 ? "a11y_click" : "");
str.add((flags & SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE) != 0 ? "a11y_long_click" : "");
str.add((flags & SYSUI_STATE_TRACING_ENABLED) != 0 ? "tracing" : "");
+ str.add((flags & SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED) != 0
+ ? "asst_gesture_constrain" : "");
return str.toString();
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java
index ca88f13..aed7c21 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/RemoteAnimationTargetCompat.java
@@ -44,7 +44,9 @@
public final Rect clipRect;
public final int prefixOrderIndex;
public final Point position;
+ public final Rect localBounds;
public final Rect sourceContainerBounds;
+ public final Rect screenSpaceBounds;
public final boolean isNotInRecents;
public final Rect contentInsets;
@@ -57,7 +59,9 @@
isTranslucent = app.isTranslucent;
clipRect = app.clipRect;
position = app.position;
+ localBounds = app.localBounds;
sourceContainerBounds = app.sourceContainerBounds;
+ screenSpaceBounds = app.screenSpaceBounds;
prefixOrderIndex = app.prefixOrderIndex;
isNotInRecents = app.isNotInRecents;
contentInsets = app.contentInsets;
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java
index 8809d83..29100ef 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestReceiver.java
@@ -20,6 +20,7 @@
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.IBinder;
+import android.util.Size;
import android.view.SurfaceControl;
import android.view.SurfaceControlViewHost;
import android.view.View;
@@ -43,13 +44,27 @@
mOpacity = opacity;
}
- /** Called whenever a surface view request is received. */
+ /** See {@link #onReceive(Context, Bundle, View, Size)}. */
public void onReceive(Context context, Bundle bundle, View view) {
+ onReceive(context, bundle, view, null);
+ }
+
+ /**
+ * Called whenever a surface view request is received.
+ * @param view the view rendering content, on the receiver end of the surface request.
+ * @param viewSize when {@param viewSize} is not specified, we will use the surface control size
+ * to attach the view to the window.
+ */
+ public void onReceive(Context context, Bundle bundle, View view, Size viewSize) {
if (mSurfaceControlViewHost != null) {
mSurfaceControlViewHost.die();
}
SurfaceControl surfaceControl = SurfaceViewRequestUtils.getSurfaceControl(bundle);
if (surfaceControl != null) {
+ if (viewSize == null) {
+ viewSize = new Size(surfaceControl.getWidth(), surfaceControl.getHeight());
+ }
+
IBinder hostToken = SurfaceViewRequestUtils.getHostToken(bundle);
WindowlessWindowManager windowlessWindowManager =
@@ -59,13 +74,23 @@
context.getDisplayNoVerify(), windowlessWindowManager);
WindowManager.LayoutParams layoutParams =
new WindowManager.LayoutParams(
- surfaceControl.getWidth(),
- surfaceControl.getHeight(),
+ viewSize.getWidth(),
+ viewSize.getHeight(),
WindowManager.LayoutParams.TYPE_APPLICATION,
- 0,
+ WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
mOpacity);
- mSurfaceControlViewHost.addView(view, layoutParams);
+ // This aspect scales the view to fit in the surface and centers it
+ final float scale = Math.min(surfaceControl.getWidth() / (float) viewSize.getWidth(),
+ surfaceControl.getHeight() / (float) viewSize.getHeight());
+ view.setScaleX(scale);
+ view.setScaleY(scale);
+ view.setPivotX(0);
+ view.setPivotY(0);
+ view.setTranslationX((surfaceControl.getWidth() - scale * viewSize.getWidth()) / 2);
+ view.setTranslationY((surfaceControl.getHeight() - scale * viewSize.getHeight()) / 2);
+
+ mSurfaceControlViewHost.setView(view, layoutParams);
}
}
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java
index 0cbd541..4409276 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/SurfaceViewRequestUtils.java
@@ -36,7 +36,7 @@
}
/**
- * Retrieves the SurfaceControl from an Intent created by
+ * Retrieves the SurfaceControl from a bundle created by
* {@link #createSurfaceBundle(SurfaceView)}.
**/
public static SurfaceControl getSurfaceControl(Bundle bundle) {
@@ -44,7 +44,7 @@
}
/**
- * Retrieves the input token from an Intent created by
+ * Retrieves the input token from a bundle created by
* {@link #createSurfaceBundle(SurfaceView)}.
**/
public static @Nullable IBinder getHostToken(Bundle bundle) {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
index 1c6223b..9e9b9dc 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListener.java
@@ -37,7 +37,8 @@
public void onTaskSnapshotChanged(int taskId, ThumbnailData snapshot) { }
public void onActivityPinned(String packageName, int userId, int taskId, int stackId) { }
public void onActivityUnpinned() { }
- public void onPinnedActivityRestartAttempt(boolean clearedTask) { }
+ public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask) { }
public void onActivityForcedResizable(String packageName, int taskId, int reason) { }
public void onActivityDismissingDockedStack() { }
public void onActivityLaunchOnSecondaryDisplayFailed() { }
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
index cbdd3f8..ce9cbab 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java
@@ -30,6 +30,7 @@
import android.os.Trace;
import android.util.Log;
+import com.android.internal.os.SomeArgs;
import com.android.systemui.shared.recents.model.ThumbnailData;
import java.util.ArrayList;
@@ -120,11 +121,14 @@
}
@Override
- public void onPinnedActivityRestartAttempt(boolean clearedTask)
- throws RemoteException {
- mHandler.removeMessages(H.ON_PINNED_ACTIVITY_RESTART_ATTEMPT);
- mHandler.obtainMessage(H.ON_PINNED_ACTIVITY_RESTART_ATTEMPT, clearedTask ? 1 : 0, 0)
- .sendToTarget();
+ public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask) throws RemoteException {
+ final SomeArgs args = SomeArgs.obtain();
+ args.arg1 = task;
+ args.argi1 = homeTaskVisible ? 1 : 0;
+ args.argi2 = clearedTask ? 1 : 0;
+ mHandler.removeMessages(H.ON_ACTIVITY_RESTART_ATTEMPT);
+ mHandler.obtainMessage(H.ON_ACTIVITY_RESTART_ATTEMPT, args).sendToTarget();
}
@Override
@@ -236,7 +240,7 @@
private static final int ON_TASK_STACK_CHANGED = 1;
private static final int ON_TASK_SNAPSHOT_CHANGED = 2;
private static final int ON_ACTIVITY_PINNED = 3;
- private static final int ON_PINNED_ACTIVITY_RESTART_ATTEMPT = 4;
+ private static final int ON_ACTIVITY_RESTART_ATTEMPT = 4;
private static final int ON_ACTIVITY_FORCED_RESIZABLE = 6;
private static final int ON_ACTIVITY_DISMISSING_DOCKED_STACK = 7;
private static final int ON_TASK_PROFILE_LOCKED = 8;
@@ -296,10 +300,14 @@
}
break;
}
- case ON_PINNED_ACTIVITY_RESTART_ATTEMPT: {
+ case ON_ACTIVITY_RESTART_ATTEMPT: {
+ final SomeArgs args = (SomeArgs) msg.obj;
+ final RunningTaskInfo task = (RunningTaskInfo) args.arg1;
+ final boolean homeTaskVisible = args.argi1 != 0;
+ final boolean clearedTask = args.argi2 != 0;
for (int i = mTaskStackListeners.size() - 1; i >= 0; i--) {
- mTaskStackListeners.get(i).onPinnedActivityRestartAttempt(
- msg.arg1 != 0);
+ mTaskStackListeners.get(i).onActivityRestartAttempt(task,
+ homeTaskVisible, clearedTask);
}
break;
}
@@ -419,6 +427,9 @@
}
}
}
+ if (msg.obj instanceof SomeArgs) {
+ ((SomeArgs) msg.obj).recycle();
+ }
}
}
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java
index b813e21..7570c2c 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/WallpaperManagerCompat.java
@@ -18,7 +18,11 @@
import android.app.WallpaperManager;
import android.content.Context;
+import android.os.IBinder;
+/**
+ * @see WallpaperManager
+ */
public class WallpaperManagerCompat {
private final WallpaperManager mWallpaperManager;
@@ -26,7 +30,10 @@
mWallpaperManager = context.getSystemService(WallpaperManager.class);
}
- public void setWallpaperZoomOut(float zoom) {
- mWallpaperManager.setWallpaperZoomOut(zoom);
+ /**
+ * @see WallpaperManager#setWallpaperZoomOut(IBinder, float)
+ */
+ public void setWallpaperZoomOut(IBinder windowToken, float zoom) {
+ mWallpaperManager.setWallpaperZoomOut(windowToken, zoom);
}
}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
index 3cf07d1..ba8a1a9 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -19,9 +19,7 @@
import static android.view.ViewRootImpl.sNewInsetsMode;
import static android.view.WindowInsets.Type.ime;
import static android.view.WindowInsets.Type.systemBars;
-
import static com.android.systemui.DejankUtils.whitelistIpcs;
-
import static java.lang.Integer.max;
import android.app.Activity;
@@ -30,6 +28,7 @@
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
+import android.graphics.Rect;
import android.metrics.LogMaker;
import android.os.Handler;
import android.os.Looper;
@@ -512,8 +511,6 @@
boolean finish = false;
boolean strongAuth = false;
int eventSubtype = -1;
- mCurrentSecuritySelection = whitelistIpcs(() ->
- mSecurityModel.getSecurityMode(targetUserId));
if (mUpdateMonitor.getUserHasTrust(targetUserId)) {
finish = true;
eventSubtype = BOUNCER_DISMISS_EXTENDED_ACCESS;
@@ -521,8 +518,13 @@
finish = true;
eventSubtype = BOUNCER_DISMISS_BIOMETRIC;
} else if (SecurityMode.None == mCurrentSecuritySelection) {
- finish = true; // no security required
- eventSubtype = BOUNCER_DISMISS_NONE_SECURITY;
+ SecurityMode securityMode = mSecurityModel.getSecurityMode(targetUserId);
+ if (SecurityMode.None == securityMode) {
+ finish = true; // no security required
+ eventSubtype = BOUNCER_DISMISS_NONE_SECURITY;
+ } else {
+ showSecurityScreen(securityMode); // switch to the alternate security view
+ }
} else if (authenticated) {
switch (mCurrentSecuritySelection) {
case Pattern:
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 4508fc7..431c451 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -379,7 +379,7 @@
if (DEBUG_SIM_STATES) {
Log.v(TAG, "onSubscriptionInfoChanged()");
List<SubscriptionInfo> sil = mSubscriptionManager
- .getActiveAndHiddenSubscriptionInfoList();
+ .getCompleteActiveSubscriptionInfoList();
if (sil != null) {
for (SubscriptionInfo subInfo : sil) {
Log.v(TAG, "SubInfo:" + subInfo);
@@ -433,10 +433,10 @@
public List<SubscriptionInfo> getSubscriptionInfo(boolean forceReload) {
List<SubscriptionInfo> sil = mSubscriptionInfo;
if (sil == null || forceReload) {
- sil = mSubscriptionManager.getActiveAndHiddenSubscriptionInfoList();
+ sil = mSubscriptionManager.getCompleteActiveSubscriptionInfoList();
}
if (sil == null) {
- // getActiveAndHiddenSubscriptionInfoList was null callers expect an empty list.
+ // getCompleteActiveSubscriptionInfoList was null callers expect an empty list.
mSubscriptionInfo = new ArrayList<SubscriptionInfo>();
} else {
mSubscriptionInfo = sil;
@@ -1086,7 +1086,7 @@
mHandler.sendEmptyMessage(MSG_TIME_UPDATE);
} else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
final Message msg = mHandler.obtainMessage(
- MSG_TIMEZONE_UPDATE, intent.getStringExtra("time-zone"));
+ MSG_TIMEZONE_UPDATE, intent.getStringExtra(Intent.EXTRA_TIMEZONE));
mHandler.sendMessage(msg);
} else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardViewController.java
new file mode 100644
index 0000000..fc29f5c
--- /dev/null
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardViewController.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2020 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.keyguard;
+
+import android.os.Bundle;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewRootImpl;
+
+import com.android.systemui.keyguard.DismissCallbackRegistry;
+import com.android.systemui.keyguard.KeyguardViewMediator;
+import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.statusbar.phone.BiometricUnlockController;
+import com.android.systemui.statusbar.phone.KeyguardBypassController;
+import com.android.systemui.statusbar.phone.NotificationPanelViewController;
+import com.android.systemui.statusbar.phone.StatusBar;
+
+/**
+ * Interface to control Keyguard View. It should be implemented by KeyguardViewManagers, which
+ * should, in turn, be injected into {@link KeyguardViewMediator}.
+ */
+public interface KeyguardViewController {
+ /**
+ * Shows Keyguard.
+ * @param options
+ */
+ void show(Bundle options);
+
+ /**
+ * Hides Keyguard with the fade-out animation as configured by the parameters provided.
+ *
+ * @param startTime
+ * @param fadeoutDuration
+ */
+ void hide(long startTime, long fadeoutDuration);
+
+ /**
+ * Resets the state of Keyguard View.
+ * @param hideBouncerWhenShowing
+ */
+ void reset(boolean hideBouncerWhenShowing);
+
+ /**
+ * Called when the device started going to sleep.
+ */
+ void onStartedGoingToSleep();
+
+ /**
+ * Called when the device has finished going to sleep.
+ */
+ void onFinishedGoingToSleep();
+
+ /**
+ * Called when the device started waking up.
+ */
+ void onStartedWakingUp();
+
+ /**
+ * Called when the device started turning on.
+ */
+ void onScreenTurningOn();
+
+ /**
+ * Called when the device has finished turning on.
+ */
+ void onScreenTurnedOn();
+
+ /**
+ * Sets whether the Keyguard needs input.
+ * @param needsInput
+ */
+ void setNeedsInput(boolean needsInput);
+
+ /**
+ * Called when cancel button in bouncer is pressed.
+ */
+ void onCancelClicked();
+
+ /**
+ * Sets whether the keyguard is occluded by another window.
+ *
+ * @param occluded
+ * @param animate
+ */
+ void setOccluded(boolean occluded, boolean animate);
+
+ /**
+ * @return Whether the keyguard is showing
+ */
+ boolean isShowing();
+
+ /**
+ * Dismisses the keyguard by going to the next screen or making it gone.
+ */
+ void dismissAndCollapse();
+
+ /**
+ * Notifies that Keyguard is just about to go away.
+ */
+ void keyguardGoingAway();
+
+ /**
+ * @return Whether window animation for unlock should be disabled.
+ */
+ boolean shouldDisableWindowAnimationsForUnlock();
+
+ /**
+ * @return Whether the keyguard is going to notification shade.
+ */
+ boolean isGoingToNotificationShade();
+
+ /**
+ * @return Whether subtle animation should be used for unlocking the device.
+ */
+ boolean isUnlockWithWallpaper();
+
+ /**
+ * @return Whether subtle animation should be used for unlocking the device.
+ */
+ boolean shouldSubtleWindowAnimationsForUnlock();
+
+ /**
+ * Starts the animation before we dismiss Keyguard, i.e. an disappearing animation on the
+ * security view of the bouncer.
+ *
+ * @param finishRunnable the runnable to be run after the animation finished, or {@code null} if
+ * no action should be run
+ */
+ void startPreHideAnimation(Runnable finishRunnable);
+
+ /**
+ * @return the ViewRootImpl of the View where the Keyguard is mounted.
+ */
+ ViewRootImpl getViewRootImpl();
+
+ // TODO: Deprecate registerStatusBar in KeyguardViewController interface. It is currently
+ // only used for testing purposes in StatusBarKeyguardViewManager, and it prevents us from
+ // achieving complete abstraction away from where the Keyguard View is mounted.
+
+ /**
+ * Registers the StatusBar to which this Keyguard View is mounted.
+ *
+ * @param statusBar
+ * @param container
+ * @param notificationPanelViewController
+ * @param biometricUnlockController
+ * @param dismissCallbackRegistry
+ * @param lockIconContainer
+ * @param notificationContainer
+ * @param bypassController
+ * @param falsingManager
+ */
+ void registerStatusBar(StatusBar statusBar,
+ ViewGroup container,
+ NotificationPanelViewController notificationPanelViewController,
+ BiometricUnlockController biometricUnlockController,
+ DismissCallbackRegistry dismissCallbackRegistry,
+ ViewGroup lockIconContainer, View notificationContainer,
+ KeyguardBypassController bypassController, FalsingManager falsingManager);
+}
diff --git a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
index 0367464..2200b22 100644
--- a/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
+++ b/packages/SystemUI/src/com/android/keyguard/clock/ClockManager.java
@@ -43,6 +43,7 @@
import com.android.systemui.util.InjectionInflationController;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -74,8 +75,8 @@
private final ContentObserver mContentObserver =
new ContentObserver(mMainHandler) {
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
- super.onChange(selfChange, uri, userId);
+ public void onChange(boolean selfChange, Collection<Uri> uris,
+ int flags, int userId) {
if (Objects.equals(userId,
mCurrentUserObservable.getCurrentUser().getValue())) {
reload();
diff --git a/packages/SystemUI/src/com/android/systemui/CameraAvailabilityListener.kt b/packages/SystemUI/src/com/android/systemui/CameraAvailabilityListener.kt
index 24fa91b..284074e 100644
--- a/packages/SystemUI/src/com/android/systemui/CameraAvailabilityListener.kt
+++ b/packages/SystemUI/src/com/android/systemui/CameraAvailabilityListener.kt
@@ -26,7 +26,7 @@
import kotlin.math.roundToInt
-const val TAG = "CameraOpTransitionController"
+const val TAG = "CameraAvailabilityListener"
/**
* Listens for usage of the Camera and controls the ScreenDecorations transition to show extra
diff --git a/packages/SystemUI/src/com/android/systemui/Dependency.java b/packages/SystemUI/src/com/android/systemui/Dependency.java
index a868cf5..b6152da 100644
--- a/packages/SystemUI/src/com/android/systemui/Dependency.java
+++ b/packages/SystemUI/src/com/android/systemui/Dependency.java
@@ -71,12 +71,11 @@
import com.android.systemui.statusbar.NotificationViewHierarchyManager;
import com.android.systemui.statusbar.SmartReplyController;
import com.android.systemui.statusbar.VibratorHelper;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager.KeyguardEnvironment;
import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.ChannelEditorDialogController;
import com.android.systemui.statusbar.notification.row.NotificationBlockingHelperManager;
@@ -289,7 +288,6 @@
@Inject Lazy<NotificationLogger> mNotificationLogger;
@Inject Lazy<NotificationViewHierarchyManager> mNotificationViewHierarchyManager;
@Inject Lazy<NotificationFilter> mNotificationFilter;
- @Inject Lazy<NotificationInterruptionStateProvider> mNotificationInterruptionStateProvider;
@Inject Lazy<KeyguardDismissUtil> mKeyguardDismissUtil;
@Inject Lazy<SmartReplyController> mSmartReplyController;
@Inject Lazy<RemoteInputQuickSettingsDisabler> mRemoteInputQuickSettingsDisabler;
@@ -489,8 +487,6 @@
mProviders.put(NotificationViewHierarchyManager.class,
mNotificationViewHierarchyManager::get);
mProviders.put(NotificationFilter.class, mNotificationFilter::get);
- mProviders.put(NotificationInterruptionStateProvider.class,
- mNotificationInterruptionStateProvider::get);
mProviders.put(KeyguardDismissUtil.class, mKeyguardDismissUtil::get);
mProviders.put(SmartReplyController.class, mSmartReplyController::get);
mProviders.put(RemoteInputQuickSettingsDisabler.class,
diff --git a/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java b/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java
deleted file mode 100644
index ad2e002..0000000
--- a/packages/SystemUI/src/com/android/systemui/HardwareUiLayout.java
+++ /dev/null
@@ -1,570 +0,0 @@
-/*
- * Copyright (C) 2017 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;
-
-import static com.android.systemui.util.leak.RotationUtils.ROTATION_LANDSCAPE;
-import static com.android.systemui.util.leak.RotationUtils.ROTATION_NONE;
-import static com.android.systemui.util.leak.RotationUtils.ROTATION_SEASCAPE;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
-import android.content.Context;
-import android.provider.Settings;
-import android.util.AttributeSet;
-import android.view.Gravity;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewOutlineProvider;
-import android.view.ViewTreeObserver;
-import android.widget.LinearLayout;
-
-import com.android.systemui.tuner.TunerService;
-import com.android.systemui.tuner.TunerService.Tunable;
-import com.android.systemui.util.leak.RotationUtils;
-
-/**
- * Layout for placing two containers at a specific physical position on the device, relative to the
- * device's hardware, regardless of screen rotation.
- */
-public class HardwareUiLayout extends MultiListLayout implements Tunable {
-
- private static final String EDGE_BLEED = "sysui_hwui_edge_bleed";
- private static final String ROUNDED_DIVIDER = "sysui_hwui_rounded_divider";
- private final int[] mTmp2 = new int[2];
- private ViewGroup mList;
- private ViewGroup mSeparatedView;
- private int mOldHeight;
- private boolean mAnimating;
- private AnimatorSet mAnimation;
- private View mDivision;
- private HardwareBgDrawable mListBackground;
- private HardwareBgDrawable mSeparatedViewBackground;
- private Animator mAnimator;
- private boolean mCollapse;
- private int mEndPoint;
- private boolean mEdgeBleed;
- private boolean mRoundedDivider;
- private boolean mRotatedBackground;
- private boolean mSwapOrientation = true;
-
- public HardwareUiLayout(Context context, AttributeSet attrs) {
- super(context, attrs);
- // Manually re-initialize mRotation to portrait-mode, since this view must always
- // be constructed in portrait mode and rotated into the correct initial position.
- mRotation = ROTATION_NONE;
- updateSettings();
- }
-
- @Override
- protected ViewGroup getSeparatedView() {
- return findViewById(com.android.systemui.R.id.separated_button);
- }
-
- @Override
- protected ViewGroup getListView() {
- return findViewById(android.R.id.list);
- }
-
- @Override
- protected void onAttachedToWindow() {
- super.onAttachedToWindow();
- updateSettings();
- Dependency.get(TunerService.class).addTunable(this, EDGE_BLEED, ROUNDED_DIVIDER);
- getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsListener);
- }
-
- @Override
- protected void onDetachedFromWindow() {
- super.onDetachedFromWindow();
- getViewTreeObserver().removeOnComputeInternalInsetsListener(mInsetsListener);
- Dependency.get(TunerService.class).removeTunable(this);
- }
-
- @Override
- public void onTuningChanged(String key, String newValue) {
- updateSettings();
- }
-
- private void updateSettings() {
- mEdgeBleed = Settings.Secure.getInt(getContext().getContentResolver(),
- EDGE_BLEED, 0) != 0;
- mRoundedDivider = Settings.Secure.getInt(getContext().getContentResolver(),
- ROUNDED_DIVIDER, 0) != 0;
- updateEdgeMargin(mEdgeBleed ? 0 : getEdgePadding());
- mListBackground = new HardwareBgDrawable(mRoundedDivider, !mEdgeBleed, getContext());
- mSeparatedViewBackground = new HardwareBgDrawable(mRoundedDivider, !mEdgeBleed,
- getContext());
- if (mList != null) {
- mList.setBackground(mListBackground);
- mSeparatedView.setBackground(mSeparatedViewBackground);
- requestLayout();
- }
- }
-
- private void updateEdgeMargin(int edge) {
- if (mList != null) {
- MarginLayoutParams params = (MarginLayoutParams) mList.getLayoutParams();
- if (mRotation == ROTATION_LANDSCAPE) {
- params.topMargin = edge;
- } else if (mRotation == ROTATION_SEASCAPE) {
- params.bottomMargin = edge;
- } else {
- params.rightMargin = edge;
- }
- mList.setLayoutParams(params);
- }
-
- if (mSeparatedView != null) {
- MarginLayoutParams params = (MarginLayoutParams) mSeparatedView.getLayoutParams();
- if (mRotation == ROTATION_LANDSCAPE) {
- params.topMargin = edge;
- } else if (mRotation == ROTATION_SEASCAPE) {
- params.bottomMargin = edge;
- } else {
- params.rightMargin = edge;
- }
- mSeparatedView.setLayoutParams(params);
- }
- }
-
- private int getEdgePadding() {
- return getContext().getResources().getDimensionPixelSize(R.dimen.edge_margin);
- }
-
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- if (mList == null) {
- if (getChildCount() != 0) {
- mList = getListView();
- mList.setBackground(mListBackground);
- mSeparatedView = getSeparatedView();
- mSeparatedView.setBackground(mSeparatedViewBackground);
- updateEdgeMargin(mEdgeBleed ? 0 : getEdgePadding());
- mOldHeight = mList.getMeasuredHeight();
-
- // Must be called to initialize view rotation correctly.
- // Requires LayoutParams, hence why this isn't called during the constructor.
- updateRotation();
- } else {
- return;
- }
- }
- int newHeight = mList.getMeasuredHeight();
- if (newHeight != mOldHeight) {
- animateChild(mOldHeight, newHeight);
- }
-
- post(() -> updatePaddingAndGravityIfTooTall());
- post(() -> updatePosition());
- }
-
- public void setSwapOrientation(boolean swapOrientation) {
- mSwapOrientation = swapOrientation;
- }
-
- private void updateRotation() {
- int rotation = RotationUtils.getRotation(getContext());
- if (rotation != mRotation) {
- rotate(mRotation, rotation);
- mRotation = rotation;
- }
- }
-
- /**
- * Requires LayoutParams to be set to work correctly, and therefore must be run after after
- * the HardwareUILayout has been added to the view hierarchy.
- */
- protected void rotate(int from, int to) {
- super.rotate(from, to);
- if (from != ROTATION_NONE && to != ROTATION_NONE) {
- // Rather than handling this confusing case, just do 2 rotations.
- rotate(from, ROTATION_NONE);
- rotate(ROTATION_NONE, to);
- return;
- }
- if (from == ROTATION_LANDSCAPE || to == ROTATION_SEASCAPE) {
- rotateRight();
- } else {
- rotateLeft();
- }
- if (mAdapter.hasSeparatedItems()) {
- if (from == ROTATION_SEASCAPE || to == ROTATION_SEASCAPE) {
- // Separated view has top margin, so seascape separated view need special rotation,
- // not a full left or right rotation.
- swapLeftAndTop(mSeparatedView);
- } else if (from == ROTATION_LANDSCAPE) {
- rotateRight(mSeparatedView);
- } else {
- rotateLeft(mSeparatedView);
- }
- }
- if (to != ROTATION_NONE) {
- if (mList instanceof LinearLayout) {
- mRotatedBackground = true;
- mListBackground.setRotatedBackground(true);
- mSeparatedViewBackground.setRotatedBackground(true);
- LinearLayout linearLayout = (LinearLayout) mList;
- if (mSwapOrientation) {
- linearLayout.setOrientation(LinearLayout.HORIZONTAL);
- setOrientation(LinearLayout.HORIZONTAL);
- }
- swapDimens(mList);
- swapDimens(mSeparatedView);
- }
- } else {
- if (mList instanceof LinearLayout) {
- mRotatedBackground = false;
- mListBackground.setRotatedBackground(false);
- mSeparatedViewBackground.setRotatedBackground(false);
- LinearLayout linearLayout = (LinearLayout) mList;
- if (mSwapOrientation) {
- linearLayout.setOrientation(LinearLayout.VERTICAL);
- setOrientation(LinearLayout.VERTICAL);
- }
- swapDimens(mList);
- swapDimens(mSeparatedView);
- }
- }
- }
-
- @Override
- public void onUpdateList() {
- super.onUpdateList();
-
- for (int i = 0; i < mAdapter.getCount(); i++) {
- ViewGroup parent;
- boolean separated = mAdapter.shouldBeSeparated(i);
- if (separated) {
- parent = getSeparatedView();
- } else {
- parent = getListView();
- }
- View v = mAdapter.getView(i, null, parent);
- parent.addView(v);
- }
- }
-
- private void rotateRight() {
- rotateRight(this);
- rotateRight(mList);
- swapDimens(this);
-
- LayoutParams p = (LayoutParams) mList.getLayoutParams();
- p.gravity = rotateGravityRight(p.gravity);
- mList.setLayoutParams(p);
-
- LayoutParams separatedViewLayoutParams = (LayoutParams) mSeparatedView.getLayoutParams();
- separatedViewLayoutParams.gravity = rotateGravityRight(separatedViewLayoutParams.gravity);
- mSeparatedView.setLayoutParams(separatedViewLayoutParams);
-
- setGravity(rotateGravityRight(getGravity()));
- }
-
- private void swapDimens(View v) {
- ViewGroup.LayoutParams params = v.getLayoutParams();
- int h = params.width;
- params.width = params.height;
- params.height = h;
- v.setLayoutParams(params);
- }
-
- private int rotateGravityRight(int gravity) {
- int retGravity = 0;
- int layoutDirection = getLayoutDirection();
- final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
- final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
-
- switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
- case Gravity.CENTER_HORIZONTAL:
- retGravity |= Gravity.CENTER_VERTICAL;
- break;
- case Gravity.RIGHT:
- retGravity |= Gravity.BOTTOM;
- break;
- case Gravity.LEFT:
- default:
- retGravity |= Gravity.TOP;
- break;
- }
-
- switch (verticalGravity) {
- case Gravity.CENTER_VERTICAL:
- retGravity |= Gravity.CENTER_HORIZONTAL;
- break;
- case Gravity.BOTTOM:
- retGravity |= Gravity.LEFT;
- break;
- case Gravity.TOP:
- default:
- retGravity |= Gravity.RIGHT;
- break;
- }
- return retGravity;
- }
-
- private void rotateLeft() {
- rotateLeft(this);
- rotateLeft(mList);
- swapDimens(this);
-
- LayoutParams p = (LayoutParams) mList.getLayoutParams();
- p.gravity = rotateGravityLeft(p.gravity);
- mList.setLayoutParams(p);
-
- LayoutParams separatedViewLayoutParams = (LayoutParams) mSeparatedView.getLayoutParams();
- separatedViewLayoutParams.gravity = rotateGravityLeft(separatedViewLayoutParams.gravity);
- mSeparatedView.setLayoutParams(separatedViewLayoutParams);
-
- setGravity(rotateGravityLeft(getGravity()));
- }
-
- private int rotateGravityLeft(int gravity) {
- if (gravity == -1) {
- gravity = Gravity.TOP | Gravity.START;
- }
- int retGravity = 0;
- int layoutDirection = getLayoutDirection();
- final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
- final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
-
- switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
- case Gravity.CENTER_HORIZONTAL:
- retGravity |= Gravity.CENTER_VERTICAL;
- break;
- case Gravity.RIGHT:
- retGravity |= Gravity.TOP;
- break;
- case Gravity.LEFT:
- default:
- retGravity |= Gravity.BOTTOM;
- break;
- }
-
- switch (verticalGravity) {
- case Gravity.CENTER_VERTICAL:
- retGravity |= Gravity.CENTER_HORIZONTAL;
- break;
- case Gravity.BOTTOM:
- retGravity |= Gravity.RIGHT;
- break;
- case Gravity.TOP:
- default:
- retGravity |= Gravity.LEFT;
- break;
- }
- return retGravity;
- }
-
- private void rotateLeft(View v) {
- v.setPadding(v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom(),
- v.getPaddingLeft());
- MarginLayoutParams params = (MarginLayoutParams) v.getLayoutParams();
- params.setMargins(params.topMargin, params.rightMargin, params.bottomMargin,
- params.leftMargin);
- v.setLayoutParams(params);
- }
-
- private void rotateRight(View v) {
- v.setPadding(v.getPaddingBottom(), v.getPaddingLeft(), v.getPaddingTop(),
- v.getPaddingRight());
- MarginLayoutParams params = (MarginLayoutParams) v.getLayoutParams();
- params.setMargins(params.bottomMargin, params.leftMargin, params.topMargin,
- params.rightMargin);
- v.setLayoutParams(params);
- }
-
- private void swapLeftAndTop(View v) {
- v.setPadding(v.getPaddingTop(), v.getPaddingLeft(), v.getPaddingBottom(),
- v.getPaddingRight());
- MarginLayoutParams params = (MarginLayoutParams) v.getLayoutParams();
- params.setMargins(params.topMargin, params.leftMargin, params.bottomMargin,
- params.rightMargin);
- v.setLayoutParams(params);
- }
-
- @Override
- protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
- super.onLayout(changed, left, top, right, bottom);
-
- post(() -> updatePosition());
-
- }
-
- private void animateChild(int oldHeight, int newHeight) {
- if (true) return;
- if (mAnimating) {
- mAnimation.cancel();
- }
- mAnimating = true;
- mAnimation = new AnimatorSet();
- mAnimation.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mAnimating = false;
- }
- });
- int fromTop = mList.getTop();
- int fromBottom = mList.getBottom();
- int toTop = fromTop - ((newHeight - oldHeight) / 2);
- int toBottom = fromBottom + ((newHeight - oldHeight) / 2);
- ObjectAnimator top = ObjectAnimator.ofInt(mList, "top", fromTop, toTop);
- top.addUpdateListener(animation -> mListBackground.invalidateSelf());
- mAnimation.playTogether(top,
- ObjectAnimator.ofInt(mList, "bottom", fromBottom, toBottom));
- }
-
- public void setDivisionView(View v) {
- mDivision = v;
- if (mDivision != null) {
- mDivision.addOnLayoutChangeListener(
- (v1, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) ->
- updatePosition());
- }
- updatePosition();
- }
-
- private void updatePosition() {
- if (mList == null) return;
- // If got separated button, setRotatedBackground to false,
- // all items won't get white background.
- boolean separated = mAdapter.hasSeparatedItems();
- mListBackground.setRotatedBackground(separated);
- mSeparatedViewBackground.setRotatedBackground(separated);
- if (mDivision != null && mDivision.getVisibility() == VISIBLE) {
- int index = mRotatedBackground ? 0 : 1;
- mDivision.getLocationOnScreen(mTmp2);
- float trans = mRotatedBackground ? mDivision.getTranslationX()
- : mDivision.getTranslationY();
- int viewTop = (int) (mTmp2[index] + trans);
- mList.getLocationOnScreen(mTmp2);
- viewTop -= mTmp2[index];
- setCutPoint(viewTop);
- } else {
- setCutPoint(mList.getMeasuredHeight());
- }
- }
-
- private void setCutPoint(int point) {
- int curPoint = mListBackground.getCutPoint();
- if (curPoint == point) return;
- if (getAlpha() == 0 || curPoint == 0) {
- mListBackground.setCutPoint(point);
- return;
- }
- if (mAnimator != null) {
- if (mEndPoint == point) {
- return;
- }
- mAnimator.cancel();
- }
- mEndPoint = point;
- mAnimator = ObjectAnimator.ofInt(mListBackground, "cutPoint", curPoint, point);
- if (mCollapse) {
- mAnimator.setStartDelay(300);
- mCollapse = false;
- }
- mAnimator.start();
- }
-
- // If current power menu height larger then screen height, remove padding to break power menu
- // alignment and set menu center vertical within the screen.
- private void updatePaddingAndGravityIfTooTall() {
- int defaultTopPadding;
- int viewsTotalHeight;
- int separatedViewTopMargin;
- int screenHeight;
- int totalHeight;
- int targetGravity;
- boolean separated = mAdapter.hasSeparatedItems();
- MarginLayoutParams params = (MarginLayoutParams) mSeparatedView.getLayoutParams();
- switch (RotationUtils.getRotation(getContext())) {
- case RotationUtils.ROTATION_LANDSCAPE:
- defaultTopPadding = getPaddingLeft();
- viewsTotalHeight = mList.getMeasuredWidth() + mSeparatedView.getMeasuredWidth();
- separatedViewTopMargin = separated ? params.leftMargin : 0;
- screenHeight = getMeasuredWidth();
- targetGravity = Gravity.CENTER_HORIZONTAL|Gravity.TOP;
- break;
- case RotationUtils.ROTATION_SEASCAPE:
- defaultTopPadding = getPaddingRight();
- viewsTotalHeight = mList.getMeasuredWidth() + mSeparatedView.getMeasuredWidth();
- separatedViewTopMargin = separated ? params.leftMargin : 0;
- screenHeight = getMeasuredWidth();
- targetGravity = Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM;
- break;
- default: // Portrait
- defaultTopPadding = getPaddingTop();
- viewsTotalHeight = mList.getMeasuredHeight() + mSeparatedView.getMeasuredHeight();
- separatedViewTopMargin = separated ? params.topMargin : 0;
- screenHeight = getMeasuredHeight();
- targetGravity = Gravity.CENTER_VERTICAL|Gravity.RIGHT;
- break;
- }
- totalHeight = defaultTopPadding + viewsTotalHeight + separatedViewTopMargin;
- if (totalHeight >= screenHeight) {
- setPadding(0, 0, 0, 0);
- setGravity(targetGravity);
- }
- }
-
- @Override
- public ViewOutlineProvider getOutlineProvider() {
- return super.getOutlineProvider();
- }
-
- public void setCollapse() {
- mCollapse = true;
- }
-
- private final ViewTreeObserver.OnComputeInternalInsetsListener mInsetsListener = inoutInfo -> {
- if (mHasOutsideTouch || (mList == null)) {
- inoutInfo.setTouchableInsets(
- ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME);
- return;
- }
- inoutInfo.setTouchableInsets(
- ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT);
- inoutInfo.contentInsets.set(mList.getLeft(), mList.getTop(),
- 0, getBottom() - mList.getBottom());
- };
-
- private float getAnimationDistance() {
- return getContext().getResources().getDimension(
- com.android.systemui.R.dimen.global_actions_panel_width) / 2;
- }
-
- @Override
- public float getAnimationOffsetX() {
- if (RotationUtils.getRotation(mContext) == ROTATION_NONE) {
- return getAnimationDistance();
- }
- return 0;
- }
-
- @Override
- public float getAnimationOffsetY() {
- switch (RotationUtils.getRotation(getContext())) {
- case RotationUtils.ROTATION_LANDSCAPE:
- return -getAnimationDistance();
- case RotationUtils.ROTATION_SEASCAPE:
- return getAnimationDistance();
- default: // Portrait
- return 0;
- }
- }
-}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
index dbcdead..23fa645 100644
--- a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
@@ -203,6 +203,11 @@
}
}
+ @Override
+ public boolean shouldZoomOutWallpaper() {
+ return true;
+ }
+
private void waitForBackgroundRendering() {
synchronized (mMonitor) {
try {
diff --git a/packages/SystemUI/src/com/android/systemui/Prefs.java b/packages/SystemUI/src/com/android/systemui/Prefs.java
index 5e6589f..6aa2326 100644
--- a/packages/SystemUI/src/com/android/systemui/Prefs.java
+++ b/packages/SystemUI/src/com/android/systemui/Prefs.java
@@ -59,7 +59,8 @@
Key.TOUCHED_RINGER_TOGGLE,
Key.HAS_SEEN_ODI_CAPTIONS_TOOLTIP,
Key.HAS_SEEN_BUBBLES_EDUCATION,
- Key.HAS_SEEN_BUBBLES_MANAGE_EDUCATION
+ Key.HAS_SEEN_BUBBLES_MANAGE_EDUCATION,
+ Key.CONTROLS_STRUCTURE_SWIPE_TOOLTIP_COUNT
})
public @interface Key {
@Deprecated
@@ -107,6 +108,7 @@
String HAS_SEEN_ODI_CAPTIONS_TOOLTIP = "HasSeenODICaptionsTooltip";
String HAS_SEEN_BUBBLES_EDUCATION = "HasSeenBubblesOnboarding";
String HAS_SEEN_BUBBLES_MANAGE_EDUCATION = "HasSeenBubblesManageOnboarding";
+ String CONTROLS_STRUCTURE_SWIPE_TOOLTIP_COUNT = "ControlsStructureSwipeTooltipCount";
}
public static boolean getBoolean(Context context, @Key String key, boolean defaultValue) {
diff --git a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
index 1324524..a8a3cae 100644
--- a/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
+++ b/packages/SystemUI/src/com/android/systemui/ScreenDecorations.java
@@ -28,6 +28,9 @@
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ValueAnimator;
import android.annotation.Dimension;
import android.annotation.NonNull;
import android.app.ActivityManager;
@@ -45,7 +48,9 @@
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
+import android.graphics.RectF;
import android.graphics.Region;
+import android.graphics.drawable.VectorDrawable;
import android.hardware.display.DisplayManager;
import android.os.Handler;
import android.os.HandlerThread;
@@ -122,8 +127,9 @@
private WindowManager mWindowManager;
private int mRotation;
private SecureSetting mColorInversionSetting;
- private boolean mPendingRotationChange;
private Handler mHandler;
+ private boolean mPendingRotationChange;
+ private boolean mIsRoundedCornerMultipleRadius;
private CameraAvailabilityListener.CameraTransitionCallback mCameraTransitionCallback =
new CameraAvailabilityListener.CameraTransitionCallback() {
@@ -190,6 +196,8 @@
mRotation = mContext.getDisplay().getRotation();
mWindowManager = mContext.getSystemService(WindowManager.class);
mDisplayManager = mContext.getSystemService(DisplayManager.class);
+ mIsRoundedCornerMultipleRadius = mContext.getResources().getBoolean(
+ R.bool.config_roundedCornerMultipleRadius);
updateRoundedCornerRadii();
setupDecorations();
setupCameraListener();
@@ -568,15 +576,22 @@
com.android.internal.R.dimen.rounded_corner_radius_top);
final int newRoundedDefaultBottom = mContext.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.rounded_corner_radius_bottom);
-
final boolean roundedCornersChanged = mRoundedDefault != newRoundedDefault
|| mRoundedDefaultBottom != newRoundedDefaultBottom
|| mRoundedDefaultTop != newRoundedDefaultTop;
if (roundedCornersChanged) {
- mRoundedDefault = newRoundedDefault;
- mRoundedDefaultTop = newRoundedDefaultTop;
- mRoundedDefaultBottom = newRoundedDefaultBottom;
+ // If config_roundedCornerMultipleRadius set as true, ScreenDecorations respect the
+ // max(width, height) size of drawable/rounded.xml instead of rounded_corner_radius
+ if (mIsRoundedCornerMultipleRadius) {
+ final VectorDrawable d = (VectorDrawable) mContext.getDrawable(R.drawable.rounded);
+ mRoundedDefault = Math.max(d.getIntrinsicWidth(), d.getIntrinsicHeight());
+ mRoundedDefaultTop = mRoundedDefaultBottom = mRoundedDefault;
+ } else {
+ mRoundedDefault = newRoundedDefault;
+ mRoundedDefaultTop = newRoundedDefaultTop;
+ mRoundedDefaultBottom = newRoundedDefaultBottom;
+ }
onTuningChanged(SIZE, null);
}
}
@@ -627,7 +642,8 @@
}
private boolean hasRoundedCorners() {
- return mRoundedDefault > 0 || mRoundedDefaultBottom > 0 || mRoundedDefaultTop > 0;
+ return mRoundedDefault > 0 || mRoundedDefaultBottom > 0 || mRoundedDefaultTop > 0
+ || mIsRoundedCornerMultipleRadius;
}
private boolean shouldShowRoundedCorner(@BoundsPosition int pos) {
@@ -714,14 +730,18 @@
public static class DisplayCutoutView extends View implements DisplayManager.DisplayListener,
RegionInterceptableView {
+ private static final float HIDDEN_CAMERA_PROTECTION_SCALE = 0.5f;
+
private final DisplayInfo mInfo = new DisplayInfo();
private final Paint mPaint = new Paint();
private final List<Rect> mBounds = new ArrayList();
private final Rect mBoundingRect = new Rect();
private final Path mBoundingPath = new Path();
- // Don't initialize these because they are cached elsewhere and may not exist
- private Rect mProtectionRect;
+ // Don't initialize these yet because they may never exist
+ private RectF mProtectionRect;
+ private RectF mProtectionRectOrig;
private Path mProtectionPath;
+ private Path mProtectionPathOrig;
private Rect mTotalBounds = new Rect();
// Whether or not to show the cutout protection path
private boolean mShowProtection = false;
@@ -732,6 +752,8 @@
private int mRotation;
private int mInitialPosition;
private int mPosition;
+ private float mCameraProtectionProgress = HIDDEN_CAMERA_PROTECTION_SCALE;
+ private ValueAnimator mCameraProtectionAnimator;
public DisplayCutoutView(Context context, @BoundsPosition int pos,
ScreenDecorations decorations) {
@@ -770,17 +792,18 @@
getLocationOnScreen(mLocation);
canvas.translate(-mLocation[0], -mLocation[1]);
- if (mShowProtection && !mProtectionRect.isEmpty()) {
- mPaint.setColor(mColor);
- mPaint.setStyle(Paint.Style.FILL);
- mPaint.setAntiAlias(true);
- canvas.drawPath(mProtectionPath, mPaint);
- } else if (!mBoundingPath.isEmpty()) {
+ if (!mBoundingPath.isEmpty()) {
mPaint.setColor(mColor);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
canvas.drawPath(mBoundingPath, mPaint);
}
+ if (mCameraProtectionProgress > HIDDEN_CAMERA_PROTECTION_SCALE
+ && !mProtectionRect.isEmpty()) {
+ canvas.scale(mCameraProtectionProgress, mCameraProtectionProgress,
+ mProtectionRect.centerX(), mProtectionRect.centerY());
+ canvas.drawPath(mProtectionPath, mPaint);
+ }
}
@Override
@@ -804,8 +827,16 @@
}
void setProtection(Path protectionPath, Rect pathBounds) {
- mProtectionPath = protectionPath;
- mProtectionRect = pathBounds;
+ if (mProtectionPathOrig == null) {
+ mProtectionPathOrig = new Path();
+ mProtectionPath = new Path();
+ }
+ mProtectionPathOrig.set(protectionPath);
+ if (mProtectionRectOrig == null) {
+ mProtectionRectOrig = new RectF();
+ mProtectionRect = new RectF();
+ }
+ mProtectionRectOrig.set(pathBounds);
}
void setShowProtection(boolean shouldShow) {
@@ -815,8 +846,31 @@
mShowProtection = shouldShow;
updateBoundingPath();
- requestLayout();
- invalidate();
+ // Delay the relayout until the end of the animation when hiding the cutout,
+ // otherwise we'd clip it.
+ if (mShowProtection) {
+ requestLayout();
+ }
+ if (mCameraProtectionAnimator != null) {
+ mCameraProtectionAnimator.cancel();
+ }
+ mCameraProtectionAnimator = ValueAnimator.ofFloat(mCameraProtectionProgress,
+ mShowProtection ? 1.0f : HIDDEN_CAMERA_PROTECTION_SCALE).setDuration(750);
+ mCameraProtectionAnimator.setInterpolator(Interpolators.DECELERATE_QUINT);
+ mCameraProtectionAnimator.addUpdateListener(animation -> {
+ mCameraProtectionProgress = (float) animation.getAnimatedValue();
+ invalidate();
+ });
+ mCameraProtectionAnimator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mCameraProtectionAnimator = null;
+ if (!mShowProtection) {
+ requestLayout();
+ }
+ }
+ });
+ mCameraProtectionAnimator.start();
}
private void update() {
@@ -858,8 +912,11 @@
Matrix m = new Matrix();
transformPhysicalToLogicalCoordinates(mInfo.rotation, dw, dh, m);
mBoundingPath.transform(m);
- if (mProtectionPath != null) {
+ if (mProtectionPathOrig != null) {
+ // Reset the protection path so we don't aggregate rotations
+ mProtectionPath.set(mProtectionPathOrig);
mProtectionPath.transform(m);
+ m.mapRect(mProtectionRect, mProtectionRectOrig);
}
}
@@ -926,7 +983,8 @@
if (mShowProtection) {
// Make sure that our measured height encompases the protection
mTotalBounds.union(mBoundingRect);
- mTotalBounds.union(mProtectionRect);
+ mTotalBounds.union((int) mProtectionRect.left, (int) mProtectionRect.top,
+ (int) mProtectionRect.right, (int) mProtectionRect.bottom);
setMeasuredDimension(
resolveSizeAndState(mTotalBounds.width(), widthMeasureSpec, 0),
resolveSizeAndState(mTotalBounds.height(), heightMeasureSpec, 0));
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
index 5077e18..cc4ee89 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
@@ -1,6 +1,9 @@
package com.android.systemui.assist;
+import static android.view.Display.DEFAULT_DISPLAY;
+
import static com.android.systemui.DejankUtils.whitelistIpcs;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -43,6 +46,7 @@
import com.android.settingslib.applications.InterestingConfigChanges;
import com.android.systemui.R;
import com.android.systemui.assist.ui.DefaultUiController;
+import com.android.systemui.model.SysUiState;
import com.android.systemui.recents.OverviewProxyService;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.policy.ConfigurationController;
@@ -51,6 +55,8 @@
import javax.inject.Inject;
import javax.inject.Singleton;
+import dagger.Lazy;
+
/**
* Class to manage everything related to assist in SystemUI.
*/
@@ -98,6 +104,9 @@
public static final String INVOCATION_TYPE_KEY = "invocation_type";
protected static final String ACTION_KEY = "action";
protected static final String SHOW_ASSIST_HANDLES_ACTION = "show_assist_handles";
+ protected static final String SET_ASSIST_GESTURE_CONSTRAINED_ACTION =
+ "set_assist_gesture_constrained";
+ protected static final String CONSTRAINED_KEY = "should_constrain";
public static final int INVOCATION_TYPE_GESTURE = 1;
public static final int INVOCATION_TYPE_ACTIVE_EDGE = 2;
@@ -120,6 +129,7 @@
private final PhoneStateMonitor mPhoneStateMonitor;
private final AssistHandleBehaviorController mHandleController;
private final UiController mUiController;
+ protected final Lazy<SysUiState> mSysUiState;
private AssistOrbContainer mView;
private final DeviceProvisionedController mDeviceProvisionedController;
@@ -185,7 +195,8 @@
CommandQueue commandQueue,
PhoneStateMonitor phoneStateMonitor,
OverviewProxyService overviewProxyService,
- ConfigurationController configurationController) {
+ ConfigurationController configurationController,
+ Lazy<SysUiState> sysUiState) {
mContext = context;
mDeviceProvisionedController = controller;
mCommandQueue = commandQueue;
@@ -206,6 +217,8 @@
mUiController = new DefaultUiController(mContext);
+ mSysUiState = sysUiState;
+
overviewProxyService.addCallback(new OverviewProxyService.OverviewProxyListener() {
@Override
public void onAssistantProgress(float progress) {
@@ -243,8 +256,16 @@
if (VERBOSE) {
Log.v(TAG, "UI hints received");
}
- if (SHOW_ASSIST_HANDLES_ACTION.equals(hints.getString(ACTION_KEY))) {
+
+ String action = hints.getString(ACTION_KEY);
+ if (SHOW_ASSIST_HANDLES_ACTION.equals(action)) {
requestAssistHandles();
+ } else if (SET_ASSIST_GESTURE_CONSTRAINED_ACTION.equals(action)) {
+ mSysUiState.get()
+ .setFlag(
+ SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED,
+ hints.getBoolean(CONSTRAINED_KEY, false))
+ .commitUpdate(DEFAULT_DISPLAY);
}
}
});
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
index cbb1982..0018d33 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java
@@ -99,6 +99,8 @@
// Non-null only if the dialog is in the act of dismissing and has not sent the reason yet.
@Nullable @AuthDialogCallback.DismissedReason Integer mPendingCallbackReason;
+ // HAT received from LockSettingsService when credential is verified.
+ @Nullable byte[] mCredentialAttestation;
static class Config {
Context mContext;
@@ -109,6 +111,7 @@
String mOpPackageName;
int mModalityMask;
boolean mSkipIntro;
+ long mOperationId;
}
public static class Builder {
@@ -149,6 +152,11 @@
return this;
}
+ public Builder setOperationId(long operationId) {
+ mConfig.mOperationId = operationId;
+ return this;
+ }
+
public AuthContainerView build(int modalityMask) {
mConfig.mModalityMask = modalityMask;
return new AuthContainerView(mConfig, new Injector());
@@ -224,7 +232,8 @@
final class CredentialCallback implements AuthCredentialView.Callback {
@Override
- public void onCredentialMatched() {
+ public void onCredentialMatched(byte[] attestation) {
+ mCredentialAttestation = attestation;
animateAway(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED);
}
}
@@ -341,6 +350,7 @@
mCredentialView.setContainerView(this);
mCredentialView.setUserId(mConfig.mUserId);
+ mCredentialView.setOperationId(mConfig.mOperationId);
mCredentialView.setEffectiveUserId(mEffectiveUserId);
mCredentialView.setCredentialType(credentialType);
mCredentialView.setCallback(mCredentialCallback);
@@ -558,7 +568,7 @@
private void sendPendingCallbackIfNotNull() {
Log.d(TAG, "pendingCallback: " + mPendingCallbackReason);
if (mPendingCallbackReason != null) {
- mConfig.mCallback.onDismissed(mPendingCallbackReason);
+ mConfig.mCallback.onDismissed(mPendingCallbackReason, mCredentialAttestation);
mPendingCallbackReason = null;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
index 6149b0b..c30477c 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java
@@ -20,6 +20,7 @@
import static android.hardware.biometrics.BiometricAuthenticator.TYPE_FINGERPRINT;
import static android.hardware.biometrics.BiometricManager.Authenticators;
+import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
import android.app.IActivityTaskManager;
@@ -99,7 +100,8 @@
try {
if (mReceiver != null) {
- mReceiver.onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ mReceiver.onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL,
+ null /* credentialAttestation */);
mReceiver = null;
}
} catch (RemoteException e) {
@@ -124,7 +126,8 @@
mCurrentDialog = null;
if (mReceiver != null) {
mReceiver.onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ BiometricPrompt.DISMISSED_REASON_USER_CANCEL,
+ null /* credentialAttestation */);
mReceiver = null;
}
}
@@ -162,35 +165,42 @@
}
@Override
- public void onDismissed(@DismissedReason int reason) {
+ public void onDismissed(@DismissedReason int reason, @Nullable byte[] credentialAttestation) {
switch (reason) {
case AuthDialogCallback.DISMISSED_USER_CANCELED:
- sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_USER_CANCEL,
+ credentialAttestation);
break;
case AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE:
- sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_NEGATIVE);
+ sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_NEGATIVE,
+ credentialAttestation);
break;
case AuthDialogCallback.DISMISSED_BUTTON_POSITIVE:
- sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
+ sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED,
+ credentialAttestation);
break;
case AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED:
sendResultAndCleanUp(
- BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
+ BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED,
+ credentialAttestation);
break;
case AuthDialogCallback.DISMISSED_ERROR:
- sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_ERROR);
+ sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_ERROR,
+ credentialAttestation);
break;
case AuthDialogCallback.DISMISSED_BY_SYSTEM_SERVER:
- sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED);
+ sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED,
+ credentialAttestation);
break;
case AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED:
- sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED);
+ sendResultAndCleanUp(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED,
+ credentialAttestation);
break;
default:
@@ -199,13 +209,14 @@
}
}
- private void sendResultAndCleanUp(@DismissedReason int reason) {
+ private void sendResultAndCleanUp(@DismissedReason int reason,
+ @Nullable byte[] credentialAttestation) {
if (mReceiver == null) {
Log.e(TAG, "sendResultAndCleanUp: Receiver is null");
return;
}
try {
- mReceiver.onDialogDismissed(reason);
+ mReceiver.onDialogDismissed(reason, credentialAttestation);
} catch (RemoteException e) {
Log.w(TAG, "Remote exception", e);
}
@@ -251,13 +262,15 @@
@Override
public void showAuthenticationDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
- int biometricModality, boolean requireConfirmation, int userId, String opPackageName) {
+ int biometricModality, boolean requireConfirmation, int userId, String opPackageName,
+ long operationId) {
final int authenticators = Utils.getAuthenticators(bundle);
if (DEBUG) {
Log.d(TAG, "showAuthenticationDialog, authenticators: " + authenticators
+ ", biometricModality: " + biometricModality
- + ", requireConfirmation: " + requireConfirmation);
+ + ", requireConfirmation: " + requireConfirmation
+ + ", operationId: " + operationId);
}
SomeArgs args = SomeArgs.obtain();
args.arg1 = bundle;
@@ -266,6 +279,7 @@
args.arg3 = requireConfirmation;
args.argi2 = userId;
args.arg4 = opPackageName;
+ args.arg5 = operationId;
boolean skipAnimation = false;
if (mCurrentDialog != null) {
@@ -354,6 +368,7 @@
final boolean requireConfirmation = (boolean) args.arg3;
final int userId = args.argi2;
final String opPackageName = (String) args.arg4;
+ final long operationId = (long) args.arg5;
// Create a new dialog but do not replace the current one yet.
final AuthDialog newDialog = buildDialog(
@@ -362,7 +377,8 @@
userId,
type,
opPackageName,
- skipAnimation);
+ skipAnimation,
+ operationId);
if (newDialog == null) {
Log.e(TAG, "Unsupported type: " + type);
@@ -429,7 +445,7 @@
}
protected AuthDialog buildDialog(Bundle biometricPromptBundle, boolean requireConfirmation,
- int userId, int type, String opPackageName, boolean skipIntro) {
+ int userId, int type, String opPackageName, boolean skipIntro, long operationId) {
return new AuthContainerView.Builder(mContext)
.setCallback(this)
.setBiometricPromptBundle(biometricPromptBundle)
@@ -437,6 +453,7 @@
.setUserId(userId)
.setOpPackageName(opPackageName)
.setSkipIntro(skipIntro)
+ .setOperationId(operationId)
.build(type);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java
index 82c8a46..b986f6c 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPasswordView.java
@@ -103,14 +103,16 @@
return;
}
- mPendingLockCheck = LockPatternChecker.checkCredential(mLockPatternUtils,
- password, mEffectiveUserId, this::onCredentialChecked);
+ mPendingLockCheck = LockPatternChecker.verifyCredential(mLockPatternUtils,
+ password, mOperationId, mEffectiveUserId, this::onCredentialVerified);
}
}
@Override
- protected void onCredentialChecked(boolean matched, int timeoutMs) {
- super.onCredentialChecked(matched, timeoutMs);
+ protected void onCredentialVerified(byte[] attestation, int timeoutMs) {
+ super.onCredentialVerified(attestation, timeoutMs);
+
+ final boolean matched = attestation != null;
if (matched) {
mImm.hideSoftInputFromWindow(getWindowToken(), 0 /* flags */);
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java
index 03136a4..6d16f43 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialPatternView.java
@@ -61,21 +61,22 @@
if (pattern.size() < LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
// Pattern size is less than the minimum, do not count it as a failed attempt.
- onPatternChecked(false /* matched */, 0 /* timeoutMs */);
+ onPatternVerified(null /* attestation */, 0 /* timeoutMs */);
return;
}
try (LockscreenCredential credential = LockscreenCredential.createPattern(pattern)) {
- mPendingLockCheck = LockPatternChecker.checkCredential(
+ mPendingLockCheck = LockPatternChecker.verifyCredential(
mLockPatternUtils,
credential,
+ mOperationId,
mEffectiveUserId,
- this::onPatternChecked);
+ this::onPatternVerified);
}
}
- private void onPatternChecked(boolean matched, int timeoutMs) {
- AuthCredentialPatternView.this.onCredentialChecked(matched, timeoutMs);
+ private void onPatternVerified(byte[] attestation, int timeoutMs) {
+ AuthCredentialPatternView.this.onCredentialVerified(attestation, timeoutMs);
if (timeoutMs > 0) {
mLockPatternView.setEnabled(false);
} else {
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java
index 48c6621..0d9d426 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthCredentialView.java
@@ -42,7 +42,7 @@
/**
* Abstract base class for Pin, Pattern, or Password authentication, for
- * {@link BiometricPrompt.Builder#setDeviceCredentialAllowed(boolean)}
+ * {@link BiometricPrompt.Builder#setAllowedAuthenticators(int)}}
*/
public abstract class AuthCredentialView extends LinearLayout {
@@ -70,11 +70,12 @@
protected Callback mCallback;
protected AsyncTask<?, ?, ?> mPendingLockCheck;
protected int mUserId;
+ protected long mOperationId;
protected int mEffectiveUserId;
protected ErrorTimer mErrorTimer;
interface Callback {
- void onCredentialMatched();
+ void onCredentialMatched(byte[] attestation);
}
protected static class ErrorTimer extends CountDownTimer {
@@ -148,6 +149,10 @@
mUserId = userId;
}
+ void setOperationId(long operationId) {
+ mOperationId = operationId;
+ }
+
void setEffectiveUserId(int effectiveUserId) {
mEffectiveUserId = effectiveUserId;
}
@@ -245,10 +250,13 @@
protected void onErrorTimeoutFinish() {}
- protected void onCredentialChecked(boolean matched, int timeoutMs) {
+ protected void onCredentialVerified(byte[] attestation, int timeoutMs) {
+
+ final boolean matched = attestation != null;
+
if (matched) {
mClearErrorRunnable.run();
- mCallback.onCredentialMatched();
+ mCallback.onCredentialMatched(attestation);
} else {
if (timeoutMs > 0) {
mHandler.removeCallbacks(mClearErrorRunnable);
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java
index 12bb122..a47621d 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthDialogCallback.java
@@ -17,6 +17,7 @@
package com.android.systemui.biometrics;
import android.annotation.IntDef;
+import android.annotation.Nullable;
/**
* Callback interface for dialog views. These should be implemented by the controller (e.g.
@@ -44,8 +45,9 @@
/**
* Invoked when the dialog is dismissed
* @param reason
+ * @param credentialAttestation the HAT received from LockSettingsService upon verification
*/
- void onDismissed(@DismissedReason int reason);
+ void onDismissed(@DismissedReason int reason, @Nullable byte[] credentialAttestation);
/**
* Invoked when the "try again" button is clicked
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
index 7ca2308..4240209c 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java
@@ -279,7 +279,8 @@
/**
* @return the display id of the virtual display on which bubble contents is drawn.
*/
- int getDisplayId() {
+ @Override
+ public int getDisplayId() {
return mExpandedView != null ? mExpandedView.getVirtualDisplayId() : INVALID_DISPLAY;
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index 48457f6..b39dd1a 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -52,6 +52,7 @@
import android.graphics.Rect;
import android.os.RemoteException;
import android.os.ServiceManager;
+import android.service.notification.NotificationListenerService;
import android.service.notification.NotificationListenerService.RankingMap;
import android.service.notification.ZenModeConfig;
import android.util.ArraySet;
@@ -83,11 +84,11 @@
import com.android.systemui.statusbar.NotificationRemoveInterceptor;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.ShadeController;
@@ -146,13 +147,15 @@
private BubbleData mBubbleData;
@Nullable private BubbleStackView mStackView;
private BubbleIconFactory mBubbleIconFactory;
- private int mMaxBubbles;
// Tracks the id of the current (foreground) user.
private int mCurrentUserId;
// Saves notification keys of active bubbles when users are switched.
private final SparseSetArray<String> mSavedBubbleKeysPerUser;
+ // Used when ranking updates occur and we check if things should bubble / unbubble
+ private NotificationListenerService.Ranking mTmpRanking;
+
// Saves notification keys of user created "fake" bubbles so that we can allow notifications
// like these to bubble by default. Doesn't persist across reboots, not a long-term solution.
private final HashSet<String> mUserCreatedBubbles;
@@ -169,7 +172,7 @@
// Callback that updates BubbleOverflowActivity on data change.
@Nullable private Runnable mOverflowCallback = null;
- private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+ private final NotificationInterruptStateProvider mNotificationInterruptStateProvider;
private IStatusBarService mBarService;
// Used for determining view rect for touch interaction
@@ -279,7 +282,7 @@
ShadeController shadeController,
BubbleData data,
ConfigurationController configurationController,
- NotificationInterruptionStateProvider interruptionStateProvider,
+ NotificationInterruptStateProvider interruptionStateProvider,
ZenModeController zenModeController,
NotificationLockscreenUserManager notifUserManager,
NotificationGroupManager groupManager,
@@ -304,7 +307,7 @@
BubbleData data,
@Nullable BubbleStackView.SurfaceSynchronizer synchronizer,
ConfigurationController configurationController,
- NotificationInterruptionStateProvider interruptionStateProvider,
+ NotificationInterruptStateProvider interruptionStateProvider,
ZenModeController zenModeController,
NotificationLockscreenUserManager notifUserManager,
NotificationGroupManager groupManager,
@@ -316,7 +319,7 @@
dumpManager.registerDumpable(TAG, this);
mContext = context;
mShadeController = shadeController;
- mNotificationInterruptionStateProvider = interruptionStateProvider;
+ mNotificationInterruptStateProvider = interruptionStateProvider;
mNotifUserManager = notifUserManager;
mZenModeController = zenModeController;
mFloatingContentCoordinator = floatingContentCoordinator;
@@ -338,7 +341,6 @@
configurationController.addCallback(this /* configurationListener */);
- mMaxBubbles = mContext.getResources().getInteger(R.integer.bubbles_max_rendered);
mBubbleData = data;
mBubbleData.setListener(mBubbleDataListener);
mBubbleData.setSuppressionChangedListener(new NotificationSuppressionChangedListener() {
@@ -632,7 +634,7 @@
for (NotificationEntry e :
mNotificationEntryManager.getActiveNotificationsForCurrentUser()) {
if (savedBubbleKeys.contains(e.getKey())
- && mNotificationInterruptionStateProvider.shouldBubbleUp(e)
+ && mNotificationInterruptStateProvider.shouldBubbleUp(e)
&& canLaunchInActivityView(mContext, e)) {
updateBubble(e, /* suppressFlyout= */ true);
}
@@ -894,7 +896,7 @@
boolean wasAdjusted = BubbleExperimentConfig.adjustForExperiments(
mContext, entry, previouslyUserCreated, userBlocked);
- if (mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
+ if (mNotificationInterruptStateProvider.shouldBubbleUp(entry)
&& (canLaunchInActivityView(mContext, entry) || wasAdjusted)) {
if (wasAdjusted && !previouslyUserCreated) {
// Gotta treat the auto-bubbled / whitelisted packaged bubbles as usercreated
@@ -910,7 +912,7 @@
boolean wasAdjusted = BubbleExperimentConfig.adjustForExperiments(
mContext, entry, previouslyUserCreated, userBlocked);
- boolean shouldBubble = mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
+ boolean shouldBubble = mNotificationInterruptStateProvider.shouldBubbleUp(entry)
&& (canLaunchInActivityView(mContext, entry) || wasAdjusted);
if (!shouldBubble && mBubbleData.hasBubbleWithKey(entry.getKey())) {
// It was previously a bubble but no longer a bubble -- lets remove it
@@ -939,9 +941,29 @@
}
}
+ /**
+ * Called when NotificationListener has received adjusted notification rank and reapplied
+ * filtering and sorting. This is used to dismiss or create bubbles based on changes in
+ * permissions on the notification channel or the global setting.
+ *
+ * @param rankingMap the updated ranking map from NotificationListenerService
+ */
private void onRankingUpdated(RankingMap rankingMap) {
- // Forward to BubbleData to block any bubbles which should no longer be shown
- mBubbleData.notificationRankingUpdated(rankingMap);
+ if (mTmpRanking == null) {
+ mTmpRanking = new NotificationListenerService.Ranking();
+ }
+ String[] orderedKeys = rankingMap.getOrderedKeys();
+ for (int i = 0; i < orderedKeys.length; i++) {
+ String key = orderedKeys[i];
+ NotificationEntry entry = mNotificationEntryManager.getPendingOrActiveNotif(key);
+ rankingMap.getRanking(key, mTmpRanking);
+ if (mBubbleData.hasBubbleWithKey(key) && !mTmpRanking.canBubble()) {
+ mBubbleData.notificationEntryRemoved(entry, BubbleController.DISMISS_BLOCKED);
+ } else if (entry != null && mTmpRanking.isBubble()) {
+ entry.setFlagBubble(true);
+ onEntryUpdated(entry);
+ }
+ }
}
@SuppressWarnings("FieldCanBeLocal")
@@ -1175,23 +1197,17 @@
* status bar, otherwise returns {@link Display#INVALID_DISPLAY}.
*/
public int getExpandedDisplayId(Context context) {
- final Bubble bubble = getExpandedBubble(context);
- return bubble != null ? bubble.getDisplayId() : INVALID_DISPLAY;
- }
-
- @Nullable
- private Bubble getExpandedBubble(Context context) {
if (mStackView == null) {
- return null;
+ return INVALID_DISPLAY;
}
final boolean defaultDisplay = context.getDisplay() != null
&& context.getDisplay().getDisplayId() == DEFAULT_DISPLAY;
- final Bubble expandedBubble = mStackView.getExpandedBubble();
- if (defaultDisplay && expandedBubble != null && isStackExpanded()
+ final BubbleViewProvider expandedViewProvider = mStackView.getExpandedBubble();
+ if (defaultDisplay && expandedViewProvider != null && isStackExpanded()
&& !mNotificationShadeWindowController.getPanelExpanded()) {
- return expandedBubble;
+ return expandedViewProvider.getDisplayId();
}
- return null;
+ return INVALID_DISPLAY;
}
@VisibleForTesting
@@ -1233,6 +1249,17 @@
}
@Override
+ public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask) {
+ for (Bubble b : mBubbleData.getBubbles()) {
+ if (b.getDisplayId() == task.displayId) {
+ expandStackAndSelectBubble(b.getKey());
+ return;
+ }
+ }
+ }
+
+ @Override
public void onActivityLaunchOnSecondaryDisplayRerouted() {
if (mStackView != null) {
mBubbleData.setExpanded(false);
@@ -1256,7 +1283,7 @@
@Override
public void onSingleTaskDisplayEmpty(int displayId) {
- final Bubble expandedBubble = mStackView != null
+ final BubbleViewProvider expandedBubble = mStackView != null
? mStackView.getExpandedBubble()
: null;
int expandedId = expandedBubble != null ? expandedBubble.getDisplayId() : -1;
@@ -1311,7 +1338,7 @@
private class BubblesImeListener extends PinnedStackListenerForwarder.PinnedStackListener {
@Override
public void onImeVisibilityChanged(boolean imeVisible, int imeHeight) {
- if (mStackView != null && mStackView.getBubbleCount() > 0) {
+ if (mStackView != null) {
mStackView.post(() -> mStackView.onImeVisibilityChanged(imeVisible, imeHeight));
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
index cf5a4d3..ff5e13c 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleData.java
@@ -26,7 +26,6 @@
import android.app.PendingIntent;
import android.content.Context;
import android.service.notification.NotificationListenerService;
-import android.service.notification.NotificationListenerService.RankingMap;
import android.util.Log;
import android.util.Pair;
@@ -207,12 +206,13 @@
// Preserve new order for next repack, which sorts by last updated time.
bubble.markUpdatedAt(mTimeSource.currentTimeMillis());
- setSelectedBubbleInternal(bubble);
mOverflowBubbles.remove(bubble);
-
bubble.inflate(
- b -> notificationEntryUpdated(bubble, /* suppressFlyout */
- false, /* showInShade */ true),
+ b -> {
+ notificationEntryUpdated(bubble, /* suppressFlyout */
+ false, /* showInShade */ true);
+ setSelectedBubbleInternal(bubble);
+ },
mContext, stack, factory);
dispatchPendingChanges();
}
@@ -225,6 +225,14 @@
Bubble getOrCreateBubble(NotificationEntry entry) {
Bubble bubble = getBubbleWithKey(entry.getKey());
if (bubble == null) {
+ for (int i = 0; i < mOverflowBubbles.size(); i++) {
+ Bubble b = mOverflowBubbles.get(i);
+ if (b.getKey().equals(entry.getKey())) {
+ mOverflowBubbles.remove(b);
+ mPendingBubbles.add(b);
+ return b;
+ }
+ }
// Check for it in pending
for (int i = 0; i < mPendingBubbles.size(); i++) {
Bubble b = mPendingBubbles.get(i);
@@ -289,31 +297,6 @@
}
/**
- * Called when NotificationListener has received adjusted notification rank and reapplied
- * filtering and sorting. This is used to dismiss any bubbles which should no longer be shown
- * due to changes in permissions on the notification channel or the global setting.
- *
- * @param rankingMap the updated ranking map from NotificationListenerService
- */
- public void notificationRankingUpdated(RankingMap rankingMap) {
- if (mTmpRanking == null) {
- mTmpRanking = new NotificationListenerService.Ranking();
- }
-
- String[] orderedKeys = rankingMap.getOrderedKeys();
- for (int i = 0; i < orderedKeys.length; i++) {
- String key = orderedKeys[i];
- if (hasBubbleWithKey(key)) {
- rankingMap.getRanking(key, mTmpRanking);
- if (!mTmpRanking.canBubble()) {
- doRemove(key, BubbleController.DISMISS_BLOCKED);
- }
- }
- }
- dispatchPendingChanges();
- }
-
- /**
* Adds a group key indicating that the summary for this group should be suppressed.
*
* @param groupKey the group key of the group whose summary should be suppressed.
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java
index e800011..19733a5 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleDebugConfig.java
@@ -59,13 +59,15 @@
return FORCE_SHOW_USER_EDUCATION || forceShow;
}
- static String formatBubblesString(List<Bubble> bubbles, Bubble selected) {
+ static String formatBubblesString(List<Bubble> bubbles, BubbleViewProvider selected) {
StringBuilder sb = new StringBuilder();
for (Bubble bubble : bubbles) {
if (bubble == null) {
sb.append(" <null> !!!!!\n");
} else {
- boolean isSelected = (selected != null && bubble == selected);
+ boolean isSelected = (selected != null
+ && selected.getKey() != BubbleOverflow.KEY
+ && bubble == selected);
String arrow = isSelected ? "=>" : " ";
sb.append(String.format("%s Bubble{act=%12d, ongoing=%d, key=%s}\n",
arrow,
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflow.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflow.java
index 313bb42..4fb2d08 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflow.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleOverflow.java
@@ -16,6 +16,7 @@
package com.android.systemui.bubbles;
+import static android.view.Display.INVALID_DISPLAY;
import static android.view.View.GONE;
import static com.android.systemui.bubbles.BadgedImageView.DEFAULT_PATH_SIZE;
@@ -45,7 +46,7 @@
public static final String KEY = "Overflow";
private BadgedImageView mOverflowBtn;
- private BubbleExpandedView mOverflowExpandedView;
+ private BubbleExpandedView mExpandedView;
private LayoutInflater mInflater;
private Context mContext;
private Bitmap mIcon;
@@ -63,11 +64,11 @@
}
void setUpOverflow(ViewGroup parentViewGroup, BubbleStackView stackView) {
- mOverflowExpandedView = (BubbleExpandedView) mInflater.inflate(
+ mExpandedView = (BubbleExpandedView) mInflater.inflate(
R.layout.bubble_expanded_view, parentViewGroup /* root */,
false /* attachToRoot */);
- mOverflowExpandedView.setOverflow(true);
- mOverflowExpandedView.setStackView(stackView);
+ mExpandedView.setOverflow(true);
+ mExpandedView.setStackView(stackView);
updateIcon(mContext, parentViewGroup);
}
@@ -124,7 +125,7 @@
@Override
public BubbleExpandedView getExpandedView() {
- return mOverflowExpandedView;
+ return mExpandedView;
}
@Override
@@ -149,7 +150,7 @@
@Override
public void setContentVisibility(boolean visible) {
- mOverflowExpandedView.setContentVisibility(visible);
+ mExpandedView.setContentVisibility(visible);
}
@Override
@@ -167,4 +168,9 @@
public String getKey() {
return BubbleOverflow.KEY;
}
+
+ @Override
+ public int getDisplayId() {
+ return mExpandedView != null ? mExpandedView.getVirtualDisplayId() : INVALID_DISPLAY;
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
index 0cf6d89..e666fb5 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java
@@ -32,7 +32,6 @@
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
-import android.annotation.NonNull;
import android.app.Notification;
import android.content.Context;
import android.content.res.Configuration;
@@ -47,7 +46,6 @@
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
-import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.view.Choreographer;
@@ -56,6 +54,7 @@
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
+import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowInsets;
import android.view.WindowManager;
@@ -66,6 +65,7 @@
import android.widget.TextView;
import androidx.annotation.MainThread;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.FloatPropertyCompat;
@@ -81,7 +81,10 @@
import com.android.systemui.bubbles.animation.PhysicsAnimationLayout;
import com.android.systemui.bubbles.animation.StackAnimationController;
import com.android.systemui.shared.system.SysUiStatsLog;
+import com.android.systemui.util.DismissCircleView;
import com.android.systemui.util.FloatingContentCoordinator;
+import com.android.systemui.util.animation.PhysicsAnimator;
+import com.android.systemui.util.magnetictarget.MagnetizedObject;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -123,6 +126,11 @@
@VisibleForTesting
static final int FLYOUT_HIDE_AFTER = 5000;
+ private static final PhysicsAnimator.SpringConfig FLYOUT_IME_ANIMATION_SPRING_CONFIG =
+ new PhysicsAnimator.SpringConfig(
+ StackAnimationController.IME_ANIMATION_STIFFNESS,
+ StackAnimationController.DEFAULT_BOUNCINESS);
+
/**
* Interface to synchronize {@link View} state and the screen.
*
@@ -227,8 +235,6 @@
pw.print(" gestureInProgress: "); pw.println(mIsGestureInProgress);
pw.print(" showingDismiss: "); pw.println(mShowingDismiss);
pw.print(" isExpansionAnimating: "); pw.println(mIsExpansionAnimating);
- pw.print(" draggingInDismiss: "); pw.println(mDraggingInDismissTarget);
- pw.print(" animatingMagnet: "); pw.println(mAnimatingMagnet);
mStackAnimationController.dump(fd, pw, args);
mExpandedAnimationController.dump(fd, pw, args);
}
@@ -240,16 +246,6 @@
private boolean mIsExpansionAnimating = false;
private boolean mShowingDismiss = false;
- /**
- * Whether the user is currently dragging their finger within the dismiss target. In this state
- * the stack will be magnetized to the center of the target, so we shouldn't move it until the
- * touch exits the dismiss target area.
- */
- private boolean mDraggingInDismissTarget = false;
-
- /** Whether the stack is magneting towards the dismiss target. */
- private boolean mAnimatingMagnet = false;
-
/** The view to desaturate/darken when magneted to the dismiss target. */
private View mDesaturateAndDarkenTargetView;
@@ -331,11 +327,104 @@
@NonNull
private final SurfaceSynchronizer mSurfaceSynchronizer;
- private BubbleDismissView mDismissContainer;
- private Runnable mAfterMagnet;
+ /**
+ * The currently magnetized object, which is being dragged and will be attracted to the magnetic
+ * dismiss target.
+ *
+ * This is either the stack itself, or an individual bubble.
+ */
+ private MagnetizedObject<?> mMagnetizedObject;
+
+ /**
+ * The action to run when the magnetized object is released in the dismiss target.
+ *
+ * This will actually perform the dismissal of either the stack or an individual bubble.
+ */
+ private Runnable mReleasedInDismissTargetAction;
+
+ /**
+ * The MagneticTarget instance for our circular dismiss view. This is added to the
+ * MagnetizedObject instances for the stack and any dragged-out bubbles.
+ */
+ private MagnetizedObject.MagneticTarget mMagneticTarget;
+
+ /** Magnet listener that handles animating and dismissing individual dragged-out bubbles. */
+ private final MagnetizedObject.MagnetListener mIndividualBubbleMagnetListener =
+ new MagnetizedObject.MagnetListener() {
+ @Override
+ public void onStuckToTarget(@NonNull MagnetizedObject.MagneticTarget target) {
+ animateDesaturateAndDarken(
+ mExpandedAnimationController.getDraggedOutBubble(), true);
+ }
+
+ @Override
+ public void onUnstuckFromTarget(@NonNull MagnetizedObject.MagneticTarget target,
+ float velX, float velY, boolean wasFlungOut) {
+ animateDesaturateAndDarken(
+ mExpandedAnimationController.getDraggedOutBubble(), false);
+
+ if (wasFlungOut) {
+ mExpandedAnimationController.snapBubbleBack(
+ mExpandedAnimationController.getDraggedOutBubble(), velX, velY);
+ hideDismissTarget();
+ } else {
+ mExpandedAnimationController.onUnstuckFromTarget();
+ }
+ }
+
+ @Override
+ public void onReleasedInTarget(@NonNull MagnetizedObject.MagneticTarget target) {
+ mExpandedAnimationController.dismissDraggedOutBubble(
+ mExpandedAnimationController.getDraggedOutBubble(),
+ mReleasedInDismissTargetAction);
+ hideDismissTarget();
+ }
+ };
+
+ /** Magnet listener that handles animating and dismissing the entire stack. */
+ private final MagnetizedObject.MagnetListener mStackMagnetListener =
+ new MagnetizedObject.MagnetListener() {
+ @Override
+ public void onStuckToTarget(
+ @NonNull MagnetizedObject.MagneticTarget target) {
+ animateDesaturateAndDarken(mBubbleContainer, true);
+ }
+
+ @Override
+ public void onUnstuckFromTarget(@NonNull MagnetizedObject.MagneticTarget target,
+ float velX, float velY, boolean wasFlungOut) {
+ animateDesaturateAndDarken(mBubbleContainer, false);
+
+ if (wasFlungOut) {
+ mStackAnimationController.flingStackThenSpringToEdge(
+ mStackAnimationController.getStackPosition().x, velX, velY);
+ hideDismissTarget();
+ } else {
+ mStackAnimationController.onUnstuckFromTarget();
+ }
+ }
+
+ @Override
+ public void onReleasedInTarget(@NonNull MagnetizedObject.MagneticTarget target) {
+ mStackAnimationController.implodeStack(
+ () -> {
+ resetDesaturationAndDarken();
+ mReleasedInDismissTargetAction.run();
+ }
+ );
+
+ hideDismissTarget();
+ }
+ };
+
+ private ViewGroup mDismissTargetContainer;
+ private PhysicsAnimator<View> mDismissTargetAnimator;
+ private PhysicsAnimator.SpringConfig mDismissTargetSpring = new PhysicsAnimator.SpringConfig(
+ SpringForce.STIFFNESS_LOW, SpringForce.DAMPING_RATIO_LOW_BOUNCY);
private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
+ @Nullable
private BubbleOverflow mBubbleOverflow;
private boolean mShouldShowUserEducation;
@@ -382,7 +471,8 @@
mExpandedViewPadding = res.getDimensionPixelSize(R.dimen.bubble_expanded_view_padding);
int elevation = res.getDimensionPixelSize(R.dimen.bubble_elevation);
- mStackAnimationController = new StackAnimationController(floatingContentCoordinator);
+ mStackAnimationController = new StackAnimationController(
+ floatingContentCoordinator, this::getBubbleCount);
mExpandedAnimationController = new ExpandedAnimationController(
mDisplaySize, mExpandedViewPadding, res.getConfiguration().orientation);
@@ -409,12 +499,31 @@
.setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY));
mFlyoutTransitionSpring.addEndListener(mAfterFlyoutTransitionSpring);
- mDismissContainer = new BubbleDismissView(mContext);
- mDismissContainer.setLayoutParams(new FrameLayout.LayoutParams(
+ final int targetSize = res.getDimensionPixelSize(R.dimen.dismiss_circle_size);
+ final View targetView = new DismissCircleView(context);
+ final FrameLayout.LayoutParams newParams =
+ new FrameLayout.LayoutParams(targetSize, targetSize);
+ newParams.gravity = Gravity.CENTER;
+ targetView.setLayoutParams(newParams);
+ mDismissTargetAnimator = PhysicsAnimator.getInstance(targetView);
+
+ mDismissTargetContainer = new FrameLayout(context);
+ mDismissTargetContainer.setLayoutParams(new FrameLayout.LayoutParams(
MATCH_PARENT,
getResources().getDimensionPixelSize(R.dimen.pip_dismiss_gradient_height),
Gravity.BOTTOM));
- addView(mDismissContainer);
+ mDismissTargetContainer.setClipChildren(false);
+ mDismissTargetContainer.addView(targetView);
+ mDismissTargetContainer.setVisibility(View.INVISIBLE);
+ addView(mDismissTargetContainer);
+
+ // Start translated down so the target springs up.
+ targetView.setTranslationY(
+ getResources().getDimensionPixelSize(R.dimen.pip_dismiss_gradient_height));
+
+ // Save the MagneticTarget instance for the newly set up view - we'll add this to the
+ // MagnetizedObjects.
+ mMagneticTarget = new MagnetizedObject.MagneticTarget(targetView, mBubbleSize * 2);
mExpandedViewXAnim =
new SpringAnimation(mExpandedViewContainer, DynamicAnimation.TRANSLATION_X);
@@ -801,14 +910,8 @@
* The {@link Bubble} that is expanded, null if one does not exist.
*/
@Nullable
- Bubble getExpandedBubble() {
- if (mExpandedBubble == null
- || (BubbleExperimentConfig.allowBubbleOverflow(mContext)
- && mExpandedBubble.getIconView() == mBubbleOverflow.getBtn()
- && BubbleOverflow.KEY.equals(mExpandedBubble.getKey()))) {
- return null;
- }
- return (Bubble) mExpandedBubble;
+ BubbleViewProvider getExpandedBubble() {
+ return mExpandedBubble;
}
// via BubbleData.Listener
@@ -1066,6 +1169,14 @@
}
}
+ /*
+ * Sets the action to run to dismiss the currently dragging object (either the stack or an
+ * individual bubble).
+ */
+ public void setReleasedInDismissTargetAction(Runnable action) {
+ mReleasedInDismissTargetAction = action;
+ }
+
/**
* Dismiss the stack of bubbles.
*
@@ -1130,7 +1241,8 @@
}
/**
- * @deprecated use {@link #setExpanded(boolean)} and {@link #setSelectedBubble(Bubble)}
+ * @deprecated use {@link #setExpanded(boolean)} and
+ * {@link BubbleData#setSelectedBubble(Bubble)}
*/
@Deprecated
@MainThread
@@ -1172,7 +1284,7 @@
if (DEBUG_BUBBLE_STACK_VIEW) {
Log.d(TAG, "animateCollapse");
Log.d(TAG, BubbleDebugConfig.formatBubblesString(getBubblesOnScreen(),
- getExpandedBubble()));
+ mExpandedBubble));
}
updateOverflowBtnVisibility(/* apply */ false);
mBubbleContainer.cancelAllAnimations();
@@ -1244,8 +1356,23 @@
public void onImeVisibilityChanged(boolean visible, int height) {
mStackAnimationController.setImeHeight(visible ? height + mImeOffset : 0);
- if (!mIsExpanded) {
- mStackAnimationController.animateForImeVisibility(visible);
+ if (!mIsExpanded && getBubbleCount() > 0) {
+ final float stackDestinationY =
+ mStackAnimationController.animateForImeVisibility(visible);
+
+ // How far the stack is animating due to IME, we'll just animate the flyout by that
+ // much too.
+ final float stackDy =
+ stackDestinationY - mStackAnimationController.getStackPosition().y;
+
+ // If the flyout is visible, translate it along with the bubble stack.
+ if (mFlyout.getVisibility() == VISIBLE) {
+ PhysicsAnimator.getInstance(mFlyout)
+ .spring(DynamicAnimation.TRANSLATION_Y,
+ mFlyout.getTranslationY() + stackDy,
+ FLYOUT_IME_ANIMATION_SPRING_CONFIG)
+ .start();
+ }
}
}
@@ -1261,13 +1388,25 @@
if (DEBUG_BUBBLE_STACK_VIEW) {
Log.d(TAG, "onBubbleDragStart: bubble=" + bubble);
}
+
+ if (mBubbleOverflow != null && bubble.equals(mBubbleOverflow.getIconView())) {
+ return;
+ }
+
+ mExpandedAnimationController.prepareForBubbleDrag(bubble, mMagneticTarget);
+
+ // We're dragging an individual bubble, so set the magnetized object to the magnetized
+ // bubble.
+ mMagnetizedObject = mExpandedAnimationController.getMagnetizedBubbleDraggingOut();
+ mMagnetizedObject.setMagnetListener(mIndividualBubbleMagnetListener);
+
maybeShowManageEducation(false);
- mExpandedAnimationController.prepareForBubbleDrag(bubble);
}
/** Called with the coordinates to which an individual bubble has been dragged. */
public void onBubbleDragged(View bubble, float x, float y) {
- if (!mIsExpanded || mIsExpansionAnimating) {
+ if (!mIsExpanded || mIsExpansionAnimating
+ || (mBubbleOverflow != null && bubble.equals(mBubbleOverflow.getIconView()))) {
return;
}
@@ -1282,7 +1421,8 @@
Log.d(TAG, "onBubbleDragFinish: bubble=" + bubble);
}
- if (!mIsExpanded || mIsExpansionAnimating) {
+ if (!mIsExpanded || mIsExpansionAnimating
+ || (mBubbleOverflow != null && bubble.equals(mBubbleOverflow.getIconView()))) {
return;
}
@@ -1290,6 +1430,18 @@
hideDismissTarget();
}
+ /** Expands the clicked bubble. */
+ public void expandBubble(Bubble bubble) {
+ if (bubble.equals(mBubbleData.getSelectedBubble())) {
+ // If the bubble we're supposed to expand is the selected bubble, that means the
+ // overflow bubble is currently expanded. Don't tell BubbleData to set this bubble as
+ // selected, since it already is. Just call the stack's setSelectedBubble to expand it.
+ setSelectedBubble(bubble);
+ } else {
+ mBubbleData.setSelectedBubble(bubble);
+ }
+ }
+
void onDragStart() {
if (DEBUG_BUBBLE_STACK_VIEW) {
Log.d(TAG, "onDragStart()");
@@ -1304,7 +1456,9 @@
mBubbleContainer.setActiveController(mStackAnimationController);
hideFlyoutImmediate();
- mDraggingInDismissTarget = false;
+ // Since we're dragging the stack, set the magnetized object to the magnetized stack.
+ mMagnetizedObject = mStackAnimationController.getMagnetizedStack(mMagneticTarget);
+ mMagnetizedObject.setMagnetListener(mStackMagnetListener);
}
void onDragged(float x, float y) {
@@ -1425,6 +1579,11 @@
}
}
+ /** Passes the MotionEvent to the magnetized object and returns true if it was consumed. */
+ boolean passEventToMagnetizedObject(MotionEvent event) {
+ return mMagnetizedObject != null && mMagnetizedObject.maybeConsumeMotionEvent(event);
+ }
+
/** Prepares and starts the desaturate/darken animation on the bubble stack. */
private void animateDesaturateAndDarken(View targetView, boolean desaturateAndDarken) {
mDesaturateAndDarkenTargetView = targetView;
@@ -1455,102 +1614,6 @@
mDesaturateAndDarkenTargetView.setLayerType(View.LAYER_TYPE_NONE, null);
}
- /**
- * Magnets the stack to the target, while also transforming the target to encircle the stack and
- * desaturating/darkening the bubbles.
- */
- void animateMagnetToDismissTarget(
- View magnetView, boolean toTarget, float x, float y, float velX, float velY) {
- mDraggingInDismissTarget = toTarget;
-
- if (toTarget) {
- // The Y-value for the bubble stack to be positioned in the center of the dismiss target
- final float destY = mDismissContainer.getDismissTargetCenterY() - mBubbleSize / 2f;
-
- mAnimatingMagnet = true;
-
- final Runnable afterMagnet = () -> {
- mAnimatingMagnet = false;
- if (mAfterMagnet != null) {
- mAfterMagnet.run();
- }
- };
-
- if (magnetView == this) {
- mStackAnimationController.magnetToDismiss(velX, velY, destY, afterMagnet);
- animateDesaturateAndDarken(mBubbleContainer, true);
- } else {
- mExpandedAnimationController.magnetBubbleToDismiss(
- magnetView, velX, velY, destY, afterMagnet);
-
- animateDesaturateAndDarken(magnetView, true);
- }
- } else {
- mAnimatingMagnet = false;
-
- if (magnetView == this) {
- mStackAnimationController.demagnetizeFromDismissToPoint(x, y, velX, velY);
- animateDesaturateAndDarken(mBubbleContainer, false);
- } else {
- mExpandedAnimationController.demagnetizeBubbleTo(x, y, velX, velY);
- animateDesaturateAndDarken(magnetView, false);
- }
- }
-
- mVibrator.vibrate(VibrationEffect.get(toTarget
- ? VibrationEffect.EFFECT_CLICK
- : VibrationEffect.EFFECT_TICK));
- }
-
- /**
- * Magnets the stack to the dismiss target if it's not already there. Then, dismiss the stack
- * using the 'implode' animation and animate out the target.
- */
- void magnetToStackIfNeededThenAnimateDismissal(
- View touchedView, float velX, float velY, Runnable after) {
- final View draggedOutBubble = mExpandedAnimationController.getDraggedOutBubble();
- final Runnable animateDismissal = () -> {
- mAfterMagnet = null;
-
- mVibrator.vibrate(VibrationEffect.get(VibrationEffect.EFFECT_CLICK));
- mDismissContainer.springOut();
-
- // 'Implode' the stack and then hide the dismiss target.
- if (touchedView == this) {
- mStackAnimationController.implodeStack(
- () -> {
- mAnimatingMagnet = false;
- mShowingDismiss = false;
- mDraggingInDismissTarget = false;
- after.run();
- resetDesaturationAndDarken();
- });
- } else {
- mExpandedAnimationController.dismissDraggedOutBubble(draggedOutBubble, () -> {
- mAnimatingMagnet = false;
- mShowingDismiss = false;
- mDraggingInDismissTarget = false;
- resetDesaturationAndDarken();
- after.run();
- });
- }
- };
-
- if (mAnimatingMagnet) {
- // If the magnet animation is currently playing, dismiss the stack after it's done. This
- // happens if the stack is flung towards the target.
- mAfterMagnet = animateDismissal;
- } else if (mDraggingInDismissTarget) {
- // If we're in the dismiss target, but not animating, we already magneted - dismiss
- // immediately.
- animateDismissal.run();
- } else {
- // Otherwise, we need to start the magnet animation and then dismiss afterward.
- animateMagnetToDismissTarget(touchedView, true, -1 /* x */, -1 /* y */, velX, velY);
- mAfterMagnet = animateDismissal;
- }
- }
-
/** Animates in the dismiss target. */
private void springInDismissTarget() {
if (mShowingDismiss) {
@@ -1559,10 +1622,14 @@
mShowingDismiss = true;
- // Show the dismiss container and bring it to the front so the bubbles will go behind it.
- mDismissContainer.springIn();
- mDismissContainer.bringToFront();
- mDismissContainer.setZ(Short.MAX_VALUE - 1);
+ mDismissTargetContainer.bringToFront();
+ mDismissTargetContainer.setZ(Short.MAX_VALUE - 1);
+ mDismissTargetContainer.setVisibility(VISIBLE);
+
+ mDismissTargetAnimator.cancel();
+ mDismissTargetAnimator
+ .spring(DynamicAnimation.TRANSLATION_Y, 0f, mDismissTargetSpring)
+ .start();
}
/**
@@ -1574,13 +1641,13 @@
return;
}
- mDismissContainer.springOut();
mShowingDismiss = false;
- }
- /** Whether the location of the given MotionEvent is within the dismiss target area. */
- boolean isInDismissTarget(MotionEvent ev) {
- return isIntersecting(mDismissContainer.getDismissTarget(), ev.getRawX(), ev.getRawY());
+ mDismissTargetAnimator
+ .spring(DynamicAnimation.TRANSLATION_Y, mDismissTargetContainer.getHeight(),
+ mDismissTargetSpring)
+ .withEndActions(() -> mDismissTargetContainer.setVisibility(View.INVISIBLE))
+ .start();
}
/** Animates the flyout collapsed (to dot), or the reverse, starting with the given velocity. */
@@ -1811,17 +1878,16 @@
}
private void updatePointerPosition() {
- Bubble expandedBubble = getExpandedBubble();
- if (expandedBubble == null) {
+ if (mExpandedBubble == null) {
return;
}
- int index = getBubbleIndex(expandedBubble);
+ int index = getBubbleIndex(mExpandedBubble);
float bubbleLeftFromScreenLeft = mExpandedAnimationController.getBubbleLeft(index);
float halfBubble = mBubbleSize / 2f;
float bubbleCenter = bubbleLeftFromScreenLeft + halfBubble;
// Padding might be adjusted for insets, so get it directly from the view
bubbleCenter -= mExpandedViewContainer.getPaddingLeft();
- expandedBubble.getExpandedView().setPointerPosition(bubbleCenter);
+ mExpandedBubble.getExpandedView().setPointerPosition(bubbleCenter);
}
/**
@@ -1843,11 +1909,10 @@
* is between 0 and the bubble count minus 1.
*/
int getBubbleIndex(@Nullable BubbleViewProvider provider) {
- if (provider == null || provider.getKey() == BubbleOverflow.KEY) {
+ if (provider == null) {
return 0;
}
- Bubble b = (Bubble) provider;
- return mBubbleContainer.indexOfChild(b.getIconView());
+ return mBubbleContainer.indexOfChild(provider.getIconView());
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
index 46d1e0d..132c45f 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleTouchHandler.java
@@ -30,28 +30,6 @@
* dismissing, and flings.
*/
class BubbleTouchHandler implements View.OnTouchListener {
- /** Velocity required to dismiss the stack without dragging it into the dismiss target. */
- private static final float STACK_DISMISS_MIN_VELOCITY = 4000f;
-
- /**
- * Velocity required to dismiss an individual bubble without dragging it into the dismiss
- * target.
- *
- * This is higher than the stack dismiss velocity since unlike the stack, a downward fling could
- * also be an attempted gesture to return the bubble to the row of expanded bubbles, which would
- * usually be below the dragged bubble. By increasing the required velocity, it's less likely
- * that the user is trying to drop it back into the row vs. fling it away.
- */
- private static final float INDIVIDUAL_BUBBLE_DISMISS_MIN_VELOCITY = 6000f;
-
- /**
- * When the stack is flung towards the bottom of the screen, it'll be dismissed if it's flung
- * towards the center of the screen (where the dismiss target is). This value is the width of
- * the target area to be considered 'towards the target'. For example 50% means that the stack
- * needs to be flung towards the middle 50%, and the 25% on the left and right sides won't
- * count.
- */
- private static final float DISMISS_FLING_TARGET_WIDTH_PERCENT = 0.5f;
private final PointF mTouchDown = new PointF();
private final PointF mViewPositionOnTouchDown = new PointF();
@@ -66,8 +44,6 @@
/** View that was initially touched, when we received the first ACTION_DOWN event. */
private View mTouchedView;
- /** Whether the current touched view is in the dismiss target. */
- private boolean mInDismissTarget;
BubbleTouchHandler(BubbleStackView stackView,
BubbleData bubbleData, Context context) {
@@ -124,13 +100,33 @@
if (isStack) {
mViewPositionOnTouchDown.set(mStack.getStackPosition());
+
+ // Dismiss the entire stack if it's released in the dismiss target.
+ mStack.setReleasedInDismissTargetAction(
+ () -> mController.dismissStack(BubbleController.DISMISS_USER_GESTURE));
mStack.onDragStart();
+ mStack.passEventToMagnetizedObject(event);
} else if (isFlyout) {
mStack.onFlyoutDragStart();
} else {
mViewPositionOnTouchDown.set(
mTouchedView.getTranslationX(), mTouchedView.getTranslationY());
+
+ // Dismiss only the dragged-out bubble if it's released in the target.
+ final String individualBubbleKey = ((BadgedImageView) mTouchedView).getKey();
+ mStack.setReleasedInDismissTargetAction(() -> {
+ final Bubble bubble =
+ mBubbleData.getBubbleWithKey(individualBubbleKey);
+ // bubble can be null if the user is in the middle of
+ // dismissing the bubble, but the app also sent a cancel
+ if (bubble != null) {
+ mController.removeBubble(bubble.getEntry(),
+ BubbleController.DISMISS_USER_GESTURE);
+ }
+ });
+
mStack.onBubbleDragStart(mTouchedView);
+ mStack.passEventToMagnetizedObject(event);
}
break;
@@ -144,27 +140,16 @@
}
if (mMovedEnough) {
- if (isStack) {
- mStack.onDragged(viewX, viewY);
- } else if (isFlyout) {
+ if (isFlyout) {
mStack.onFlyoutDragged(deltaX);
- } else {
- mStack.onBubbleDragged(mTouchedView, viewX, viewY);
- }
- }
-
- final boolean currentlyInDismissTarget = mStack.isInDismissTarget(event);
- if (currentlyInDismissTarget != mInDismissTarget) {
- mInDismissTarget = currentlyInDismissTarget;
-
- mVelocityTracker.computeCurrentVelocity(/* maxVelocity */ 1000);
- final float velX = mVelocityTracker.getXVelocity();
- final float velY = mVelocityTracker.getYVelocity();
-
- // If the touch event is within the dismiss target, magnet the stack to it.
- if (!isFlyout) {
- mStack.animateMagnetToDismissTarget(
- mTouchedView, mInDismissTarget, viewX, viewY, velX, velY);
+ } else if (!mStack.passEventToMagnetizedObject(event)) {
+ // If the magnetic target doesn't consume the event, drag the stack or
+ // bubble.
+ if (isStack) {
+ mStack.onDragged(viewX, viewY);
+ } else {
+ mStack.onBubbleDragged(mTouchedView, viewX, viewY);
+ }
}
}
break;
@@ -179,42 +164,21 @@
final float velX = mVelocityTracker.getXVelocity();
final float velY = mVelocityTracker.getYVelocity();
- final boolean shouldDismiss =
- isStack
- ? mInDismissTarget
- || isFastFlingTowardsDismissTarget(rawX, rawY, velX, velY)
- : mInDismissTarget
- || velY > INDIVIDUAL_BUBBLE_DISMISS_MIN_VELOCITY;
-
if (isFlyout && mMovedEnough) {
mStack.onFlyoutDragFinished(rawX - mTouchDown.x /* deltaX */, velX);
- } else if (shouldDismiss) {
- final String individualBubbleKey =
- isStack ? null : ((BadgedImageView) mTouchedView).getKey();
- mStack.magnetToStackIfNeededThenAnimateDismissal(mTouchedView, velX, velY,
- () -> {
- if (isStack) {
- mController.dismissStack(BubbleController.DISMISS_USER_GESTURE);
- } else {
- final Bubble bubble =
- mBubbleData.getBubbleWithKey(individualBubbleKey);
- // bubble can be null if the user is in the middle of
- // dismissing the bubble, but the app also sent a cancel
- if (bubble != null) {
- mController.removeBubble(bubble.getEntry(),
- BubbleController.DISMISS_USER_GESTURE);
- }
- }
- });
} else if (isFlyout) {
if (!mBubbleData.isExpanded() && !mMovedEnough) {
mStack.onFlyoutTapped();
}
} else if (mMovedEnough) {
- if (isStack) {
- mStack.onDragFinish(viewX, viewY, velX, velY);
- } else {
- mStack.onBubbleDragFinish(mTouchedView, viewX, viewY, velX, velY);
+ if (!mStack.passEventToMagnetizedObject(event)) {
+ // If the magnetic target didn't consume the event, tell the stack to finish
+ // the drag.
+ if (isStack) {
+ mStack.onDragFinish(viewX, viewY, velX, velY);
+ } else {
+ mStack.onBubbleDragFinish(mTouchedView, viewX, viewY, velX, velY);
+ }
}
} else if (mTouchedView == mStack.getExpandedBubbleView()) {
mBubbleData.setExpanded(false);
@@ -225,7 +189,7 @@
if (key == BubbleOverflow.KEY) {
mStack.showOverflow();
} else {
- mBubbleData.setSelectedBubble(mBubbleData.getBubbleWithKey(key));
+ mStack.expandBubble(mBubbleData.getBubbleWithKey(key));
}
}
resetForNextGesture();
@@ -235,45 +199,15 @@
return true;
}
- /**
- * Whether the given touch data represents a powerful fling towards the bottom-center of the
- * screen (the dismiss target).
- */
- private boolean isFastFlingTowardsDismissTarget(
- float rawX, float rawY, float velX, float velY) {
- // Not a fling downward towards the target if velocity is zero or negative.
- if (velY <= 0) {
- return false;
- }
-
- float bottomOfScreenInterceptX = rawX;
-
- // Only do math if the X velocity is non-zero, otherwise X won't change.
- if (velX != 0) {
- // Rise over run...
- final float slope = velY / velX;
- // ...y = mx + b, b = y / mx...
- final float yIntercept = rawY - slope * rawX;
- // ...calculate the x value when y = bottom of the screen.
- bottomOfScreenInterceptX = (mStack.getHeight() - yIntercept) / slope;
- }
-
- final float dismissTargetWidth =
- mStack.getWidth() * DISMISS_FLING_TARGET_WIDTH_PERCENT;
- return velY > STACK_DISMISS_MIN_VELOCITY
- && bottomOfScreenInterceptX > dismissTargetWidth / 2f
- && bottomOfScreenInterceptX < mStack.getWidth() - dismissTargetWidth / 2f;
- }
-
/** Clears all touch-related state. */
private void resetForNextGesture() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
+
mTouchedView = null;
mMovedEnough = false;
- mInDismissTarget = false;
mStack.onGestureFinished();
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewProvider.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewProvider.java
index f04933a..ef84c73 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleViewProvider.java
@@ -41,4 +41,6 @@
Path getDotPath();
boolean showDot();
+
+ int getDisplayId();
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java
index 607b5ef..9b5dc31 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/ExpandedAnimationController.java
@@ -25,13 +25,14 @@
import android.view.View;
import android.view.WindowInsets;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import com.android.systemui.Interpolators;
import com.android.systemui.R;
-import com.android.systemui.bubbles.BubbleExperimentConfig;
+import com.android.systemui.util.magnetictarget.MagnetizedObject;
import com.google.android.collect.Sets;
@@ -62,6 +63,12 @@
/** What percentage of the screen to use when centering the bubbles in landscape. */
private static final float CENTER_BUBBLES_LANDSCAPE_PERCENT = 0.66f;
+ /**
+ * Velocity required to dismiss an individual bubble without dragging it into the dismiss
+ * target.
+ */
+ private static final float FLING_TO_DISMISS_MIN_VELOCITY = 6000f;
+
/** Horizontal offset between bubbles, which we need to know to re-stack them. */
private float mStackOffsetPx;
/** Space between status bar and bubbles in the expanded state. */
@@ -79,9 +86,6 @@
/** What the current screen orientation is. */
private int mScreenOrientation;
- /** Whether the dragged-out bubble is in the dismiss target. */
- private boolean mIndividualBubbleWithinDismissTarget = false;
-
private boolean mAnimatingExpand = false;
private boolean mAnimatingCollapse = false;
private @Nullable Runnable mAfterExpand;
@@ -99,6 +103,17 @@
*/
private boolean mSpringingBubbleToTouch = false;
+ /**
+ * Whether to spring the bubble to the next touch event coordinates. This is used to animate the
+ * bubble out of the magnetic dismiss target to the touch location.
+ *
+ * Once it 'catches up' and the animation ends, we'll revert to moving it directly.
+ */
+ private boolean mSpringToTouchOnNextMotionEvent = false;
+
+ /** The bubble currently being dragged out of the row (to potentially be dismissed). */
+ private MagnetizedObject<View> mMagnetizedBubbleDraggingOut;
+
private int mExpandedViewPadding;
public ExpandedAnimationController(Point displaySize, int expandedViewPadding,
@@ -113,9 +128,6 @@
*/
private boolean mBubbleDraggedOutEnough = false;
- /** The bubble currently being dragged out of the row (to potentially be dismissed). */
- private View mBubbleDraggingOut;
-
/**
* Animates expanding the bubbles into a row along the top of the screen.
*/
@@ -235,12 +247,46 @@
}).startAll(after);
}
+ /** Notifies the controller that the dragged-out bubble was unstuck from the magnetic target. */
+ public void onUnstuckFromTarget() {
+ mSpringToTouchOnNextMotionEvent = true;
+ }
+
/** Prepares the given bubble to be dragged out. */
- public void prepareForBubbleDrag(View bubble) {
+ public void prepareForBubbleDrag(View bubble, MagnetizedObject.MagneticTarget target) {
mLayout.cancelAnimationsOnView(bubble);
- mBubbleDraggingOut = bubble;
- mBubbleDraggingOut.setTranslationZ(Short.MAX_VALUE);
+ bubble.setTranslationZ(Short.MAX_VALUE);
+ mMagnetizedBubbleDraggingOut = new MagnetizedObject<View>(
+ mLayout.getContext(), bubble,
+ DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y) {
+ @Override
+ public float getWidth(@NonNull View underlyingObject) {
+ return mBubbleSizePx;
+ }
+
+ @Override
+ public float getHeight(@NonNull View underlyingObject) {
+ return mBubbleSizePx;
+ }
+
+ @Override
+ public void getLocationOnScreen(@NonNull View underlyingObject, @NonNull int[] loc) {
+ loc[0] = (int) bubble.getTranslationX();
+ loc[1] = (int) bubble.getTranslationY();
+ }
+ };
+ mMagnetizedBubbleDraggingOut.addTarget(target);
+ mMagnetizedBubbleDraggingOut.setHapticsEnabled(true);
+ mMagnetizedBubbleDraggingOut.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY);
+ }
+
+ private void springBubbleTo(View bubble, float x, float y) {
+ animationForChild(bubble)
+ .translationX(x)
+ .translationY(y)
+ .withStiffness(SpringForce.STIFFNESS_HIGH)
+ .start();
}
/**
@@ -249,20 +295,20 @@
* bubble is dragged back into the row.
*/
public void dragBubbleOut(View bubbleView, float x, float y) {
- if (mSpringingBubbleToTouch) {
+ if (mSpringToTouchOnNextMotionEvent) {
+ springBubbleTo(mMagnetizedBubbleDraggingOut.getUnderlyingObject(), x, y);
+ mSpringToTouchOnNextMotionEvent = false;
+ mSpringingBubbleToTouch = true;
+ } else if (mSpringingBubbleToTouch) {
if (mLayout.arePropertiesAnimatingOnView(
bubbleView, DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y)) {
- animationForChild(mBubbleDraggingOut)
- .translationX(x)
- .translationY(y)
- .withStiffness(SpringForce.STIFFNESS_HIGH)
- .start();
+ springBubbleTo(mMagnetizedBubbleDraggingOut.getUnderlyingObject(), x, y);
} else {
mSpringingBubbleToTouch = false;
}
}
- if (!mSpringingBubbleToTouch && !mIndividualBubbleWithinDismissTarget) {
+ if (!mSpringingBubbleToTouch && !mMagnetizedBubbleDraggingOut.getObjectStuckToTarget()) {
bubbleView.setTranslationX(x);
bubbleView.setTranslationY(y);
}
@@ -277,8 +323,6 @@
/** Plays a dismiss animation on the dragged out bubble. */
public void dismissDraggedOutBubble(View bubble, Runnable after) {
- mIndividualBubbleWithinDismissTarget = false;
-
animationForChild(bubble)
.withStiffness(SpringForce.STIFFNESS_HIGH)
.scaleX(1.1f)
@@ -290,37 +334,14 @@
}
@Nullable public View getDraggedOutBubble() {
- return mBubbleDraggingOut;
+ return mMagnetizedBubbleDraggingOut == null
+ ? null
+ : mMagnetizedBubbleDraggingOut.getUnderlyingObject();
}
- /** Magnets the given bubble to the dismiss target. */
- public void magnetBubbleToDismiss(
- View bubbleView, float velX, float velY, float destY, Runnable after) {
- mIndividualBubbleWithinDismissTarget = true;
- mSpringingBubbleToTouch = false;
- animationForChild(bubbleView)
- .withStiffness(SpringForce.STIFFNESS_MEDIUM)
- .withDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
- .withPositionStartVelocities(velX, velY)
- .translationX(mLayout.getWidth() / 2f - mBubbleSizePx / 2f)
- .translationY(destY, after)
- .start();
- }
-
- /**
- * Springs the dragged-out bubble towards the given coordinates and sets flags to have touch
- * events update the spring's final position until it's settled.
- */
- public void demagnetizeBubbleTo(float x, float y, float velX, float velY) {
- mIndividualBubbleWithinDismissTarget = false;
- mSpringingBubbleToTouch = true;
-
- animationForChild(mBubbleDraggingOut)
- .translationX(x)
- .translationY(y)
- .withPositionStartVelocities(velX, velY)
- .withStiffness(SpringForce.STIFFNESS_HIGH)
- .start();
+ /** Returns the MagnetizedObject instance for the dragging-out bubble. */
+ public MagnetizedObject<View> getMagnetizedBubbleDraggingOut() {
+ return mMagnetizedBubbleDraggingOut;
}
/**
@@ -335,13 +356,14 @@
.withPositionStartVelocities(velX, velY)
.start(() -> bubbleView.setTranslationZ(0f) /* after */);
+ mMagnetizedBubbleDraggingOut = null;
+
updateBubblePositions();
}
/** Resets bubble drag out gesture flags. */
public void onGestureFinished() {
mBubbleDraggedOutEnough = false;
- mBubbleDraggingOut = null;
updateBubblePositions();
}
@@ -373,7 +395,6 @@
pw.print(" isActive: "); pw.println(isActiveController());
pw.print(" animatingExpand: "); pw.println(mAnimatingExpand);
pw.print(" animatingCollapse: "); pw.println(mAnimatingCollapse);
- pw.print(" bubbleInDismiss: "); pw.println(mIndividualBubbleWithinDismissTarget);
pw.print(" springingBubble: "); pw.println(mSpringingBubbleToTouch);
}
@@ -388,11 +409,8 @@
mBubblesMaxRendered = res.getInteger(R.integer.bubbles_max_rendered);
// Includes overflow button.
- // TODO(b/148675523) this is a temporary work around; change back once we have proper fix.
-// float totalGapWidth = getWidthForDisplayingBubbles() - (mExpandedViewPadding * 2)
-// - (mBubblesMaxRendered + 1) * mBubbleSizePx;
- float totalGapWidth = getAvailableScreenWidth(true /* includeStableInsets */)
- - (mExpandedViewPadding * 2) - (mBubblesMaxRendered + 1) * mBubbleSizePx;
+ float totalGapWidth = getWidthForDisplayingBubbles() - (mExpandedViewPadding * 2)
+ - (mBubblesMaxRendered + 1) * mBubbleSizePx;
mSpaceBetweenBubbles = totalGapWidth / mBubblesMaxRendered;
// Ensure that all child views are at 1x scale, and visible, in case they were animating
@@ -453,8 +471,8 @@
final PhysicsAnimationLayout.PhysicsPropertyAnimator animator = animationForChild(child);
// If we're removing the dragged-out bubble, that means it got dismissed.
- if (child.equals(mBubbleDraggingOut)) {
- mBubbleDraggingOut = null;
+ if (child.equals(getDraggedOutBubble())) {
+ mMagnetizedBubbleDraggingOut = null;
finishRemoval.run();
} else {
animator.alpha(0f, finishRemoval /* endAction */)
@@ -490,7 +508,7 @@
// Don't animate the dragging out bubble, or it'll jump around while being dragged. It
// will be snapped to the correct X value after the drag (if it's not dismissed).
- if (bubble.equals(mBubbleDraggingOut)) {
+ if (bubble.equals(getDraggedOutBubble())) {
return;
}
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java b/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
index f22c8fa..b63ba6f 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/animation/StackAnimationController.java
@@ -16,7 +16,6 @@
package com.android.systemui.bubbles.animation;
-import android.annotation.NonNull;
import android.content.res.Resources;
import android.graphics.PointF;
import android.graphics.Rect;
@@ -25,6 +24,7 @@
import android.view.View;
import android.view.WindowInsets;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.FlingAnimation;
@@ -35,6 +35,7 @@
import com.android.systemui.R;
import com.android.systemui.util.FloatingContentCoordinator;
import com.android.systemui.util.animation.PhysicsAnimator;
+import com.android.systemui.util.magnetictarget.MagnetizedObject;
import com.google.android.collect.Sets;
@@ -42,6 +43,7 @@
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;
+import java.util.function.IntSupplier;
/**
* Animation controller for bubbles when they're in their stacked state. Stacked bubbles sit atop
@@ -67,9 +69,10 @@
/**
* Values to use for the default {@link SpringForce} provided to the physics animation layout.
*/
- private static final int DEFAULT_STIFFNESS = 12000;
+ public static final int DEFAULT_STIFFNESS = 12000;
+ public static final float IME_ANIMATION_STIFFNESS = SpringForce.STIFFNESS_LOW;
private static final int FLING_FOLLOW_STIFFNESS = 20000;
- private static final float DEFAULT_BOUNCINESS = 0.9f;
+ public static final float DEFAULT_BOUNCINESS = 0.9f;
/**
* Friction applied to fling animations. Since the stack must land on one of the sides of the
@@ -92,6 +95,9 @@
*/
private static final float ESCAPE_VELOCITY = 750f;
+ /** Velocity required to dismiss the stack without dragging it into the dismiss target. */
+ private static final float FLING_TO_DISMISS_MIN_VELOCITY = 4000f;
+
/**
* The canonical position of the stack. This is typically the position of the first bubble, but
* we need to keep track of it separately from the first bubble's translation in case there are
@@ -100,6 +106,12 @@
private PointF mStackPosition = new PointF(-1, -1);
/**
+ * MagnetizedObject instance for the stack, which is used by the touch handler for the magnetic
+ * dismiss target.
+ */
+ private MagnetizedObject<StackAnimationController> mMagnetizedStack;
+
+ /**
* The area that Bubbles will occupy after all animations end. This is used to move other
* floating content out of the way proactively.
*/
@@ -108,8 +120,11 @@
/** Whether or not the stack's start position has been set. */
private boolean mStackMovedToStartPosition = false;
- /** The most recent position in which the stack was resting on the edge of the screen. */
- @Nullable private PointF mRestingStackPosition;
+ /**
+ * The stack's most recent position along the edge of the screen. This is saved when the last
+ * bubble is removed, so that the stack can be restored in its previous position.
+ */
+ private PointF mRestingStackPosition;
/** The height of the most recently visible IME. */
private float mImeHeight = 0f;
@@ -136,11 +151,6 @@
private boolean mIsMovingFromFlinging = false;
/**
- * Whether the stack is within the dismiss target (either by being dragged, magnet'd, or flung).
- */
- private boolean mWithinDismissTarget = false;
-
- /**
* Whether the first bubble is springing towards the touch point, rather than using the default
* behavior of moving directly to the touch point with the rest of the stack following it.
*
@@ -154,6 +164,14 @@
*/
private boolean mFirstBubbleSpringingToTouch = false;
+ /**
+ * Whether to spring the stack to the next touch event coordinates. This is used to animate the
+ * stack (including the first bubble) out of the magnetic dismiss target to the touch location.
+ * Once it 'catches up' and the animation ends, we'll revert to moving the first bubble directly
+ * and only animating the following bubbles.
+ */
+ private boolean mSpringToTouchOnNextMotionEvent = false;
+
/** Horizontal offset of bubbles in the stack. */
private float mStackOffset;
/** Diameter of the bubble icon. */
@@ -224,9 +242,15 @@
}
};
+ /** Returns the number of 'real' bubbles (excluding the overflow bubble). */
+ private IntSupplier mBubbleCountSupplier;
+
public StackAnimationController(
- FloatingContentCoordinator floatingContentCoordinator) {
+ FloatingContentCoordinator floatingContentCoordinator,
+ IntSupplier bubbleCountSupplier) {
mFloatingContentCoordinator = floatingContentCoordinator;
+ mBubbleCountSupplier = bubbleCountSupplier;
+
}
/**
@@ -273,7 +297,8 @@
* Note that we need new SpringForce instances per animation despite identical configs because
* SpringAnimation uses SpringForce's internal (changing) velocity while the animation runs.
*/
- public void springStack(float destinationX, float destinationY, float stiffness) {
+ public void springStack(
+ float destinationX, float destinationY, float stiffness) {
notifyFloatingCoordinatorStackAnimatingTo(destinationX, destinationY);
springFirstBubbleWithStackFollowing(DynamicAnimation.TRANSLATION_X,
@@ -404,7 +429,7 @@
pw.println(mRestingStackPosition != null ? mRestingStackPosition.toString() : "null");
pw.print(" currentStackPos: "); pw.println(mStackPosition.toString());
pw.print(" isMovingFromFlinging: "); pw.println(mIsMovingFromFlinging);
- pw.print(" withinDismiss: "); pw.println(mWithinDismissTarget);
+ pw.print(" withinDismiss: "); pw.println(isStackStuckToTarget());
pw.print(" firstBubbleSpringing: "); pw.println(mFirstBubbleSpringingToTouch);
}
@@ -451,7 +476,6 @@
.addEndListener((animation, canceled, endValue, endVelocity) -> {
if (!canceled) {
- mRestingStackPosition = new PointF();
mRestingStackPosition.set(mStackPosition);
springFirstBubbleWithStackFollowing(property, spring, endVelocity,
@@ -487,8 +511,10 @@
/**
* Animates the stack either away from the newly visible IME, or back to its original position
* due to the IME going away.
+ *
+ * @return The destination Y value of the stack due to the IME movement.
*/
- public void animateForImeVisibility(boolean imeVisible) {
+ public float animateForImeVisibility(boolean imeVisible) {
final float maxBubbleY = getAllowableStackPositionRegion().bottom;
float destinationY = Float.MIN_VALUE;
@@ -509,12 +535,14 @@
springFirstBubbleWithStackFollowing(
DynamicAnimation.TRANSLATION_Y,
getSpringForce(DynamicAnimation.TRANSLATION_Y, /* view */ null)
- .setStiffness(SpringForce.STIFFNESS_LOW),
+ .setStiffness(IME_ANIMATION_STIFFNESS),
/* startVel */ 0f,
destinationY);
notifyFloatingCoordinatorStackAnimatingTo(mStackPosition.x, destinationY);
}
+
+ return destinationY;
}
/**
@@ -569,7 +597,7 @@
- mBubblePaddingTop
- (mImeHeight > Float.MIN_VALUE ? mImeHeight + mBubblePaddingTop : 0f)
- Math.max(
- insets.getSystemWindowInsetBottom(),
+ insets.getStableInsetBottom(),
insets.getDisplayCutout() != null
? insets.getDisplayCutout().getSafeInsetBottom()
: 0);
@@ -580,14 +608,18 @@
/** Moves the stack in response to a touch event. */
public void moveStackFromTouch(float x, float y) {
-
- // If we're springing to the touch point to 'catch up' after dragging out of the dismiss
- // target, then update the stack position animations instead of moving the bubble directly.
- if (mFirstBubbleSpringingToTouch) {
+ // Begin the spring-to-touch catch up animation if needed.
+ if (mSpringToTouchOnNextMotionEvent) {
+ springStack(x, y, DEFAULT_STIFFNESS);
+ mSpringToTouchOnNextMotionEvent = false;
+ mFirstBubbleSpringingToTouch = true;
+ } else if (mFirstBubbleSpringingToTouch) {
final SpringAnimation springToTouchX =
- (SpringAnimation) mStackPositionAnimations.get(DynamicAnimation.TRANSLATION_X);
+ (SpringAnimation) mStackPositionAnimations.get(
+ DynamicAnimation.TRANSLATION_X);
final SpringAnimation springToTouchY =
- (SpringAnimation) mStackPositionAnimations.get(DynamicAnimation.TRANSLATION_Y);
+ (SpringAnimation) mStackPositionAnimations.get(
+ DynamicAnimation.TRANSLATION_Y);
// If either animation is still running, we haven't caught up. Update the animations.
if (springToTouchX.isRunning() || springToTouchY.isRunning()) {
@@ -600,56 +632,14 @@
}
}
- if (!mFirstBubbleSpringingToTouch && !mWithinDismissTarget) {
+ if (!mFirstBubbleSpringingToTouch && !isStackStuckToTarget()) {
moveFirstBubbleWithStackFollowing(x, y);
}
}
- /**
- * Demagnetizes the stack, springing it towards the given point. This also sets flags so that
- * subsequent touch events will update the final position of the demagnetization spring instead
- * of directly moving the bubbles, until demagnetization is complete.
- */
- public void demagnetizeFromDismissToPoint(float x, float y, float velX, float velY) {
- mWithinDismissTarget = false;
- mFirstBubbleSpringingToTouch = true;
-
- springFirstBubbleWithStackFollowing(
- DynamicAnimation.TRANSLATION_X,
- new SpringForce()
- .setDampingRatio(DEFAULT_BOUNCINESS)
- .setStiffness(DEFAULT_STIFFNESS),
- velX, x);
-
- springFirstBubbleWithStackFollowing(
- DynamicAnimation.TRANSLATION_Y,
- new SpringForce()
- .setDampingRatio(DEFAULT_BOUNCINESS)
- .setStiffness(DEFAULT_STIFFNESS),
- velY, y);
- }
-
- /**
- * Spring the stack towards the dismiss target, respecting existing velocity. This also sets
- * flags so that subsequent touch events will not move the stack until it's demagnetized.
- */
- public void magnetToDismiss(float velX, float velY, float destY, Runnable after) {
- mWithinDismissTarget = true;
- mFirstBubbleSpringingToTouch = false;
-
- springFirstBubbleWithStackFollowing(
- DynamicAnimation.TRANSLATION_X,
- new SpringForce()
- .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
- .setStiffness(SpringForce.STIFFNESS_MEDIUM),
- velX, mLayout.getWidth() / 2f - mBubbleBitmapSize / 2f);
-
- springFirstBubbleWithStackFollowing(
- DynamicAnimation.TRANSLATION_Y,
- new SpringForce()
- .setDampingRatio(SpringForce.DAMPING_RATIO_LOW_BOUNCY)
- .setStiffness(SpringForce.STIFFNESS_MEDIUM),
- velY, destY, after);
+ /** Notify the controller that the stack has been unstuck from the dismiss target. */
+ public void onUnstuckFromTarget() {
+ mSpringToTouchOnNextMotionEvent = true;
}
/**
@@ -663,13 +653,7 @@
.alpha(0f)
.withDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY)
.withStiffness(SpringForce.STIFFNESS_HIGH)
- .start(() -> {
- // Run the callback and reset flags. The child translation animations might
- // still be running, but that's fine. Once the alpha is at 0f they're no longer
- // visible anyway.
- after.run();
- mWithinDismissTarget = false;
- });
+ .start(after);
}
/**
@@ -692,6 +676,8 @@
new SpringAnimation(this, firstBubbleProperty)
.setSpring(spring)
.addEndListener((dynamicAnimation, b, v, v1) -> {
+ mRestingStackPosition.set(mStackPosition);
+
if (after != null) {
for (Runnable callback : after) {
callback.run();
@@ -720,7 +706,7 @@
if (property.equals(DynamicAnimation.TRANSLATION_X)
|| property.equals(DynamicAnimation.TRANSLATION_Y)) {
return index + 1;
- } else if (mWithinDismissTarget) {
+ } else if (isStackStuckToTarget()) {
return index + 1; // Chain all animations in dismiss (scale, alpha, etc. are used).
} else {
return NONE;
@@ -733,7 +719,7 @@
if (property.equals(DynamicAnimation.TRANSLATION_X)) {
// If we're in the dismiss target, have the bubbles pile on top of each other with no
// offset.
- if (mWithinDismissTarget) {
+ if (isStackStuckToTarget()) {
return 0f;
} else {
// Offset to the left if we're on the left, or the right otherwise.
@@ -755,11 +741,11 @@
@Override
void onChildAdded(View child, int index) {
// Don't animate additions within the dismiss target.
- if (mWithinDismissTarget) {
+ if (isStackStuckToTarget()) {
return;
}
- if (mLayout.getChildCount() == 1) {
+ if (getBubbleCount() == 1) {
// If this is the first child added, position the stack in its starting position.
moveStackToStartPosition();
} else if (isStackPositionSet() && mLayout.indexOfChild(child) == 0) {
@@ -781,11 +767,9 @@
.start();
// If there are other bubbles, pull them into the correct position.
- if (mLayout.getChildCount() > 0) {
+ if (getBubbleCount() > 0) {
animationForChildAtIndex(0).translationX(mStackPosition.x).start();
} else {
- // If there's no other bubbles, and we were in the dismiss target, reset the flag.
- mWithinDismissTarget = false;
// When all children are removed ensure stack position is sane
setStackPosition(mRestingStackPosition == null
? getDefaultStartPosition()
@@ -831,6 +815,9 @@
}
}
+ private boolean isStackStuckToTarget() {
+ return mMagnetizedStack != null && mMagnetizedStack.getObjectStuckToTarget();
+ }
/** Moves the stack, without any animation, to the starting position. */
private void moveStackToStartPosition() {
@@ -882,7 +869,12 @@
public void setStackPosition(PointF pos) {
Log.d(TAG, String.format("Setting position to (%f, %f).", pos.x, pos.y));
mStackPosition.set(pos.x, pos.y);
- mRestingStackPosition = mStackPosition;
+
+ if (mRestingStackPosition == null) {
+ mRestingStackPosition = new PointF();
+ }
+
+ mRestingStackPosition.set(mStackPosition);
// If we're not the active controller, we don't want to physically move the bubble views.
if (isActiveController()) {
@@ -959,6 +951,49 @@
}
/**
+ * Returns the {@link MagnetizedObject} instance for the bubble stack, with the provided
+ * {@link MagnetizedObject.MagneticTarget} added as a target.
+ */
+ public MagnetizedObject<StackAnimationController> getMagnetizedStack(
+ MagnetizedObject.MagneticTarget target) {
+ if (mMagnetizedStack == null) {
+ mMagnetizedStack = new MagnetizedObject<StackAnimationController>(
+ mLayout.getContext(),
+ this,
+ new StackPositionProperty(DynamicAnimation.TRANSLATION_X),
+ new StackPositionProperty(DynamicAnimation.TRANSLATION_Y)
+ ) {
+ @Override
+ public float getWidth(@NonNull StackAnimationController underlyingObject) {
+ return mBubbleSize;
+ }
+
+ @Override
+ public float getHeight(@NonNull StackAnimationController underlyingObject) {
+ return mBubbleSize;
+ }
+
+ @Override
+ public void getLocationOnScreen(@NonNull StackAnimationController underlyingObject,
+ @NonNull int[] loc) {
+ loc[0] = (int) mStackPosition.x;
+ loc[1] = (int) mStackPosition.y;
+ }
+ };
+ mMagnetizedStack.addTarget(target);
+ mMagnetizedStack.setHapticsEnabled(true);
+ mMagnetizedStack.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY);
+ }
+
+ return mMagnetizedStack;
+ }
+
+ /** Returns the number of 'real' bubbles (excluding overflow). */
+ private int getBubbleCount() {
+ return mBubbleCountSupplier.getAsInt();
+ }
+
+ /**
* FloatProperty that uses {@link #moveFirstBubbleWithStackFollowing} to set the first bubble's
* translation and animate the rest of the stack with it. A DynamicAnimation can animate this
* property directly to move the first bubble and cause the stack to 'follow' to the new
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/dagger/BubbleModule.java b/packages/SystemUI/src/com/android/systemui/bubbles/dagger/BubbleModule.java
index ac97d8a..27c9e98 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/dagger/BubbleModule.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/dagger/BubbleModule.java
@@ -25,8 +25,8 @@
import com.android.systemui.statusbar.FeatureFlags;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.ShadeController;
@@ -54,7 +54,7 @@
ShadeController shadeController,
BubbleData data,
ConfigurationController configurationController,
- NotificationInterruptionStateProvider interruptionStateProvider,
+ NotificationInterruptStateProvider interruptionStateProvider,
ZenModeController zenModeController,
NotificationLockscreenUserManager notifUserManager,
NotificationGroupManager groupManager,
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ControlStatus.kt b/packages/SystemUI/src/com/android/systemui/controls/ControlStatus.kt
index 49a16d8..dec6007 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ControlStatus.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ControlStatus.kt
@@ -16,10 +16,12 @@
package com.android.systemui.controls
+import android.content.ComponentName
import android.service.controls.Control
data class ControlStatus(
val control: Control,
+ val component: ComponentName,
var favorite: Boolean,
val removed: Boolean = false
-)
\ No newline at end of file
+)
diff --git a/packages/SystemUI/src/com/android/systemui/controls/TooltipManager.kt b/packages/SystemUI/src/com/android/systemui/controls/TooltipManager.kt
new file mode 100644
index 0000000..6e17bc9
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/TooltipManager.kt
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2020 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.controls
+
+import android.annotation.StringRes
+import android.content.Context
+import android.graphics.CornerPathEffect
+import android.graphics.drawable.ShapeDrawable
+import android.util.TypedValue
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.view.animation.AccelerateInterpolator
+import android.view.animation.DecelerateInterpolator
+import android.widget.TextView
+import com.android.systemui.Prefs
+import com.android.systemui.R
+import com.android.systemui.recents.TriangleShape
+
+/**
+ * Manager for showing an onboarding tooltip on screen.
+ *
+ * The tooltip can be made to appear below or above a point. The number of times it will appear
+ * is determined by an shared preference (defined in [Prefs]).
+ *
+ * @property context A context to use to inflate the views and retrieve shared preferences from
+ * @property preferenceName name of the preference to use to track the number of times the tooltip
+ * has been shown.
+ * @property maxTimesShown the maximum number of times to show the tooltip
+ * @property below whether the tooltip should appear below (with up pointing arrow) or above (down
+ * pointing arrow) the specified point.
+ * @see [TooltipManager.show]
+ */
+class TooltipManager(
+ context: Context,
+ private val preferenceName: String,
+ private val maxTimesShown: Int = 2,
+ private val below: Boolean = true
+) {
+
+ companion object {
+ private const val SHOW_DELAY_MS: Long = 500
+ private const val SHOW_DURATION_MS: Long = 300
+ private const val HIDE_DURATION_MS: Long = 100
+ }
+
+ private var shown = Prefs.getInt(context, preferenceName, 0)
+
+ val layout: ViewGroup =
+ LayoutInflater.from(context).inflate(R.layout.controls_onboarding, null) as ViewGroup
+ val preferenceStorer = { num: Int ->
+ Prefs.putInt(context, preferenceName, num)
+ }
+
+ init {
+ layout.alpha = 0f
+ }
+
+ private val textView = layout.requireViewById<TextView>(R.id.onboarding_text)
+ private val dismissView = layout.requireViewById<View>(R.id.dismiss).apply {
+ setOnClickListener {
+ hide(true)
+ }
+ }
+
+ private val arrowView = layout.requireViewById<View>(R.id.arrow).apply {
+ val typedValue = TypedValue()
+ context.theme.resolveAttribute(android.R.attr.colorAccent, typedValue, true)
+ val toastColor = context.resources.getColor(typedValue.resourceId, context.theme)
+ val arrowRadius = context.resources.getDimensionPixelSize(
+ R.dimen.recents_onboarding_toast_arrow_corner_radius)
+ val arrowLp = layoutParams
+ val arrowDrawable = ShapeDrawable(TriangleShape.create(
+ arrowLp.width.toFloat(), arrowLp.height.toFloat(), below))
+ val arrowPaint = arrowDrawable.paint
+ arrowPaint.color = toastColor
+ // The corner path effect won't be reflected in the shadow, but shouldn't be noticeable.
+ arrowPaint.pathEffect = CornerPathEffect(arrowRadius.toFloat())
+ setBackground(arrowDrawable)
+ }
+
+ init {
+ if (!below) {
+ layout.removeView(arrowView)
+ layout.addView(arrowView)
+ (arrowView.layoutParams as ViewGroup.MarginLayoutParams).apply {
+ bottomMargin = topMargin
+ topMargin = 0
+ }
+ }
+ }
+
+ /**
+ * Show the tooltip
+ *
+ * @param stringRes the id of the string to show in the tooltip
+ * @param x horizontal position (w.r.t. screen) for the arrow point
+ * @param y vertical position (w.r.t. screen) for the arrow point
+ */
+ fun show(@StringRes stringRes: Int, x: Int, y: Int) {
+ if (!shouldShow()) return
+ textView.setText(stringRes)
+ shown++
+ preferenceStorer(shown)
+ layout.post {
+ val p = IntArray(2)
+ layout.getLocationOnScreen(p)
+ layout.translationX = (x - p[0] - layout.width / 2).toFloat()
+ layout.translationY = (y - p[1]).toFloat() - if (!below) layout.height else 0
+ if (layout.alpha == 0f) {
+ layout.animate()
+ .alpha(1f)
+ .withLayer()
+ .setStartDelay(SHOW_DELAY_MS)
+ .setDuration(SHOW_DURATION_MS)
+ .setInterpolator(DecelerateInterpolator())
+ .start()
+ }
+ }
+ }
+
+ /**
+ * Hide the tooltip
+ *
+ * @param animate whether to animate the fade out
+ */
+ fun hide(animate: Boolean = false) {
+ if (layout.alpha == 0f) return
+ layout.post {
+ if (animate) {
+ layout.animate()
+ .alpha(0f)
+ .withLayer()
+ .setStartDelay(0)
+ .setDuration(HIDE_DURATION_MS)
+ .setInterpolator(AccelerateInterpolator())
+ .start()
+ } else {
+ layout.animate().cancel()
+ layout.alpha = 0f
+ }
+ }
+ }
+
+ private fun shouldShow() = shown < maxTimesShown
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingController.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingController.kt
index fd6e256..c5af436 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingController.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingController.kt
@@ -38,8 +38,9 @@
*
* @param component The [ComponentName] of the service to bind
* @param callback a callback to return the loaded controls to (or an error).
+ * @return a runnable to cancel the load
*/
- fun bindAndLoad(component: ComponentName, callback: LoadCallback)
+ fun bindAndLoad(component: ComponentName, callback: LoadCallback): Runnable
/**
* Request to bind to the given service.
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingControllerImpl.kt
index 8f02c25..f8d4a39 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsBindingControllerImpl.kt
@@ -31,7 +31,6 @@
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.util.concurrency.DelayableExecutor
import dagger.Lazy
-import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
@@ -47,8 +46,6 @@
private const val TAG = "ControlsBindingControllerImpl"
}
- private val refreshing = AtomicBoolean(false)
-
private var currentUser = UserHandle.of(ActivityManager.getCurrentUser())
override val currentUserId: Int
@@ -56,6 +53,12 @@
private var currentProvider: ControlsProviderLifecycleManager? = null
+ /*
+ * Will track any active subscriber for subscribe/unsubscribe requests coming into
+ * this controller. Only one can be active at any time
+ */
+ private var statefulControlSubscriber: StatefulControlSubscriber? = null
+
private val actionCallbackService = object : IControlsActionCallback.Stub() {
override fun accept(
token: IBinder,
@@ -66,27 +69,6 @@
}
}
- private val subscriberService = object : IControlsSubscriber.Stub() {
- override fun onSubscribe(token: IBinder, subs: IControlsSubscription) {
- backgroundExecutor.execute(OnSubscribeRunnable(token, subs))
- }
-
- override fun onNext(token: IBinder, c: Control) {
- if (!refreshing.get()) {
- Log.d(TAG, "Refresh outside of window for token:$token")
- } else {
- backgroundExecutor.execute(OnNextRunnable(token, c))
- }
- }
- override fun onError(token: IBinder, s: String) {
- backgroundExecutor.execute(OnErrorRunnable(token, s))
- }
-
- override fun onComplete(token: IBinder) {
- backgroundExecutor.execute(OnCompleteRunnable(token))
- }
- }
-
@VisibleForTesting
internal open fun createProviderManager(component: ComponentName):
ControlsProviderLifecycleManager {
@@ -94,43 +76,45 @@
context,
backgroundExecutor,
actionCallbackService,
- subscriberService,
currentUser,
component
)
}
private fun retrieveLifecycleManager(component: ComponentName):
- ControlsProviderLifecycleManager? {
+ ControlsProviderLifecycleManager {
if (currentProvider != null && currentProvider?.componentName != component) {
unbind()
}
- if (currentProvider == null) {
- currentProvider = createProviderManager(component)
- }
+ val provider = currentProvider ?: createProviderManager(component)
+ currentProvider = provider
- return currentProvider
+ return provider
}
override fun bindAndLoad(
component: ComponentName,
callback: ControlsBindingController.LoadCallback
- ) {
- retrieveLifecycleManager(component)?.maybeBindAndLoad(LoadSubscriber(callback))
+ ): Runnable {
+ val subscriber = LoadSubscriber(callback)
+ retrieveLifecycleManager(component).maybeBindAndLoad(subscriber)
+ return subscriber.loadCancel()
}
override fun subscribe(structureInfo: StructureInfo) {
- if (refreshing.compareAndSet(false, true)) {
- val provider = retrieveLifecycleManager(structureInfo.componentName)
- provider?.maybeBindAndSubscribe(structureInfo.controls.map { it.controlId })
- }
+ // make sure this has happened. only allow one active subscription
+ unsubscribe()
+
+ statefulControlSubscriber = null
+ val provider = retrieveLifecycleManager(structureInfo.componentName)
+ val scs = StatefulControlSubscriber(lazyController.get(), provider, backgroundExecutor)
+ statefulControlSubscriber = scs
+ provider.maybeBindAndSubscribe(structureInfo.controls.map { it.controlId }, scs)
}
override fun unsubscribe() {
- if (refreshing.compareAndSet(true, false)) {
- currentProvider?.unsubscribe()
- }
+ statefulControlSubscriber?.cancel()
}
override fun action(
@@ -138,20 +122,24 @@
controlInfo: ControlInfo,
action: ControlAction
) {
- retrieveLifecycleManager(componentName)
- ?.maybeBindAndSendAction(controlInfo.controlId, action)
+ if (statefulControlSubscriber == null) {
+ Log.w(TAG, "No actions can occur outside of an active subscription. Ignoring.")
+ } else {
+ retrieveLifecycleManager(componentName)
+ .maybeBindAndSendAction(controlInfo.controlId, action)
+ }
}
override fun bindService(component: ComponentName) {
- retrieveLifecycleManager(component)?.bindService()
+ retrieveLifecycleManager(component).bindService()
}
override fun changeUser(newUser: UserHandle) {
if (newUser == currentUser) return
+ unsubscribe()
unbind()
-
- refreshing.set(false)
+ currentProvider = null
currentUser = newUser
}
@@ -172,8 +160,8 @@
override fun toString(): String {
return StringBuilder(" ControlsBindingController:\n").apply {
- append(" refreshing=${refreshing.get()}\n")
append(" currentUser=$currentUser\n")
+ append(" StatefulControlSubscriber=$statefulControlSubscriber")
append(" Providers=$currentProvider\n")
}.toString()
}
@@ -208,22 +196,6 @@
) : CallbackRunnable(token) {
override fun doRun() {
callback.accept(list)
- provider?.unbindService()
- }
- }
-
- private inner class OnNextRunnable(
- token: IBinder,
- val control: Control
- ) : CallbackRunnable(token) {
- override fun doRun() {
- if (!refreshing.get()) {
- Log.d(TAG, "onRefresh outside of window from:${provider?.componentName}")
- }
-
- provider?.let {
- lazyController.get().refreshStatus(it.componentName, control)
- }
}
}
@@ -232,33 +204,7 @@
val subscription: IControlsSubscription
) : CallbackRunnable(token) {
override fun doRun() {
- if (!refreshing.get()) {
- Log.d(TAG, "onRefresh outside of window from '${provider?.componentName}'")
- }
- provider?.let {
- it.startSubscription(subscription)
- }
- }
- }
-
- private inner class OnCompleteRunnable(
- token: IBinder
- ) : CallbackRunnable(token) {
- override fun doRun() {
- provider?.let {
- Log.i(TAG, "onComplete receive from '${it.componentName}'")
- }
- }
- }
-
- private inner class OnErrorRunnable(
- token: IBinder,
- val error: String
- ) : CallbackRunnable(token) {
- override fun doRun() {
- provider?.let {
- Log.e(TAG, "onError receive from '${it.componentName}': $error")
- }
+ provider?.startSubscription(subscription)
}
}
@@ -292,8 +238,14 @@
) : IControlsSubscriber.Stub() {
val loadedControls = ArrayList<Control>()
var hasError = false
+ private var _loadCancelInternal: (() -> Unit)? = null
+ fun loadCancel() = Runnable {
+ Log.d(TAG, "Cancel load requested")
+ _loadCancelInternal?.invoke()
+ }
override fun onSubscribe(token: IBinder, subs: IControlsSubscription) {
+ _loadCancelInternal = subs::cancel
backgroundExecutor.execute(OnSubscribeRunnable(token, subs))
}
@@ -302,11 +254,15 @@
}
override fun onError(token: IBinder, s: String) {
hasError = true
+ _loadCancelInternal = {}
+ currentProvider?.cancelLoadTimeout()
backgroundExecutor.execute(OnLoadErrorRunnable(token, s, callback))
}
override fun onComplete(token: IBinder) {
+ _loadCancelInternal = {}
if (!hasError) {
+ currentProvider?.cancelLoadTimeout()
backgroundExecutor.execute(OnLoadRunnable(token, loadedControls, callback))
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsController.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsController.kt
index f2881d4..9e0d26c 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsController.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsController.kt
@@ -59,6 +59,11 @@
)
/**
+ * Cancels a pending load call
+ */
+ fun cancelLoad()
+
+ /**
* Request to subscribe for favorited controls per structure
*
* @param structureInfo structure to limit the subscription to
@@ -124,6 +129,18 @@
fun getFavoritesForComponent(componentName: ComponentName): List<StructureInfo>
/**
+ * Adds a single favorite to a given component and structure
+ * @param componentName the name of the service that provides the [Control]
+ * @param structureName the name of the structure that holds the [Control]
+ * @param controlInfo persistent information about the [Control] to be added.
+ */
+ fun addFavorite(
+ componentName: ComponentName,
+ structureName: CharSequence,
+ controlInfo: ControlInfo
+ )
+
+ /**
* Replaces the favorites for the given structure.
*
* Calling this method will eliminate the previous selection of favorites and replace it with a
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt
index dedd341..9cb902f 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsControllerImpl.kt
@@ -72,6 +72,8 @@
private var userChanging: Boolean = true
+ private var loadCanceller: Runnable? = null
+
private var currentUser = UserHandle.of(ActivityManager.getCurrentUser())
override val currentUserId
get() = currentUser.identifier
@@ -125,14 +127,19 @@
@VisibleForTesting
internal val settingObserver = object : ContentObserver(null) {
- override fun onChange(selfChange: Boolean, uri: Uri, userId: Int) {
+ override fun onChange(
+ selfChange: Boolean,
+ uris: Collection<Uri>,
+ flags: Int,
+ userId: Int
+ ) {
// Do not listen to changes in the middle of user change, those will be read by the
// user-switch receiver.
if (userChanging || userId != currentUserId) {
return
}
available = Settings.Secure.getIntForUser(contentResolver, CONTROLS_AVAILABLE,
- DEFAULT_ENABLED, currentUserId) != 0
+ DEFAULT_ENABLED, currentUserId) != 0
resetFavorites(available)
}
}
@@ -208,8 +215,9 @@
if (!confirmAvailability()) {
if (userChanging) {
// Try again later, userChanging should not last forever. If so, we have bigger
- // problems
- executor.executeDelayed(
+ // problems. This will return a runnable that allows to cancel the delayed version,
+ // it will not be able to cancel the load if
+ loadCanceller = executor.executeDelayed(
{ loadForComponent(componentName, dataCallback) },
USER_CHANGE_RETRY_DELAY,
TimeUnit.MILLISECONDS
@@ -219,10 +227,11 @@
}
return
}
- bindingController.bindAndLoad(
+ loadCanceller = bindingController.bindAndLoad(
componentName,
object : ControlsBindingController.LoadCallback {
override fun accept(controls: List<Control>) {
+ loadCanceller = null
executor.execute {
val favoritesForComponentKeys = Favorites
.getControlsForComponent(componentName).map { it.controlId }
@@ -233,7 +242,11 @@
}
val removed = findRemoved(favoritesForComponentKeys.toSet(), controls)
val controlsWithFavorite = controls.map {
- ControlStatus(it, it.controlId in favoritesForComponentKeys)
+ ControlStatus(
+ it,
+ componentName,
+ it.controlId in favoritesForComponentKeys
+ )
}
val loadData = createLoadDataObject(
Favorites.getControlsForComponent(componentName)
@@ -242,28 +255,37 @@
controlsWithFavorite,
favoritesForComponentKeys
)
-
dataCallback.accept(loadData)
}
}
override fun error(message: String) {
- val loadData = Favorites.getControlsForComponent(componentName).let {
- controls ->
+ loadCanceller = null
+ executor.execute {
+ val loadData = Favorites.getControlsForComponent(componentName)
+ .let { controls ->
val keys = controls.map { it.controlId }
createLoadDataObject(
- controls.map { createRemovedStatus(componentName, it, false) },
- keys,
- true
+ controls.map {
+ createRemovedStatus(componentName, it, false)
+ },
+ keys,
+ true
)
+ }
+ dataCallback.accept(loadData)
}
-
- dataCallback.accept(loadData)
}
}
)
}
+ override fun cancelLoad() {
+ loadCanceller?.let {
+ executor.execute(it)
+ }
+ }
+
private fun createRemovedStatus(
componentName: ComponentName,
controlInfo: ControlInfo,
@@ -281,7 +303,7 @@
.setTitle(controlInfo.controlTitle)
.setDeviceType(controlInfo.deviceType)
.build()
- return ControlStatus(control, true, setRemoved)
+ return ControlStatus(control, componentName, true, setRemoved)
}
private fun findRemoved(favoriteKeys: Set<String>, list: List<Control>): Set<String> {
@@ -300,6 +322,19 @@
bindingController.unsubscribe()
}
+ override fun addFavorite(
+ componentName: ComponentName,
+ structureName: CharSequence,
+ controlInfo: ControlInfo
+ ) {
+ if (!confirmAvailability()) return
+ executor.execute {
+ if (Favorites.addFavorite(componentName, structureName, controlInfo)) {
+ persistenceWrapper.storeFavorites(Favorites.getAllStructures())
+ }
+ }
+ }
+
override fun replaceFavoritesForStructure(structureInfo: StructureInfo) {
if (!confirmAvailability()) return
executor.execute {
@@ -437,6 +472,24 @@
favMap = newFavMap
}
+ fun addFavorite(
+ componentName: ComponentName,
+ structureName: CharSequence,
+ controlInfo: ControlInfo
+ ): Boolean {
+ // Check if control is in favorites
+ if (getControlsForComponent(componentName)
+ .any { it.controlId == controlInfo.controlId }) {
+ return false
+ }
+ val structureInfo = favMap.get(componentName)
+ ?.firstOrNull { it.structure == structureName }
+ ?: StructureInfo(componentName, structureName, emptyList())
+ val newStructureInfo = structureInfo.copy(controls = structureInfo.controls + controlInfo)
+ replaceControls(newStructureInfo)
+ return true
+ }
+
fun replaceControls(updatedStructure: StructureInfo) {
val newFavMap = favMap.toMutableMap()
val structures = mutableListOf<StructureInfo>()
@@ -449,15 +502,17 @@
updatedStructure
} else { s }
- structures.add(newStructure)
+ if (!newStructure.controls.isEmpty()) {
+ structures.add(newStructure)
+ }
}
- if (!replaced) {
+ if (!replaced && !updatedStructure.controls.isEmpty()) {
structures.add(updatedStructure)
}
- newFavMap.put(componentName, structures.toList())
- favMap = newFavMap.toMap()
+ newFavMap.put(componentName, structures)
+ favMap = newFavMap
}
fun clear() {
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManager.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManager.kt
index 86e8e83..4918bd7 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManager.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManager.kt
@@ -58,7 +58,6 @@
private val context: Context,
private val executor: DelayableExecutor,
private val actionCallbackService: IControlsActionCallback.Stub,
- private val subscriberService: IControlsSubscriber.Stub,
val user: UserHandle,
val componentName: ComponentName
) : IBinder.DeathRecipient {
@@ -157,10 +156,9 @@
load(msg.subscriber)
}
- queue.filter { it is Message.Subscribe }.flatMap { (it as Message.Subscribe).list }.run {
- if (this.isNotEmpty()) {
- subscribe(this)
- }
+ queue.filter { it is Message.Subscribe }.forEach {
+ val msg = it as Message.Subscribe
+ subscribe(msg.list, msg.subscriber)
}
queue.filter { it is Message.Action }.forEach {
val msg = it as Message.Action
@@ -185,9 +183,9 @@
}
}
- private fun unqueueMessage(message: Message) {
+ private fun unqueueMessageType(type: Int) {
synchronized(queuedMessages) {
- queuedMessages.removeIf { it.type == message.type }
+ queuedMessages.removeIf { it.type == type }
}
}
@@ -219,7 +217,7 @@
* @param subscriber the subscriber that manages coordination for loading controls
*/
fun maybeBindAndLoad(subscriber: IControlsSubscriber.Stub) {
- unqueueMessage(Message.Unbind)
+ unqueueMessageType(MSG_UNBIND)
onLoadCanceller = executor.executeDelayed({
// Didn't receive a response in time, log and send back error
Log.d(TAG, "Timeout waiting onLoad for $componentName")
@@ -230,6 +228,11 @@
invokeOrQueue({ load(subscriber) }, Message.Load(subscriber))
}
+ fun cancelLoadTimeout() {
+ onLoadCanceller?.run()
+ onLoadCanceller = null
+ }
+
/**
* Request a subscription to the [Publisher] returned by [ControlsProviderService.publisherFor]
*
@@ -237,16 +240,20 @@
*
* @param controlIds a list of the ids of controls to send status back.
*/
- fun maybeBindAndSubscribe(controlIds: List<String>) {
- invokeOrQueue({ subscribe(controlIds) }, Message.Subscribe(controlIds))
+ fun maybeBindAndSubscribe(controlIds: List<String>, subscriber: IControlsSubscriber) {
+ invokeOrQueue(
+ { subscribe(controlIds, subscriber) },
+ Message.Subscribe(controlIds, subscriber)
+ )
}
- private fun subscribe(controlIds: List<String>) {
+ private fun subscribe(controlIds: List<String>, subscriber: IControlsSubscriber) {
if (DEBUG) {
Log.d(TAG, "subscribe $componentName - $controlIds")
}
- if (!(wrapper?.subscribe(controlIds, subscriberService) ?: false)) {
- queueMessage(Message.Subscribe(controlIds))
+
+ if (!(wrapper?.subscribe(controlIds, subscriber) ?: false)) {
+ queueMessage(Message.Subscribe(controlIds, subscriber))
binderDied()
}
}
@@ -276,10 +283,13 @@
/**
* Starts the subscription to the [ControlsProviderService] and requests status of controls.
*
- * @param subscription the subscriber to use to request controls
+ * @param subscription the subscription to use to request controls
* @see maybeBindAndLoad
*/
fun startSubscription(subscription: IControlsSubscription) {
+ if (DEBUG) {
+ Log.d(TAG, "startSubscription: $subscription")
+ }
synchronized(subscriptions) {
subscriptions.add(subscription)
}
@@ -287,30 +297,26 @@
}
/**
- * Unsubscribe from this service, cancelling all status requests.
+ * Cancels the subscription to the [ControlsProviderService].
+ *
+ * @param subscription the subscription to cancel
+ * @see maybeBindAndLoad
*/
- fun unsubscribe() {
+ fun cancelSubscription(subscription: IControlsSubscription) {
if (DEBUG) {
- Log.d(TAG, "unsubscribe $componentName")
+ Log.d(TAG, "cancelSubscription: $subscription")
}
- unqueueMessage(Message.Subscribe(emptyList())) // Removes all subscribe messages
-
- val subs = synchronized(subscriptions) {
- ArrayList(subscriptions).also {
- subscriptions.clear()
- }
+ synchronized(subscriptions) {
+ subscriptions.remove(subscription)
}
-
- subs.forEach {
- wrapper?.cancel(it)
- }
+ wrapper?.cancel(subscription)
}
/**
* Request bind to the service.
*/
fun bindService() {
- unqueueMessage(Message.Unbind)
+ unqueueMessageType(MSG_UNBIND)
bindService(true)
}
@@ -321,8 +327,16 @@
onLoadCanceller?.run()
onLoadCanceller = null
- // just in case this wasn't called already
- unsubscribe()
+ // be sure to cancel all subscriptions
+ val subs = synchronized(subscriptions) {
+ ArrayList(subscriptions).also {
+ subscriptions.clear()
+ }
+ }
+
+ subs.forEach {
+ wrapper?.cancel(it)
+ }
bindService(false)
}
@@ -346,7 +360,7 @@
object Unbind : Message() {
override val type = MSG_UNBIND
}
- class Subscribe(val list: List<String>) : Message() {
+ class Subscribe(val list: List<String>, val subscriber: IControlsSubscriber) : Message() {
override val type = MSG_SUBSCRIBE
}
class Action(val id: String, val action: ControlAction) : Message() {
diff --git a/packages/SystemUI/src/com/android/systemui/controls/controller/StatefulControlSubscriber.kt b/packages/SystemUI/src/com/android/systemui/controls/controller/StatefulControlSubscriber.kt
new file mode 100644
index 0000000..a371aa6
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/controller/StatefulControlSubscriber.kt
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2020 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.controls.controller
+
+import android.os.IBinder
+import android.service.controls.Control
+import android.service.controls.IControlsSubscriber
+import android.service.controls.IControlsSubscription
+import android.util.Log
+import com.android.systemui.util.concurrency.DelayableExecutor
+
+/**
+ * A single subscriber, supporting stateful controls for publishers created by
+ * {@link ControlsProviderService#createPublisherFor}. In general, this subscription will remain
+ * active until the SysUi chooses to cancel it.
+ */
+class StatefulControlSubscriber(
+ private val controller: ControlsController,
+ private val provider: ControlsProviderLifecycleManager,
+ private val bgExecutor: DelayableExecutor
+) : IControlsSubscriber.Stub() {
+ private var subscriptionOpen = false
+ private var subscription: IControlsSubscription? = null
+
+ companion object {
+ private const val TAG = "StatefulControlSubscriber"
+ }
+
+ private fun run(token: IBinder, f: () -> Unit) {
+ if (provider.token == token) {
+ bgExecutor.execute { f() }
+ }
+ }
+
+ override fun onSubscribe(token: IBinder, subs: IControlsSubscription) {
+ run(token) {
+ subscriptionOpen = true
+ subscription = subs
+ provider.startSubscription(subs)
+ }
+ }
+
+ override fun onNext(token: IBinder, control: Control) {
+ run(token) {
+ if (!subscriptionOpen) {
+ Log.w(TAG, "Refresh outside of window for token:$token")
+ } else {
+ controller.refreshStatus(provider.componentName, control)
+ }
+ }
+ }
+ override fun onError(token: IBinder, error: String) {
+ run(token) {
+ if (subscriptionOpen) {
+ subscriptionOpen = false
+ Log.e(TAG, "onError receive from '${provider.componentName}': $error")
+ }
+ }
+ }
+
+ override fun onComplete(token: IBinder) {
+ run(token) {
+ if (subscriptionOpen) {
+ subscriptionOpen = false
+ Log.i(TAG, "onComplete receive from '${provider.componentName}'")
+ }
+ }
+ }
+
+ fun cancel() {
+ if (!subscriptionOpen) return
+ bgExecutor.execute {
+ if (subscriptionOpen) {
+ subscriptionOpen = false
+ subscription?.let {
+ provider.cancelSubscription(it)
+ }
+ subscription = null
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt b/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt
index 859311e..946a236 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt
@@ -26,6 +26,7 @@
import com.android.systemui.controls.management.ControlsListingController
import com.android.systemui.controls.management.ControlsListingControllerImpl
import com.android.systemui.controls.management.ControlsProviderSelectorActivity
+import com.android.systemui.controls.management.ControlsRequestDialog
import com.android.systemui.controls.ui.ControlsUiController
import com.android.systemui.controls.ui.ControlsUiControllerImpl
import dagger.Binds
@@ -69,4 +70,11 @@
abstract fun provideControlsFavoritingActivity(
activity: ControlsFavoritingActivity
): Activity
+
+ @Binds
+ @IntoMap
+ @ClassKey(ControlsRequestDialog::class)
+ abstract fun provideControlsRequestDialog(
+ activity: ControlsRequestDialog
+ ): Activity
}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/AllModel.kt b/packages/SystemUI/src/com/android/systemui/controls/management/AllModel.kt
index c053517..01f9069 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/management/AllModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/AllModel.kt
@@ -22,14 +22,20 @@
import com.android.systemui.controls.controller.ControlInfo
/**
- * This model is used to show all controls separated by zones.
+ * This model is used to show controls separated by zones.
*
* The model will sort the controls and zones in the following manner:
* * The zones will be sorted in a first seen basis
* * The controls in each zone will be sorted in a first seen basis.
*
- * @property controls List of all controls as returned by loading
- * @property initialFavoriteIds sorted ids of favorite controls
+ * The controls passed should belong to the same structure, as an instance of this model will be
+ * created for each structure.
+ *
+ * The list of favorite ids can contain ids for controls not passed to this model. Those will be
+ * filtered out.
+ *
+ * @property controls List of controls as returned by loading
+ * @property initialFavoriteIds sorted ids of favorite controls.
* @property noZoneString text to use as header for all controls that have blank or `null` zone.
*/
class AllModel(
@@ -50,7 +56,10 @@
}
}
- private val favoriteIds = initialFavoriteIds.toMutableList()
+ private val favoriteIds = run {
+ val ids = controls.mapTo(HashSet()) { it.control.controlId }
+ initialFavoriteIds.filter { it in ids }.toMutableList()
+ }
override val elements: List<ElementWrapper> = createWrappers(controls)
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlAdapter.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlAdapter.kt
index e87cf74..563c2f6 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/management/ControlAdapter.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlAdapter.kt
@@ -16,8 +16,8 @@
package com.android.systemui.controls.management
+import android.content.ComponentName
import android.graphics.Rect
-import android.graphics.drawable.Icon
import android.service.controls.DeviceTypes
import android.view.LayoutInflater
import android.view.View
@@ -42,7 +42,7 @@
* @param onlyFavorites set to true to only display favorites instead of all controls
*/
class ControlAdapter(
- private val layoutInflater: LayoutInflater
+ private val elevation: Float
) : RecyclerView.Adapter<Holder>() {
companion object {
@@ -59,6 +59,7 @@
private var model: ControlsModel? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
+ val layoutInflater = LayoutInflater.from(parent.context)
return when (viewType) {
TYPE_CONTROL -> {
ControlHolder(
@@ -66,7 +67,7 @@
layoutParams.apply {
width = ViewGroup.LayoutParams.MATCH_PARENT
}
- elevation = 15f
+ elevation = this@ControlAdapter.elevation
}
) { id, favorite ->
model?.changeFavoriteStatus(id, favorite)
@@ -146,7 +147,7 @@
override fun bindData(wrapper: ElementWrapper) {
wrapper as ControlWrapper
val data = wrapper.controlStatus
- val renderInfo = getRenderInfo(data.control.deviceType)
+ val renderInfo = getRenderInfo(data.component, data.control.deviceType)
title.text = data.control.title
subtitle.text = data.control.subtitle
favorite.isChecked = data.favorite
@@ -159,16 +160,17 @@
}
private fun getRenderInfo(
+ component: ComponentName,
@DeviceTypes.DeviceType deviceType: Int
): RenderInfo {
- return RenderInfo.lookup(deviceType, true)
+ return RenderInfo.lookup(itemView.context, component, deviceType, true)
}
private fun applyRenderInfo(ri: RenderInfo) {
val context = itemView.context
val fg = context.getResources().getColorStateList(ri.foreground, context.getTheme())
- icon.setImageIcon(Icon.createWithResource(context, ri.iconResourceId))
+ icon.setImageDrawable(ri.icon)
icon.setImageTintList(fg)
}
}
@@ -190,4 +192,4 @@
right = sideMargins
}
}
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt
index 08a1a500..f2303e6 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsFavoritingActivity.kt
@@ -19,20 +19,29 @@
import android.app.Activity
import android.content.ComponentName
import android.content.Intent
+import android.content.res.Configuration
+import android.graphics.drawable.Drawable
import android.os.Bundle
-import android.view.LayoutInflater
+import android.text.TextUtils
+import android.view.Gravity
import android.view.View
+import android.view.ViewGroup
import android.view.ViewStub
import android.widget.Button
+import android.widget.FrameLayout
+import android.widget.ImageView
import android.widget.TextView
-import androidx.recyclerview.widget.GridLayoutManager
-import androidx.recyclerview.widget.RecyclerView
+import androidx.viewpager2.widget.ViewPager2
+import com.android.systemui.Prefs
import com.android.systemui.R
import com.android.systemui.broadcast.BroadcastDispatcher
-import com.android.systemui.controls.controller.StructureInfo
+import com.android.systemui.controls.ControlsServiceInfo
+import com.android.systemui.controls.TooltipManager
import com.android.systemui.controls.controller.ControlsControllerImpl
+import com.android.systemui.controls.controller.StructureInfo
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.settings.CurrentUserTracker
+import java.text.Collator
import java.util.concurrent.Executor
import java.util.function.Consumer
import javax.inject.Inject
@@ -40,20 +49,31 @@
class ControlsFavoritingActivity @Inject constructor(
@Main private val executor: Executor,
private val controller: ControlsControllerImpl,
+ private val listingController: ControlsListingController,
broadcastDispatcher: BroadcastDispatcher
) : Activity() {
companion object {
private const val TAG = "ControlsFavoritingActivity"
const val EXTRA_APP = "extra_app_label"
+ private const val TOOLTIP_PREFS_KEY = Prefs.Key.CONTROLS_STRUCTURE_SWIPE_TOOLTIP_COUNT
+ private const val TOOLTIP_MAX_SHOWN = 2
}
- private lateinit var recyclerViewAll: RecyclerView
- private lateinit var adapterAll: ControlAdapter
- private lateinit var statusText: TextView
- private var model: ControlsModel? = null
private var component: ComponentName? = null
- private var structureName: CharSequence = ""
+ private var appName: CharSequence? = null
+
+ private lateinit var structurePager: ViewPager2
+ private lateinit var statusText: TextView
+ private lateinit var titleView: TextView
+ private lateinit var iconView: ImageView
+ private lateinit var iconFrame: View
+ private lateinit var pageIndicator: ManagementPageIndicator
+ private var mTooltipManager: TooltipManager? = null
+ private lateinit var doneButton: View
+ private var listOfStructures = emptyList<StructureContainer>()
+
+ private lateinit var comparator: Comparator<StructureContainer>
private val currentUserTracker = object : CurrentUserTracker(broadcastDispatcher) {
private val startingUser = controller.currentUserId
@@ -66,29 +86,164 @@
}
}
+ private val listingCallback = object : ControlsListingController.ControlsListingCallback {
+ private var icon: Drawable? = null
+
+ override fun onServicesUpdated(serviceInfos: List<ControlsServiceInfo>) {
+ val newIcon = serviceInfos.firstOrNull { it.componentName == component }?.loadIcon()
+ if (icon == newIcon) return
+ icon = newIcon
+ executor.execute {
+ if (icon != null) {
+ iconView.setImageDrawable(icon)
+ }
+ iconFrame.visibility = if (icon != null) View.VISIBLE else View.GONE
+ }
+ }
+ }
+
override fun onBackPressed() {
finish()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ val collator = Collator.getInstance(resources.configuration.locales[0])
+ comparator = compareBy(collator) { it.structureName }
+ appName = intent.getCharSequenceExtra(EXTRA_APP)
+ component = intent.getParcelableExtra<ComponentName>(Intent.EXTRA_COMPONENT_NAME)
+
+ bindViews()
+
+ setUpPager()
+
+ loadControls()
+
+ listingController.addCallback(listingCallback)
+
+ currentUserTracker.startTracking()
+ }
+
+ private fun loadControls() {
+ component?.let {
+ statusText.text = resources.getText(com.android.internal.R.string.loading)
+ val emptyZoneString = resources.getText(
+ R.string.controls_favorite_other_zone_header)
+ controller.loadForComponent(it, Consumer { data ->
+ val allControls = data.allControls
+ val favoriteKeys = data.favoritesIds
+ val error = data.errorOnLoad
+ val controlsByStructure = allControls.groupBy { it.control.structure ?: "" }
+ listOfStructures = controlsByStructure.map {
+ StructureContainer(it.key, AllModel(it.value, favoriteKeys, emptyZoneString))
+ }.sortedWith(comparator)
+ executor.execute {
+ doneButton.isEnabled = true
+ structurePager.adapter = StructureAdapter(listOfStructures)
+ if (error) {
+ statusText.text = resources.getText(R.string.controls_favorite_load_error)
+ } else {
+ statusText.visibility = View.GONE
+ }
+ pageIndicator.setNumPages(listOfStructures.size)
+ pageIndicator.setLocation(0f)
+ pageIndicator.visibility =
+ if (listOfStructures.size > 1) View.VISIBLE else View.GONE
+ }
+ })
+ }
+ }
+
+ private fun setUpPager() {
+ structurePager.apply {
+ adapter = StructureAdapter(emptyList())
+ registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
+ override fun onPageSelected(position: Int) {
+ super.onPageSelected(position)
+ val name = listOfStructures[position].structureName
+ titleView.text = if (!TextUtils.isEmpty(name)) name else appName
+ }
+
+ override fun onPageScrolled(
+ position: Int,
+ positionOffset: Float,
+ positionOffsetPixels: Int
+ ) {
+ super.onPageScrolled(position, positionOffset, positionOffsetPixels)
+ pageIndicator.setLocation(position + positionOffset)
+ }
+ })
+ }
+ }
+
+ private fun bindViews() {
setContentView(R.layout.controls_management)
requireViewById<ViewStub>(R.id.stub).apply {
layoutResource = R.layout.controls_management_favorites
inflate()
}
- val app = intent.getCharSequenceExtra(EXTRA_APP)
- component = intent.getParcelableExtra<ComponentName>(Intent.EXTRA_COMPONENT_NAME)
statusText = requireViewById(R.id.status_message)
+ if (shouldShowTooltip()) {
+ mTooltipManager = TooltipManager(statusText.context,
+ TOOLTIP_PREFS_KEY, TOOLTIP_MAX_SHOWN)
+ addContentView(
+ mTooltipManager?.layout,
+ FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ Gravity.TOP or Gravity.LEFT
+ )
+ )
+ }
+ pageIndicator = requireViewById<ManagementPageIndicator>(
+ R.id.structure_page_indicator).apply {
+ addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
+ override fun onLayoutChange(
+ v: View,
+ left: Int,
+ top: Int,
+ right: Int,
+ bottom: Int,
+ oldLeft: Int,
+ oldTop: Int,
+ oldRight: Int,
+ oldBottom: Int
+ ) {
+ if (v.visibility == View.VISIBLE && mTooltipManager != null) {
+ val p = IntArray(2)
+ v.getLocationOnScreen(p)
+ val x = p[0] + (right - left) / 2
+ val y = p[1] + bottom - top
+ mTooltipManager?.show(R.string.controls_structure_tooltip, x, y)
+ }
+ }
+ })
+ visibilityListener = {
+ if (it != View.VISIBLE) {
+ mTooltipManager?.hide(true)
+ }
+ }
+ }
- setUpRecyclerView()
-
- requireViewById<TextView>(R.id.title).text = app?.let { it }
- ?: resources.getText(R.string.controls_favorite_default_title)
+ titleView = requireViewById<TextView>(R.id.title).apply {
+ text = appName ?: resources.getText(R.string.controls_favorite_default_title)
+ }
requireViewById<TextView>(R.id.subtitle).text =
resources.getText(R.string.controls_favorite_subtitle)
+ iconView = requireViewById(com.android.internal.R.id.icon)
+ iconFrame = requireViewById(R.id.icon_frame)
+ structurePager = requireViewById<ViewPager2>(R.id.structure_pager)
+ structurePager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
+ override fun onPageSelected(position: Int) {
+ super.onPageSelected(position)
+ mTooltipManager?.hide(true)
+ }
+ })
+ bindButtons()
+ }
+ private fun bindButtons() {
requireViewById<Button>(R.id.other_apps).apply {
visibility = View.VISIBLE
setOnClickListener {
@@ -96,65 +251,41 @@
}
}
- requireViewById<Button>(R.id.done).setOnClickListener {
- if (component == null) return@setOnClickListener
- val favoritesForStorage = model?.favorites?.map {
- it.build()
- }
- if (favoritesForStorage != null) {
- controller.replaceFavoritesForStructure(StructureInfo(component!!, structureName,
- favoritesForStorage))
+ doneButton = requireViewById<Button>(R.id.done).apply {
+ isEnabled = false
+ setOnClickListener {
+ if (component == null) return@setOnClickListener
+ listOfStructures.forEach {
+ val favoritesForStorage = it.model.favorites.map { it.build() }
+ controller.replaceFavoritesForStructure(
+ StructureInfo(component!!, it.structureName, favoritesForStorage)
+ )
+ }
finishAffinity()
}
}
-
- component?.let {
- statusText.text = resources.getText(com.android.internal.R.string.loading)
- controller.loadForComponent(it, Consumer { data ->
- val allControls = data.allControls
- val favoriteKeys = data.favoritesIds
- val error = data.errorOnLoad
- val structures = allControls.fold(hashSetOf<CharSequence>()) {
- s, c ->
- s.add(c.control.structure ?: "")
- s
- }
- // TODO add multi structure switching support
- executor.execute {
- val emptyZoneString = resources.getText(
- R.string.controls_favorite_other_zone_header)
- val model = AllModel(allControls, favoriteKeys, emptyZoneString)
- adapterAll.changeModel(model)
- this.model = model
- if (error) {
- statusText.text = resources.getText(R.string.controls_favorite_load_error)
- } else {
- statusText.visibility = View.GONE
- }
- }
- })
- }
-
- currentUserTracker.startTracking()
}
- private fun setUpRecyclerView() {
- val margin = resources.getDimensionPixelSize(R.dimen.controls_card_margin)
- val itemDecorator = MarginItemDecorator(margin, margin)
- val layoutInflater = LayoutInflater.from(applicationContext)
+ override fun onPause() {
+ super.onPause()
+ mTooltipManager?.hide(false)
+ }
- adapterAll = ControlAdapter(layoutInflater)
- recyclerViewAll = requireViewById<RecyclerView>(R.id.listAll).apply {
- adapter = adapterAll
- layoutManager = GridLayoutManager(applicationContext, 2).apply {
- spanSizeLookup = adapterAll.spanSizeLookup
- }
- addItemDecoration(itemDecorator)
- }
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ mTooltipManager?.hide(false)
}
override fun onDestroy() {
currentUserTracker.stopTracking()
+ listingController.removeCallback(listingCallback)
+ controller.cancelLoad()
super.onDestroy()
}
+
+ private fun shouldShowTooltip(): Boolean {
+ return Prefs.getInt(applicationContext, TOOLTIP_PREFS_KEY, 0) < TOOLTIP_MAX_SHOWN
+ }
}
+
+data class StructureContainer(val structureName: CharSequence, val model: ControlsModel)
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt
index 9b108cf..94487e5 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt
@@ -88,6 +88,8 @@
init {
serviceListing.addCallback(serviceListingCallback)
+ serviceListing.setListening(true)
+ serviceListing.reload()
}
override fun changeUser(newUser: UserHandle) {
@@ -95,11 +97,12 @@
callbacks.clear()
availableServices = emptyList()
serviceListing.setListening(false)
- serviceListing.removeCallback(serviceListingCallback)
currentUserId = newUser.identifier
val contextForUser = context.createContextAsUser(newUser, 0)
serviceListing = serviceListingBuilder(contextForUser)
serviceListing.addCallback(serviceListingCallback)
+ serviceListing.setListening(true)
+ serviceListing.reload()
}
}
@@ -118,12 +121,7 @@
backgroundExecutor.execute {
Log.d(TAG, "Subscribing callback")
callbacks.add(listener)
- if (callbacks.size == 1) {
- serviceListing.setListening(true)
- serviceListing.reload()
- } else {
- listener.onServicesUpdated(getCurrentServices())
- }
+ listener.onServicesUpdated(getCurrentServices())
}
}
@@ -136,9 +134,6 @@
backgroundExecutor.execute {
Log.d(TAG, "Unsubscribing callback")
callbacks.remove(listener)
- if (callbacks.size == 0) {
- serviceListing.setListening(false)
- }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsRequestDialog.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsRequestDialog.kt
new file mode 100644
index 0000000..a7fc2ac8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsRequestDialog.kt
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2020 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.controls.management
+
+import android.app.AlertDialog
+import android.app.Dialog
+import android.content.ComponentName
+import android.content.DialogInterface
+import android.content.Intent
+import android.os.Bundle
+import android.os.UserHandle
+import android.service.controls.Control
+import android.service.controls.ControlsProviderService
+import android.util.Log
+import android.view.LayoutInflater
+import android.view.View
+import android.widget.ImageView
+import android.widget.TextView
+import com.android.systemui.R
+import com.android.systemui.broadcast.BroadcastDispatcher
+import com.android.systemui.controls.ControlsServiceInfo
+import com.android.systemui.controls.controller.ControlInfo
+import com.android.systemui.controls.controller.ControlsController
+import com.android.systemui.controls.ui.RenderInfo
+import com.android.systemui.settings.CurrentUserTracker
+import com.android.systemui.statusbar.phone.SystemUIDialog
+import com.android.systemui.util.LifecycleActivity
+import javax.inject.Inject
+
+class ControlsRequestDialog @Inject constructor(
+ private val controller: ControlsController,
+ private val broadcastDispatcher: BroadcastDispatcher,
+ private val controlsListingController: ControlsListingController
+) : LifecycleActivity(), DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
+
+ companion object {
+ private const val TAG = "ControlsRequestDialog"
+ }
+
+ private lateinit var component: ComponentName
+ private lateinit var control: Control
+ private var dialog: Dialog? = null
+ private val callback = object : ControlsListingController.ControlsListingCallback {
+ override fun onServicesUpdated(candidates: List<ControlsServiceInfo>) {}
+ }
+
+ private val currentUserTracker = object : CurrentUserTracker(broadcastDispatcher) {
+ private val startingUser = controller.currentUserId
+
+ override fun onUserSwitched(newUserId: Int) {
+ if (newUserId != startingUser) {
+ stopTracking()
+ finish()
+ }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (!controller.available) {
+ Log.w(TAG, "Quick Controls not available for this user ")
+ finish()
+ }
+ currentUserTracker.startTracking()
+ controlsListingController.addCallback(callback)
+
+ val requestUser = intent.getIntExtra(Intent.EXTRA_USER_ID, UserHandle.USER_NULL)
+ val currentUser = controller.currentUserId
+
+ if (requestUser != currentUser) {
+ Log.w(TAG, "Current user ($currentUser) different from request user ($requestUser)")
+ finish()
+ }
+
+ component = intent.getParcelableExtra(Intent.EXTRA_COMPONENT_NAME) ?: run {
+ Log.e(TAG, "Request did not contain componentName")
+ finish()
+ return
+ }
+
+ control = intent.getParcelableExtra(ControlsProviderService.EXTRA_CONTROL) ?: run {
+ Log.e(TAG, "Request did not contain control")
+ finish()
+ return
+ }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ val label = verifyComponentAndGetLabel()
+ if (label == null) {
+ Log.e(TAG, "The component specified (${component.flattenToString()} " +
+ "is not a valid ControlsProviderService")
+ finish()
+ return
+ }
+
+ if (isCurrentFavorite()) {
+ Log.w(TAG, "The control ${control.title} is already a favorite")
+ finish()
+ }
+
+ dialog = createDialog(label)
+
+ dialog?.show()
+ }
+
+ override fun onDestroy() {
+ dialog?.dismiss()
+ currentUserTracker.stopTracking()
+ controlsListingController.removeCallback(callback)
+ super.onDestroy()
+ }
+
+ private fun verifyComponentAndGetLabel(): CharSequence? {
+ return controlsListingController.getAppLabel(component)
+ }
+
+ private fun isCurrentFavorite(): Boolean {
+ val favorites = controller.getFavoritesForComponent(component)
+ return favorites.any { it.controls.any { it.controlId == control.controlId } }
+ }
+
+ fun createDialog(label: CharSequence): Dialog {
+ val renderInfo = RenderInfo.lookup(this, component, control.deviceType, true)
+ val frame = LayoutInflater.from(this).inflate(R.layout.controls_dialog, null).apply {
+ requireViewById<ImageView>(R.id.icon).apply {
+ setImageDrawable(renderInfo.icon)
+ setImageTintList(
+ context.resources.getColorStateList(renderInfo.foreground, context.theme))
+ }
+ requireViewById<TextView>(R.id.title).text = control.title
+ requireViewById<TextView>(R.id.subtitle).text = control.subtitle
+ requireViewById<View>(R.id.control).elevation =
+ resources.getFloat(R.dimen.control_card_elevation)
+ }
+
+ val dialog = AlertDialog.Builder(this)
+ .setTitle(getString(R.string.controls_dialog_title))
+ .setMessage(getString(R.string.controls_dialog_message, label))
+ .setPositiveButton(R.string.controls_dialog_ok, this)
+ .setNegativeButton(android.R.string.cancel, this)
+ .setOnCancelListener(this)
+ .setView(frame)
+ .create()
+
+ SystemUIDialog.registerDismissListener(dialog)
+ dialog.setCanceledOnTouchOutside(true)
+ return dialog
+ }
+
+ override fun onCancel(dialog: DialogInterface?) {
+ finish()
+ }
+
+ override fun onClick(dialog: DialogInterface?, which: Int) {
+ if (which == Dialog.BUTTON_POSITIVE) {
+ controller.addFavorite(componentName, control.structure ?: "",
+ ControlInfo(control.controlId, control.title, control.deviceType))
+ }
+ finish()
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsRequestReceiver.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsRequestReceiver.kt
new file mode 100644
index 0000000..5c30b5a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsRequestReceiver.kt
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2020 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.controls.management
+
+import android.app.ActivityManager
+import android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
+import android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.UserHandle
+import android.service.controls.Control
+import android.service.controls.ControlsProviderService
+import android.util.Log
+
+/**
+ * Proxy to launch in user 0
+ */
+class ControlsRequestReceiver : BroadcastReceiver() {
+
+ companion object {
+ private const val TAG = "ControlsRequestReceiver"
+
+ fun isPackageInForeground(context: Context, packageName: String): Boolean {
+ val uid = try {
+ context.packageManager.getPackageUid(packageName, 0)
+ } catch (_: PackageManager.NameNotFoundException) {
+ Log.w(TAG, "Package $packageName not found")
+ return false
+ }
+
+ val am = context.getSystemService(ActivityManager::class.java)
+ if ((am?.getUidImportance(uid) ?: IMPORTANCE_GONE) != IMPORTANCE_FOREGROUND) {
+ Log.w(TAG, "Uid $uid not in foreground")
+ return false
+ }
+ return true
+ }
+ }
+
+ override fun onReceive(context: Context, intent: Intent) {
+
+ val packageName = intent.getParcelableExtra<ComponentName>(Intent.EXTRA_COMPONENT_NAME)
+ ?.packageName
+
+ if (packageName == null || !isPackageInForeground(context, packageName)) {
+ return
+ }
+
+ val activityIntent = Intent(context, ControlsRequestDialog::class.java).apply {
+ Intent.EXTRA_COMPONENT_NAME.let {
+ putExtra(it, intent.getParcelableExtra<ComponentName>(it))
+ }
+ ControlsProviderService.EXTRA_CONTROL.let {
+ putExtra(it, intent.getParcelableExtra<Control>(it))
+ }
+ }
+ activityIntent.putExtra(Intent.EXTRA_USER_ID, context.userId)
+
+ context.startActivityAsUser(activityIntent, UserHandle.SYSTEM)
+ }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ManagementPageIndicator.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ManagementPageIndicator.kt
new file mode 100644
index 0000000..72b1098
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/ManagementPageIndicator.kt
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2020 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.controls.management
+
+import android.content.Context
+import android.util.AttributeSet
+import android.view.View
+import com.android.systemui.qs.PageIndicator
+
+/**
+ * Page indicator for management screens.
+ *
+ * Adds RTL support to [PageIndicator]. To be used with [ViewPager2].
+ */
+class ManagementPageIndicator(
+ context: Context,
+ attrs: AttributeSet
+) : PageIndicator(context, attrs) {
+
+ override fun setLocation(location: Float) {
+ // Location doesn't know about RTL
+ if (layoutDirection == View.LAYOUT_DIRECTION_RTL) {
+ val numPages = childCount
+ super.setLocation(numPages - 1 - location)
+ } else {
+ super.setLocation(location)
+ }
+ }
+
+ var visibilityListener: (Int) -> Unit = {}
+
+ override fun onVisibilityChanged(changedView: View, visibility: Int) {
+ super.onVisibilityChanged(changedView, visibility)
+ if (changedView == this) {
+ visibilityListener(visibility)
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/StructureAdapter.kt b/packages/SystemUI/src/com/android/systemui/controls/management/StructureAdapter.kt
new file mode 100644
index 0000000..cb67454
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/management/StructureAdapter.kt
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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.controls.management
+
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.recyclerview.widget.GridLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.android.systemui.R
+
+class StructureAdapter(
+ private val models: List<StructureContainer>
+) : RecyclerView.Adapter<StructureAdapter.StructureHolder>() {
+
+ override fun onCreateViewHolder(parent: ViewGroup, p1: Int): StructureHolder {
+ val layoutInflater = LayoutInflater.from(parent.context)
+ return StructureHolder(
+ layoutInflater.inflate(R.layout.controls_structure_page, parent, false)
+ )
+ }
+
+ override fun getItemCount() = models.size
+
+ override fun onBindViewHolder(holder: StructureHolder, index: Int) {
+ holder.bind(models[index].model)
+ }
+
+ class StructureHolder(view: View) : RecyclerView.ViewHolder(view) {
+
+ private val recyclerView: RecyclerView
+ private val controlAdapter: ControlAdapter
+
+ init {
+ recyclerView = itemView.requireViewById<RecyclerView>(R.id.listAll)
+ val elevation = itemView.context.resources.getFloat(R.dimen.control_card_elevation)
+ controlAdapter = ControlAdapter(elevation)
+ setUpRecyclerView()
+ }
+
+ fun bind(model: ControlsModel) {
+ controlAdapter.changeModel(model)
+ }
+
+ private fun setUpRecyclerView() {
+ val margin = itemView.context.resources
+ .getDimensionPixelSize(R.dimen.controls_card_margin)
+ val itemDecorator = MarginItemDecorator(margin, margin)
+
+ recyclerView.apply {
+ this.adapter = controlAdapter
+ layoutManager = GridLayoutManager(recyclerView.context, 2).apply {
+ spanSizeLookup = controlAdapter.spanSizeLookup
+ }
+ addItemDecoration(itemDecorator)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt
new file mode 100644
index 0000000..2494fd1
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ChallengeDialogs.kt
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2020 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.controls.ui
+
+import android.app.AlertDialog
+import android.app.Dialog
+import android.content.DialogInterface
+import android.service.controls.actions.BooleanAction
+import android.service.controls.actions.CommandAction
+import android.service.controls.actions.ControlAction
+import android.service.controls.actions.FloatAction
+import android.service.controls.actions.ModeAction
+import android.text.InputType
+import android.util.Log
+import android.view.WindowManager
+import android.widget.CheckBox
+import android.widget.EditText
+
+import com.android.systemui.R
+
+/**
+ * Creates all dialogs for challengeValues that can occur from a call to
+ * {@link ControlsProviderService#performControlAction}. The types of challenge
+ * responses are listed in {@link ControlAction.ResponseResult}.
+ */
+object ChallengeDialogs {
+
+ fun createPinDialog(cvh: ControlViewHolder): Dialog? {
+ val lastAction = cvh.lastAction
+ if (lastAction == null) {
+ Log.e(ControlsUiController.TAG,
+ "PIN Dialog attempted but no last action is set. Will not show")
+ return null
+ }
+ val builder = AlertDialog.Builder(
+ cvh.context,
+ android.R.style.Theme_DeviceDefault_Dialog_Alert
+ ).apply {
+ setTitle(R.string.controls_pin_verify)
+ setView(R.layout.controls_dialog_pin)
+ setPositiveButton(
+ android.R.string.ok,
+ DialogInterface.OnClickListener { dialog, _ ->
+ if (dialog is Dialog) {
+ dialog.requireViewById<EditText>(R.id.controls_pin_input)
+ val pin = dialog.requireViewById<EditText>(R.id.controls_pin_input)
+ .getText().toString()
+ cvh.action(addChallengeValue(lastAction, pin))
+ dialog.dismiss()
+ }
+ })
+ setNegativeButton(
+ android.R.string.cancel,
+ DialogInterface.OnClickListener { dialog, _ -> dialog.cancel() }
+ )
+ }
+ return builder.create().apply {
+ getWindow().apply {
+ setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY)
+ setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
+ }
+ setOnShowListener(DialogInterface.OnShowListener { _ ->
+ val editText = requireViewById<EditText>(R.id.controls_pin_input)
+ requireViewById<CheckBox>(R.id.controls_pin_use_alpha).setOnClickListener { v ->
+ if ((v as CheckBox).isChecked) {
+ editText.setInputType(
+ InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
+ } else {
+ editText.setInputType(
+ InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD)
+ }
+ }
+ editText.requestFocus()
+ })
+ }
+ }
+
+ private fun addChallengeValue(action: ControlAction, challengeValue: String): ControlAction {
+ val id = action.getTemplateId()
+ return when (action) {
+ is BooleanAction -> BooleanAction(id, action.getNewState(), challengeValue)
+ is FloatAction -> FloatAction(id, action.getNewValue(), challengeValue)
+ is CommandAction -> CommandAction(id, challengeValue)
+ is ModeAction -> ModeAction(id, action.getNewMode(), challengeValue)
+ else -> throw IllegalStateException("'action' is not a known type: $action")
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt
index eb84a8b..680d006 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinator.kt
@@ -20,6 +20,7 @@
import android.content.Intent
import android.provider.Settings
import android.service.controls.actions.BooleanAction
+import android.service.controls.actions.CommandAction
import android.util.Log
import android.view.HapticFeedbackConstants
@@ -36,6 +37,10 @@
cvh.clipLayer.setLevel(nextLevel)
}
+ fun touch(cvh: ControlViewHolder, templateId: String) {
+ cvh.action(CommandAction(templateId))
+ }
+
fun longPress(cvh: ControlViewHolder) {
// Long press snould only be called when there is valid control state, otherwise ignore
cvh.cws.control?.let {
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
index f2c8490..b439206 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlViewHolder.kt
@@ -17,15 +17,14 @@
package com.android.systemui.controls.ui
import android.content.Context
-import android.graphics.BlendMode
import android.graphics.drawable.ClipDrawable
-import android.graphics.drawable.Icon
+import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.service.controls.Control
import android.service.controls.actions.ControlAction
import android.service.controls.templates.ControlTemplate
+import android.service.controls.templates.StatelessTemplate
import android.service.controls.templates.TemperatureControlTemplate
-import android.service.controls.templates.ThumbnailTemplate
import android.service.controls.templates.ToggleRangeTemplate
import android.service.controls.templates.ToggleTemplate
import android.view.View
@@ -40,6 +39,8 @@
import kotlin.reflect.KClass
private const val UPDATE_DELAY_IN_MILLIS = 3000L
+private const val ALPHA_ENABLED = (255.0 * 0.2).toInt()
+private const val ALPHA_DISABLED = 255
class ControlViewHolder(
val layout: ViewGroup,
@@ -57,6 +58,7 @@
lateinit var cws: ControlWithState
var cancelUpdate: Runnable? = null
var behavior: Behavior? = null
+ var lastAction: ControlAction? = null
init {
val ld = layout.getBackground() as LayerDrawable
@@ -69,7 +71,7 @@
cancelUpdate?.run()
- val (status, template) = cws.control?.let {
+ val (controlStatus, template) = cws.control?.let {
title.setText(it.getTitle())
subtitle.setText(it.getSubtitle())
Pair(it.getStatus(), it.getControlTemplate())
@@ -80,32 +82,32 @@
}
cws.control?.let {
+ layout.setClickable(true)
layout.setOnLongClickListener(View.OnLongClickListener() {
ControlActionCoordinator.longPress(this@ControlViewHolder)
true
})
}
- val clazz = findBehavior(status, template)
+ val clazz = findBehavior(controlStatus, template)
if (behavior == null || behavior!!::class != clazz) {
// Behavior changes can signal a change in template from the app or
// first time setup
behavior = clazz.java.newInstance()
behavior?.initialize(this)
+
+ // let behaviors define their own, if necessary, and clear any existing ones
+ layout.setAccessibilityDelegate(null)
}
+
behavior?.bind(cws)
+
+ layout.setContentDescription(
+ "${title.text} ${subtitle.text} ${status.text} ${statusExtra.text}")
}
fun actionResponse(@ControlAction.ResponseResult response: Int) {
- val text = when (response) {
- ControlAction.RESPONSE_OK -> "Success"
- ControlAction.RESPONSE_FAIL -> "Error"
- else -> ""
- }
-
- if (!text.isEmpty()) {
- setTransientStatus(text)
- }
+ // TODO: b/150931809 - handle response codes
}
fun setTransientStatus(tempStatus: String) {
@@ -122,6 +124,7 @@
}
fun action(action: ControlAction) {
+ lastAction = action
controlsController.action(cws.componentName, cws.ci, action)
}
@@ -129,29 +132,39 @@
return when {
status == Control.STATUS_UNKNOWN -> UnknownBehavior::class
template is ToggleTemplate -> ToggleBehavior::class
+ template is StatelessTemplate -> TouchBehavior::class
template is ToggleRangeTemplate -> ToggleRangeBehavior::class
template is TemperatureControlTemplate -> TemperatureControlBehavior::class
- template is ThumbnailTemplate -> StaticBehavior::class
else -> DefaultBehavior::class
}
}
- internal fun applyRenderInfo(ri: RenderInfo) {
+ internal fun applyRenderInfo(enabled: Boolean, offset: Int = 0) {
+ setEnabled(enabled)
+
+ val deviceType = cws.control?.let { it.getDeviceType() } ?: cws.ci.deviceType
+ val ri = RenderInfo.lookup(context, cws.componentName, deviceType, enabled, offset)
+
val fg = context.getResources().getColorStateList(ri.foreground, context.getTheme())
- val bg = context.getResources().getColorStateList(ri.background, context.getTheme())
+ val (bg, alpha) = if (enabled) {
+ Pair(ri.enabledBackground, ALPHA_ENABLED)
+ } else {
+ Pair(R.color.control_default_background, ALPHA_DISABLED)
+ }
+
status.setTextColor(fg)
statusExtra.setTextColor(fg)
- icon.setImageIcon(Icon.createWithResource(context, ri.iconResourceId))
+ icon.setImageDrawable(ri.icon)
icon.setImageTintList(fg)
- clipLayer.getDrawable().apply {
- setTintBlendMode(BlendMode.HUE)
- setTintList(bg)
+ (clipLayer.getDrawable() as GradientDrawable).apply {
+ setColor(context.getResources().getColor(bg, context.getTheme()))
+ setAlpha(alpha)
}
}
- fun setEnabled(enabled: Boolean) {
+ private fun setEnabled(enabled: Boolean) {
status.setEnabled(enabled)
icon.setEnabled(enabled)
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt
index eaf57ff..138cd47 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt
@@ -16,18 +16,15 @@
package com.android.systemui.controls.ui
-import android.accounts.Account
-import android.accounts.AccountManager
+import android.app.Dialog
import android.content.ComponentName
import android.content.Context
import android.content.Intent
-import android.content.ServiceConnection
import android.content.SharedPreferences
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
-import android.os.IBinder
import android.service.controls.Control
-import android.service.controls.TokenProvider
+import android.service.controls.actions.ControlAction
import android.util.Log
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
@@ -49,8 +46,8 @@
import com.android.systemui.controls.management.ControlsProviderSelectorActivity
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.dagger.qualifiers.Main
-import com.android.systemui.R
import com.android.systemui.util.concurrency.DelayableExecutor
+import com.android.systemui.R
import dagger.Lazy
@@ -59,68 +56,6 @@
import javax.inject.Inject
import javax.inject.Singleton
-// TEMP CODE for MOCK
-private const val TOKEN = "https://www.googleapis.com/auth/assistant"
-private const val SCOPE = "oauth2:" + TOKEN
-private var tokenProviderConnection: TokenProviderConnection? = null
-class TokenProviderConnection(
- val cc: ControlsController,
- val context: Context,
- val structure: StructureInfo?
-) : ServiceConnection {
- private var mTokenProvider: TokenProvider? = null
-
- override fun onServiceConnected(cName: ComponentName, binder: IBinder) {
- Thread({
- Log.i(ControlsUiController.TAG, "TokenProviderConnection connected")
- mTokenProvider = TokenProvider.Stub.asInterface(binder)
-
- val mLastAccountName = mTokenProvider?.getAccountName()
-
- if (mLastAccountName == null || mLastAccountName.isEmpty()) {
- Log.e(ControlsUiController.TAG, "NO ACCOUNT IS SET. Open HomeMock app")
- } else {
- mTokenProvider?.setAuthToken(getAuthToken(mLastAccountName))
- structure?.let {
- cc.subscribeToFavorites(it)
- }
- }
- }, "TokenProviderThread").start()
- }
-
- override fun onServiceDisconnected(cName: ComponentName) {
- mTokenProvider = null
- }
-
- fun getAuthToken(accountName: String): String? {
- val am = AccountManager.get(context)
- val accounts = am.getAccountsByType("com.google")
- if (accounts == null || accounts.size == 0) {
- Log.w(ControlsUiController.TAG, "No com.google accounts found")
- return null
- }
-
- var account: Account? = null
- for (a in accounts) {
- if (a.name.equals(accountName)) {
- account = a
- break
- }
- }
-
- if (account == null) {
- account = accounts[0]
- }
-
- try {
- return am.blockingGetAuthToken(account!!, SCOPE, true)
- } catch (e: Throwable) {
- Log.e(ControlsUiController.TAG, "Error getting auth token", e)
- return null
- }
- }
-}
-
private data class ControlKey(val componentName: ComponentName, val controlId: String)
@Singleton
@@ -152,7 +87,7 @@
private lateinit var parent: ViewGroup
private lateinit var lastItems: List<SelectionItem>
private var popup: ListPopupWindow? = null
-
+ private var activeDialog: Dialog? = null
private val addControlsItem: SelectionItem
init {
@@ -213,21 +148,10 @@
ControlKey(selectedStructure.componentName, it.ci.controlId)
}
listingCallback = createCallback(::showControlsView)
+ controlsController.get().subscribeToFavorites(selectedStructure)
}
controlsListingController.get().addCallback(listingCallback)
-
- // Temp code to pass auth
- tokenProviderConnection = TokenProviderConnection(controlsController.get(), context,
- selectedStructure)
-
- val serviceIntent = Intent()
- serviceIntent.setComponent(ComponentName("com.android.systemui.home.mock",
- "com.android.systemui.home.mock.AuthService"))
- if (!context.bindService(serviceIntent, tokenProviderConnection!!,
- Context.BIND_AUTO_CREATE)) {
- controlsController.get().subscribeToFavorites(selectedStructure)
- }
}
private fun showInitialSetupView(items: List<SelectionItem>) {
@@ -264,36 +188,23 @@
parent.removeAllViews()
controlViewsById.clear()
- val inflater = LayoutInflater.from(context)
- inflater.inflate(R.layout.controls_with_favorites, parent, true)
+ createListView()
+ createDropDown(items)
+ }
- val listView = parent.requireViewById(R.id.global_actions_controls_list) as ViewGroup
- var lastRow: ViewGroup = createRow(inflater, listView)
- selectedStructure.controls.forEach {
- if (lastRow.getChildCount() == 2) {
- lastRow = createRow(inflater, listView)
- }
- val item = inflater.inflate(
- R.layout.controls_base_item, lastRow, false) as ViewGroup
- lastRow.addView(item)
- val cvh = ControlViewHolder(item, controlsController.get(), uiExecutor, bgExecutor)
- val key = ControlKey(selectedStructure.componentName, it.controlId)
- cvh.bindData(controlsById.getValue(key))
- controlViewsById.put(key, cvh)
- }
-
- // add spacer if necessary to keep control size consistent
- if ((selectedStructure.controls.size % 2) == 1) {
- lastRow.addView(Space(context), LinearLayout.LayoutParams(0, 0, 1f))
+ private fun createDropDown(items: List<SelectionItem>) {
+ items.forEach {
+ RenderInfo.registerComponentIcon(it.componentName, it.icon)
}
val itemsByComponent = items.associateBy { it.componentName }
- var adapter = ItemAdapter(context, R.layout.controls_spinner_item).apply {
- val listItems = allStructures.mapNotNull {
- itemsByComponent.get(it.componentName)?.copy(structure = it.structure)
- }
+ val itemsWithStructure = allStructures.mapNotNull {
+ itemsByComponent.get(it.componentName)?.copy(structure = it.structure)
+ }
+ val selectionItem = findSelectionItem(selectedStructure, itemsWithStructure) ?: items[0]
- addAll(listItems + addControlsItem)
+ var adapter = ItemAdapter(context, R.layout.controls_spinner_item).apply {
+ addAll(itemsWithStructure + addControlsItem)
}
/*
@@ -301,16 +212,15 @@
* for this dialog. Use a textView with the ListPopupWindow to achieve
* a similar effect
*/
- val item = adapter.findSelectionItem(selectedStructure) ?: adapter.getItem(0)
parent.requireViewById<TextView>(R.id.app_or_structure_spinner).apply {
- setText(item.getTitle())
+ setText(selectionItem.getTitle())
// override the default color on the dropdown drawable
(getBackground() as LayerDrawable).getDrawable(1)
.setTint(context.resources.getColor(R.color.control_spinner_dropdown, null))
}
parent.requireViewById<ImageView>(R.id.app_icon).apply {
- setContentDescription(item.getTitle())
- setImageDrawable(item.icon)
+ setContentDescription(selectionItem.getTitle())
+ setImageDrawable(selectionItem.icon)
}
val anchor = parent.requireViewById<ViewGroup>(R.id.controls_header)
anchor.setOnClickListener(object : View.OnClickListener {
@@ -348,6 +258,36 @@
})
}
+ private fun createListView() {
+ val inflater = LayoutInflater.from(context)
+ inflater.inflate(R.layout.controls_with_favorites, parent, true)
+
+ val listView = parent.requireViewById(R.id.global_actions_controls_list) as ViewGroup
+ var lastRow: ViewGroup = createRow(inflater, listView)
+ selectedStructure.controls.forEach {
+ if (lastRow.getChildCount() == 2) {
+ lastRow = createRow(inflater, listView)
+ }
+ val baseLayout = inflater.inflate(
+ R.layout.controls_base_item, lastRow, false) as ViewGroup
+ lastRow.addView(baseLayout)
+ val cvh = ControlViewHolder(
+ baseLayout,
+ controlsController.get(),
+ uiExecutor,
+ bgExecutor
+ )
+ val key = ControlKey(selectedStructure.componentName, it.controlId)
+ cvh.bindData(controlsById.getValue(key))
+ controlViewsById.put(key, cvh)
+ }
+
+ // add spacer if necessary to keep control size consistent
+ if ((selectedStructure.controls.size % 2) == 1) {
+ lastRow.addView(Space(context), LinearLayout.LayoutParams(0, 0, 1f))
+ }
+ }
+
private fun loadPreference(structures: List<StructureInfo>): StructureInfo {
if (structures.isEmpty()) return EMPTY_STRUCTURE
@@ -388,15 +328,16 @@
override fun hide() {
Log.d(ControlsUiController.TAG, "hide()")
popup?.dismiss()
+ activeDialog?.dismiss()
controlsController.get().unsubscribe()
- context.unbindService(tokenProviderConnection)
- tokenProviderConnection = null
parent.removeAllViews()
controlsById.clear()
controlViewsById.clear()
controlsListingController.get().removeCallback(listingCallback)
+
+ RenderInfo.clearCache()
}
override fun onRefreshState(componentName: ComponentName, controls: List<Control>) {
@@ -418,7 +359,15 @@
override fun onActionResponse(componentName: ComponentName, controlId: String, response: Int) {
val key = ControlKey(componentName, controlId)
uiExecutor.execute {
- controlViewsById.get(key)?.actionResponse(response)
+ controlViewsById.get(key)?.let { cvh ->
+ when (response) {
+ ControlAction.RESPONSE_CHALLENGE_PIN -> {
+ activeDialog = ChallengeDialogs.createPinDialog(cvh)
+ activeDialog?.show()
+ }
+ else -> cvh.actionResponse(response)
+ }
+ }
}
}
@@ -427,6 +376,11 @@
listView.addView(row)
return row
}
+
+ private fun findSelectionItem(si: StructureInfo, items: List<SelectionItem>): SelectionItem? =
+ items.firstOrNull {
+ it.componentName == si.componentName && it.structure == si.structure
+ }
}
private data class SelectionItem(
@@ -452,22 +406,9 @@
setText(item.getTitle())
}
view.requireViewById<ImageView>(R.id.app_icon).apply {
- setContentDescription(item.getTitle())
+ setContentDescription(item.appName)
setImageDrawable(item.icon)
}
return view
}
-
- fun findSelectionItem(si: StructureInfo): SelectionItem? {
- var i = 0
- while (i < getCount()) {
- val item = getItem(i)
- if (item.componentName == si.componentName &&
- item.structure == si.structure) {
- return item
- }
- i++
- }
- return null
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/DefaultBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/DefaultBehavior.kt
index 1747929..e850a6a 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/DefaultBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/DefaultBehavior.kt
@@ -25,7 +25,6 @@
override fun bind(cws: ControlWithState) {
cvh.status.setText(cws.control?.getStatusText() ?: "")
- cvh.setEnabled(false)
- cvh.applyRenderInfo(RenderInfo.lookup(cws.ci.deviceType, false))
+ cvh.applyRenderInfo(false)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
index da52c6f..27e4649 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/RenderInfo.kt
@@ -16,8 +16,15 @@
package com.android.systemui.controls.ui
+import android.annotation.ColorRes
+import android.annotation.MainThread
+import android.content.ComponentName
+import android.content.Context
+import android.graphics.drawable.Drawable
import android.service.controls.DeviceTypes
import android.service.controls.templates.TemperatureControlTemplate
+import android.util.ArrayMap
+import android.util.SparseArray
import com.android.systemui.R
@@ -31,18 +38,58 @@
}
}
-data class RenderInfo(val iconResourceId: Int, val foreground: Int, val background: Int) {
-
+data class RenderInfo(
+ val icon: Drawable,
+ val foreground: Int,
+ @ColorRes val enabledBackground: Int
+) {
companion object {
- fun lookup(deviceType: Int, enabled: Boolean): RenderInfo {
- val iconState = deviceIconMap.getValue(deviceType)
+ const val APP_ICON_ID = -1
+ private val iconMap = SparseArray<Drawable>()
+ private val appIconMap = ArrayMap<ComponentName, Drawable>()
+
+ @MainThread
+ fun lookup(
+ context: Context,
+ componentName: ComponentName,
+ deviceType: Int,
+ enabled: Boolean,
+ offset: Int = 0
+ ): RenderInfo {
val (fg, bg) = deviceColorMap.getValue(deviceType)
- return RenderInfo(iconState[enabled], fg, bg)
+
+ val iconKey = if (offset > 0) {
+ deviceType * BUCKET_SIZE + offset
+ } else deviceType
+
+ val iconState = deviceIconMap.getValue(iconKey)
+ val resourceId = iconState[enabled]
+ var icon: Drawable? = null
+ if (resourceId == APP_ICON_ID) {
+ icon = appIconMap.get(componentName)
+ if (icon == null) {
+ icon = context.resources
+ .getDrawable(R.drawable.ic_device_unknown_gm2_24px, null)
+ appIconMap.put(componentName, icon)
+ }
+ } else {
+ icon = iconMap.get(resourceId)
+ if (icon == null) {
+ icon = context.resources.getDrawable(resourceId, null)
+ icon.mutate()
+ iconMap.put(resourceId, icon)
+ }
+ }
+ return RenderInfo(icon!!, fg, bg)
}
- fun lookup(deviceType: Int, offset: Int, enabled: Boolean): RenderInfo {
- val key = deviceType * BUCKET_SIZE + offset
- return lookup(key, enabled)
+ fun registerComponentIcon(componentName: ComponentName, icon: Drawable) {
+ appIconMap.put(componentName, icon)
+ }
+
+ fun clearCache() {
+ iconMap.clear()
+ appIconMap.clear()
}
}
}
@@ -52,12 +99,13 @@
private val deviceColorMap = mapOf<Int, Pair<Int, Int>>(
(THERMOSTAT_RANGE + TemperatureControlTemplate.MODE_HEAT) to
- Pair(R.color.thermo_heat_foreground, R.color.thermo_heat_background),
+ Pair(R.color.thermo_heat_foreground, R.color.control_enabled_thermo_heat_background),
(THERMOSTAT_RANGE + TemperatureControlTemplate.MODE_COOL) to
- Pair(R.color.thermo_cool_foreground, R.color.thermo_cool_background),
- DeviceTypes.TYPE_LIGHT to Pair(R.color.light_foreground, R.color.light_background)
+ Pair(R.color.thermo_cool_foreground, R.color.control_enabled_thermo_cool_background),
+ DeviceTypes.TYPE_LIGHT
+ to Pair(R.color.light_foreground, R.color.control_enabled_light_background)
).withDefault {
- Pair(R.color.control_foreground, R.color.control_background)
+ Pair(R.color.control_foreground, R.color.control_enabled_default_background)
}
private val deviceIconMap = mapOf<Int, IconState>(
@@ -116,6 +164,10 @@
DeviceTypes.TYPE_MOP to IconState(
R.drawable.ic_vacuum_gm2_24px,
R.drawable.ic_vacuum_gm2_24px
+ ),
+ DeviceTypes.TYPE_ROUTINE to IconState(
+ RenderInfo.APP_ICON_ID,
+ RenderInfo.APP_ICON_ID
)
).withDefault {
IconState(
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/StaticBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/StaticBehavior.kt
deleted file mode 100644
index c006d6f..0000000
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/StaticBehavior.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2020 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.controls.ui
-
-import android.graphics.drawable.ClipDrawable
-import android.graphics.drawable.LayerDrawable
-import android.service.controls.Control
-import android.service.controls.templates.ThumbnailTemplate
-
-import com.android.systemui.R
-import com.android.systemui.controls.ui.ControlActionCoordinator.MAX_LEVEL
-
-/**
- * Used for controls that cannot be interacted with. Information is presented to the user
- * but no actions can be taken. If using a ThumbnailTemplate, the background image will
- * be changed.
- */
-class StaticBehavior() : Behavior {
- lateinit var control: Control
- lateinit var cvh: ControlViewHolder
-
- override fun initialize(cvh: ControlViewHolder) {
- this.cvh = cvh
- }
-
- override fun bind(cws: ControlWithState) {
- this.control = cws.control!!
-
- cvh.status.setText(control.getStatusText())
-
- val ld = cvh.layout.getBackground() as LayerDrawable
- val clipLayer = ld.findDrawableByLayerId(R.id.clip_layer) as ClipDrawable
-
- clipLayer.setLevel(MAX_LEVEL)
- cvh.setEnabled(true)
- cvh.applyRenderInfo(RenderInfo.lookup(control.getDeviceType(), true))
-
- val template = control.getControlTemplate()
- if (template is ThumbnailTemplate) {
- cvh.bgExecutor.execute {
- // clear the default tinting in favor of only using alpha
- val drawable = template.getThumbnail().loadDrawable(cvh.context)
- drawable.setTintList(null)
- drawable.setAlpha((0.45 * 255).toInt())
- cvh.uiExecutor.execute {
- val radius = cvh.context.getResources()
- .getDimensionPixelSize(R.dimen.control_corner_radius).toFloat()
- clipLayer.setDrawable(CornerDrawable(drawable, radius))
- }
- }
- }
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/TemperatureControlBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/TemperatureControlBehavior.kt
index 239d2e5..15c1dab 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/TemperatureControlBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/TemperatureControlBehavior.kt
@@ -47,10 +47,7 @@
val activeMode = template.getCurrentActiveMode()
val enabled = activeMode != 0 && activeMode != TemperatureControlTemplate.MODE_OFF
- val deviceType = control.getDeviceType()
-
clipLayer.setLevel(if (enabled) MAX_LEVEL else MIN_LEVEL)
- cvh.setEnabled(enabled)
- cvh.applyRenderInfo(RenderInfo.lookup(deviceType, activeMode, enabled))
+ cvh.applyRenderInfo(enabled, activeMode)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleBehavior.kt
index d306d7c..a3368ef 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleBehavior.kt
@@ -34,7 +34,7 @@
override fun initialize(cvh: ControlViewHolder) {
this.cvh = cvh
- cvh.setEnabled(false)
+ cvh.applyRenderInfo(false)
cvh.layout.setOnClickListener(View.OnClickListener() {
ControlActionCoordinator.toggle(cvh, template.getTemplateId(), template.isChecked())
@@ -51,10 +51,7 @@
clipLayer = ld.findDrawableByLayerId(R.id.clip_layer)
val checked = template.isChecked()
- val deviceType = control.getDeviceType()
-
clipLayer.setLevel(if (checked) MAX_LEVEL else MIN_LEVEL)
- cvh.setEnabled(checked)
- cvh.applyRenderInfo(RenderInfo.lookup(deviceType, checked))
+ cvh.applyRenderInfo(checked)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt
index cca56c2..c495c58 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ToggleRangeBehavior.kt
@@ -16,6 +16,7 @@
package com.android.systemui.controls.ui
+import android.os.Bundle
import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
@@ -24,6 +25,9 @@
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
+import android.view.ViewGroup
+import android.view.accessibility.AccessibilityEvent
+import android.view.accessibility.AccessibilityNodeInfo
import android.widget.TextView
import android.service.controls.Control
import android.service.controls.actions.FloatAction
@@ -56,7 +60,7 @@
status = cvh.status
context = status.getContext()
- cvh.setEnabled(false)
+ cvh.applyRenderInfo(false)
val gestureListener = ToggleRangeGestureListener(cvh.layout)
val gestureDetector = GestureDetector(context, gestureListener)
@@ -89,14 +93,76 @@
rangeTemplate = template.getRange()
val checked = template.isChecked()
- val deviceType = control.getDeviceType()
-
val currentRatio = rangeTemplate.getCurrentValue() /
(rangeTemplate.getMaxValue() - rangeTemplate.getMinValue())
updateRange(currentRatio, checked)
- cvh.setEnabled(checked)
- cvh.applyRenderInfo(RenderInfo.lookup(deviceType, checked))
+ cvh.applyRenderInfo(checked)
+
+ /*
+ * This is custom widget behavior, so add a new accessibility delegate to
+ * handle clicks and range events. Present as a seek bar control.
+ */
+ cvh.layout.setAccessibilityDelegate(object : View.AccessibilityDelegate() {
+ override fun onInitializeAccessibilityNodeInfo(
+ host: View,
+ info: AccessibilityNodeInfo
+ ) {
+ super.onInitializeAccessibilityNodeInfo(host, info)
+
+ val min = levelToRangeValue(MIN_LEVEL)
+ val current = levelToRangeValue(clipLayer.getLevel())
+ val max = levelToRangeValue(MAX_LEVEL)
+
+ val step = rangeTemplate.getStepValue().toDouble()
+ val type = if (step == Math.floor(step)) {
+ AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_INT
+ } else {
+ AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_FLOAT
+ }
+
+ val rangeInfo = AccessibilityNodeInfo.RangeInfo.obtain(type, min, max, current)
+ info.setRangeInfo(rangeInfo)
+ info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_PROGRESS)
+ }
+
+ override fun performAccessibilityAction(
+ host: View,
+ action: Int,
+ arguments: Bundle?
+ ): Boolean {
+ val handled = when (action) {
+ AccessibilityNodeInfo.ACTION_CLICK -> {
+ ControlActionCoordinator.toggle(cvh, template.getTemplateId(),
+ template.isChecked())
+ true
+ }
+ AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_PROGRESS.getId() -> {
+ if (arguments == null || !arguments.containsKey(
+ AccessibilityNodeInfo.ACTION_ARGUMENT_PROGRESS_VALUE)) {
+ false
+ } else {
+ val value = arguments.getFloat(
+ AccessibilityNodeInfo.ACTION_ARGUMENT_PROGRESS_VALUE)
+ val ratioDiff = (value - rangeTemplate.getCurrentValue()) /
+ (rangeTemplate.getMaxValue() - rangeTemplate.getMinValue())
+ updateRange(ratioDiff, template.isChecked())
+ endUpdateRange()
+ true
+ }
+ }
+ else -> false
+ }
+
+ return handled || super.performAccessibilityAction(host, action, arguments)
+ }
+
+ override fun onRequestSendAccessibilityEvent(
+ host: ViewGroup,
+ child: View,
+ event: AccessibilityEvent
+ ): Boolean = false
+ })
}
fun beginUpdateRange() {
@@ -111,7 +177,7 @@
clipLayer.setLevel(newLevel)
if (checked) {
- val newValue = levelToRangeValue()
+ val newValue = levelToRangeValue(clipLayer.getLevel())
val formattedNewValue = format(rangeTemplate.getFormatString().toString(),
DEFAULT_FORMAT, newValue)
@@ -136,8 +202,8 @@
}
}
- private fun levelToRangeValue(): Float {
- val ratio = clipLayer.getLevel().toFloat() / MAX_LEVEL
+ private fun levelToRangeValue(i: Int): Float {
+ val ratio = i.toFloat() / MAX_LEVEL
return rangeTemplate.getMinValue() +
(ratio * (rangeTemplate.getMaxValue() - rangeTemplate.getMinValue()))
}
@@ -146,7 +212,8 @@
statusExtra.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources()
.getDimensionPixelSize(R.dimen.control_status_normal).toFloat())
status.setVisibility(View.VISIBLE)
- cvh.action(FloatAction(rangeTemplate.getTemplateId(), findNearestStep(levelToRangeValue())))
+ cvh.action(FloatAction(rangeTemplate.getTemplateId(),
+ findNearestStep(levelToRangeValue(clipLayer.getLevel()))))
}
fun findNearestStep(value: Float): Float {
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/TouchBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/TouchBehavior.kt
new file mode 100644
index 0000000..d64a5f0
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/TouchBehavior.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2020 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.controls.ui
+
+import android.graphics.drawable.Drawable
+import android.graphics.drawable.LayerDrawable
+import android.view.View
+import android.service.controls.Control
+import android.service.controls.templates.StatelessTemplate
+
+import com.android.systemui.R
+import com.android.systemui.controls.ui.ControlActionCoordinator.MIN_LEVEL
+
+/**
+ * Supports touch events, but has no notion of state as the {@link ToggleBehavior} does. Must be
+ * used with {@link StatelessTemplate}.
+ */
+class TouchBehavior : Behavior {
+ lateinit var clipLayer: Drawable
+ lateinit var template: StatelessTemplate
+ lateinit var control: Control
+ lateinit var cvh: ControlViewHolder
+
+ override fun initialize(cvh: ControlViewHolder) {
+ this.cvh = cvh
+ cvh.applyRenderInfo(false)
+
+ cvh.layout.setOnClickListener(View.OnClickListener() {
+ ControlActionCoordinator.touch(cvh, template.getTemplateId())
+ })
+ }
+
+ override fun bind(cws: ControlWithState) {
+ this.control = cws.control!!
+ cvh.status.setText(control.getStatusText())
+ template = control.getControlTemplate() as StatelessTemplate
+
+ val ld = cvh.layout.getBackground() as LayerDrawable
+ clipLayer = ld.findDrawableByLayerId(R.id.clip_layer)
+ clipLayer.setLevel(MIN_LEVEL)
+
+ cvh.applyRenderInfo(false)
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/UnknownBehavior.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/UnknownBehavior.kt
index 1f33b85..c357249 100644
--- a/packages/SystemUI/src/com/android/systemui/controls/ui/UnknownBehavior.kt
+++ b/packages/SystemUI/src/com/android/systemui/controls/ui/UnknownBehavior.kt
@@ -25,7 +25,6 @@
override fun bind(cws: ControlWithState) {
cvh.status.setText(cvh.context.getString(com.android.internal.R.string.loading))
- cvh.setEnabled(false)
- cvh.applyRenderInfo(RenderInfo.lookup(cws.ci.deviceType, false))
+ cvh.applyRenderInfo(false)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/DependencyBinder.java b/packages/SystemUI/src/com/android/systemui/dagger/DependencyBinder.java
index 2877ed0..5b3d5c5 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/DependencyBinder.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/DependencyBinder.java
@@ -44,8 +44,6 @@
import com.android.systemui.statusbar.phone.StatusBarIconController;
import com.android.systemui.statusbar.phone.StatusBarIconControllerImpl;
import com.android.systemui.statusbar.phone.StatusBarRemoteInputCallback;
-import com.android.systemui.statusbar.policy.BatteryController;
-import com.android.systemui.statusbar.policy.BatteryControllerImpl;
import com.android.systemui.statusbar.policy.BluetoothController;
import com.android.systemui.statusbar.policy.BluetoothControllerImpl;
import com.android.systemui.statusbar.policy.CastController;
@@ -179,12 +177,6 @@
/**
*/
@Binds
- public abstract BatteryController provideBatteryController(
- BatteryControllerImpl controllerImpl);
-
- /**
- */
- @Binds
public abstract ManagedProfileController provideManagedProfileController(
ManagedProfileControllerImpl controllerImpl);
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java b/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java
index 6c502d2..3a4b273 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/DependencyProvider.java
@@ -90,7 +90,7 @@
/** */
@Provides
- public AmbientDisplayConfiguration provideAmbientDispalyConfiguration(Context context) {
+ public AmbientDisplayConfiguration provideAmbientDisplayConfiguration(Context context) {
return new AmbientDisplayConfiguration(context);
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java
index 3e257b6..956b4aa 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIDefaultModule.java
@@ -23,6 +23,7 @@
import androidx.annotation.Nullable;
+import com.android.keyguard.KeyguardViewController;
import com.android.systemui.dock.DockManager;
import com.android.systemui.dock.DockManagerImpl;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
@@ -41,6 +42,9 @@
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.ShadeController;
import com.android.systemui.statusbar.phone.ShadeControllerImpl;
+import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
+import com.android.systemui.statusbar.policy.BatteryController;
+import com.android.systemui.statusbar.policy.BatteryControllerImpl;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.DeviceProvisionedControllerImpl;
@@ -76,6 +80,11 @@
NotificationLockscreenUserManagerImpl notificationLockscreenUserManager);
@Binds
+ @Singleton
+ public abstract BatteryController provideBatteryController(
+ BatteryControllerImpl controllerImpl);
+
+ @Binds
abstract DockManager bindDockManager(DockManagerImpl dockManager);
@Binds
@@ -117,4 +126,8 @@
@Binds
abstract DeviceProvisionedController bindDeviceProvisionedController(
DeviceProvisionedControllerImpl deviceProvisionedController);
+
+ @Binds
+ abstract KeyguardViewController bindKeyguardViewController(
+ StatusBarKeyguardViewManager statusBarKeyguardViewManager);
}
diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
index 513580f..2e9ce12 100644
--- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
+++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java
@@ -19,7 +19,6 @@
import android.annotation.Nullable;
import android.content.Context;
import android.content.pm.PackageManager;
-import android.view.Choreographer;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.systemui.BootCompleteCache;
@@ -31,22 +30,16 @@
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.recents.Recents;
import com.android.systemui.stackdivider.Divider;
-import com.android.systemui.statusbar.BlurUtils;
import com.android.systemui.statusbar.CommandQueue;
-import com.android.systemui.statusbar.NotificationShadeWindowBlurController;
-import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.notification.collection.inflation.NotificationRowBinder;
import com.android.systemui.statusbar.notification.collection.inflation.NotificationRowBinderImpl;
import com.android.systemui.statusbar.notification.people.PeopleHubModule;
import com.android.systemui.statusbar.notification.row.dagger.ExpandableNotificationRowComponent;
import com.android.systemui.statusbar.notification.row.dagger.NotificationRowComponent;
-import com.android.systemui.statusbar.phone.BiometricUnlockController;
import com.android.systemui.statusbar.phone.KeyguardLiftController;
-import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.phone.dagger.StatusBarComponent;
import com.android.systemui.statusbar.policy.HeadsUpManager;
-import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.util.concurrency.ConcurrencyModule;
import com.android.systemui.util.sensors.AsyncSensorManager;
import com.android.systemui.util.time.SystemClock;
@@ -98,21 +91,6 @@
keyguardUpdateMonitor, dumpManager);
}
- @Singleton
- @Provides
- @Nullable
- static NotificationShadeWindowBlurController providesBlurController(BlurUtils blurUtils,
- SysuiStatusBarStateController statusBarStateController,
- DumpManager dumpManager, BiometricUnlockController biometricUnlockController,
- KeyguardStateController keyguardStateController,
- NotificationShadeWindowController notificationShadeWindowController,
- Choreographer choreographer) {
- return blurUtils.supportsBlursOnWindows() ? new NotificationShadeWindowBlurController(
- statusBarStateController, blurUtils, biometricUnlockController,
- keyguardStateController, notificationShadeWindowController, choreographer,
- dumpManager) : null;
- }
-
/** */
@Binds
public abstract NotificationRowBinder bindNotificationRowBinder(
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java b/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java
index c45063a..f6fccc0 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java
@@ -161,15 +161,8 @@
}
int scrimOpacity = -1;
- if (mPaused || mScreenOff) {
- // If AOD is paused, force the screen black until the
- // sensor reports a new brightness. This ensures that when the screen comes on
- // again, it will only show after the brightness sensor has stabilized,
- // avoiding a potential flicker.
- scrimOpacity = 255;
- } else if (!mScreenOff && mLightSensor == null) {
- // No light sensor but previous state turned the screen black. Make the scrim
- // transparent and below views visible.
+ if (mLightSensor == null) {
+ // No light sensor, scrims are always transparent.
scrimOpacity = 0;
} else if (brightnessReady) {
// Only unblank scrim once brightness is ready.
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
index 44e5d3d..700a861 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeSensors.java
@@ -49,6 +49,7 @@
import com.android.systemui.util.wakelock.WakeLock;
import java.io.PrintWriter;
+import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
@@ -261,7 +262,7 @@
private final ContentObserver mSettingsObserver = new ContentObserver(mHandler) {
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags, int userId) {
if (userId != ActivityManager.getCurrentUser()) {
return;
}
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
index 24f505d..b99d765 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialog.java
@@ -100,6 +100,7 @@
import com.android.systemui.plugins.GlobalActions.GlobalActionsManager;
import com.android.systemui.plugins.GlobalActionsPanelPlugin;
import com.android.systemui.statusbar.BlurUtils;
+import com.android.systemui.statusbar.NotificationShadeDepthController;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.ScrimController;
import com.android.systemui.statusbar.policy.ConfigurationController;
@@ -115,16 +116,17 @@
import javax.inject.Inject;
/**
- * Helper to show the global actions dialog. Each item is an {@link Action} that
- * may show depending on whether the keyguard is showing, and whether the device
- * is provisioned.
+ * Helper to show the global actions dialog. Each item is an {@link Action} that may show depending
+ * on whether the keyguard is showing, and whether the device is provisioned.
*/
public class GlobalActionsDialog implements DialogInterface.OnDismissListener,
- DialogInterface.OnShowListener, ConfigurationController.ConfigurationListener {
+ DialogInterface.OnShowListener,
+ ConfigurationController.ConfigurationListener,
+ GlobalActionsPanelPlugin.Callbacks {
- static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
- static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
- static public final String SYSTEM_DIALOG_REASON_DREAM = "dream";
+ public static final String SYSTEM_DIALOG_REASON_KEY = "reason";
+ public static final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
+ public static final String SYSTEM_DIALOG_REASON_DREAM = "dream";
private static final String TAG = "GlobalActionsDialog";
@@ -162,6 +164,7 @@
private final IActivityManager mIActivityManager;
private final TelecomManager mTelecomManager;
private final MetricsLogger mMetricsLogger;
+ private final NotificationShadeDepthController mDepthController;
private final BlurUtils mBlurUtils;
private ArrayList<Action> mItems;
@@ -207,8 +210,8 @@
KeyguardStateController keyguardStateController, UserManager userManager,
TrustManager trustManager, IActivityManager iActivityManager,
@Nullable TelecomManager telecomManager, MetricsLogger metricsLogger,
- BlurUtils blurUtils, SysuiColorExtractor colorExtractor,
- IStatusBarService statusBarService,
+ NotificationShadeDepthController depthController, SysuiColorExtractor colorExtractor,
+ IStatusBarService statusBarService, BlurUtils blurUtils,
NotificationShadeWindowController notificationShadeWindowController,
ControlsUiController controlsUiController, IWindowManager iWindowManager,
@Background Executor backgroundExecutor,
@@ -229,7 +232,7 @@
mIActivityManager = iActivityManager;
mTelecomManager = telecomManager;
mMetricsLogger = metricsLogger;
- mBlurUtils = blurUtils;
+ mDepthController = depthController;
mSysuiColorExtractor = colorExtractor;
mStatusBarService = statusBarService;
mNotificationShadeWindowController = notificationShadeWindowController;
@@ -237,6 +240,7 @@
mIWindowManager = iWindowManager;
mBackgroundExecutor = backgroundExecutor;
mControlsListingController = controlsListingController;
+ mBlurUtils = blurUtils;
// receive broadcasts
IntentFilter filter = new IntentFilter();
@@ -268,8 +272,9 @@
@Override
public void onUnlockedChanged() {
if (mDialog != null && mDialog.mPanelController != null) {
- boolean locked = !keyguardStateController.canDismissLockScreen();
- mDialog.mPanelController.onDeviceLockStateChanged(locked);
+ boolean unlocked = keyguardStateController.isUnlocked()
+ || keyguardStateController.canDismissLockScreen();
+ mDialog.mPanelController.onDeviceLockStateChanged(unlocked);
}
}
});
@@ -383,7 +388,7 @@
mItems.add(getSettingsAction());
} else if (GLOBAL_ACTION_KEY_LOCKDOWN.equals(actionKey)) {
if (Settings.Secure.getIntForUser(mContentResolver,
- Settings.Secure.LOCKDOWN_IN_POWER_MENU, 0, getCurrentUser().id) != 0
+ Settings.Secure.LOCKDOWN_IN_POWER_MENU, 0, getCurrentUser().id) != 0
&& shouldDisplayLockdown()) {
mItems.add(getLockdownAction());
}
@@ -417,29 +422,10 @@
mAdapter = new MyAdapter();
- GlobalActionsPanelPlugin.PanelViewController panelViewController =
- mPanelPlugin != null
- ? mPanelPlugin.onPanelShown(
- new GlobalActionsPanelPlugin.Callbacks() {
- @Override
- public void dismissGlobalActionsMenu() {
- dismissDialog();
- }
-
- @Override
- public void startPendingIntentDismissingKeyguard(
- PendingIntent intent) {
- mActivityStarter
- .startPendingIntentDismissingKeyguard(intent);
- }
- },
- !mKeyguardStateController.isUnlocked())
- : null;
-
- ActionsDialog dialog = new ActionsDialog(mContext, mAdapter, panelViewController,
- mBlurUtils, mSysuiColorExtractor, mStatusBarService,
+ ActionsDialog dialog = new ActionsDialog(mContext, mAdapter, getWalletPanelViewController(),
+ mDepthController, mSysuiColorExtractor, mStatusBarService,
mNotificationShadeWindowController,
- shouldShowControls() ? mControlsUiController : null);
+ shouldShowControls() ? mControlsUiController : null, mBlurUtils);
dialog.setCanceledOnTouchOutside(false); // Handled by the custom class.
dialog.setKeyguardShowing(mKeyguardShowing);
@@ -474,6 +460,33 @@
mConfigurationController.removeCallback(this);
}
+ @Nullable
+ private GlobalActionsPanelPlugin.PanelViewController getWalletPanelViewController() {
+ if (mPanelPlugin == null) {
+ return null;
+ }
+ return mPanelPlugin.onPanelShown(this, !mKeyguardStateController.isUnlocked());
+ }
+
+ /**
+ * Implements {@link GlobalActionsPanelPlugin.Callbacks#dismissGlobalActionsMenu()}, which is
+ * called when the quick access wallet requests dismissal.
+ */
+ @Override
+ public void dismissGlobalActionsMenu() {
+ dismissDialog();
+ }
+
+ /**
+ * Implements {@link GlobalActionsPanelPlugin.Callbacks#dismissGlobalActionsMenu()}, which is
+ * called when the quick access wallet requests that an intent be started (with lock screen
+ * shown first if needed).
+ */
+ @Override
+ public void startPendingIntentDismissingKeyguard(PendingIntent pendingIntent) {
+ mActivityStarter.startPendingIntentDismissingKeyguard(pendingIntent);
+ }
+
private final class PowerAction extends SinglePressAction implements LongPressAction {
private PowerAction() {
super(R.drawable.ic_lock_power_off,
@@ -916,7 +929,9 @@
}
}
- /** {@inheritDoc} */
+ /**
+ * {@inheritDoc}
+ */
public void onDismiss(DialogInterface dialog) {
if (mDialog == dialog) {
mDialog = null;
@@ -932,17 +947,19 @@
}
}
- /** {@inheritDoc} */
+ /**
+ * {@inheritDoc}
+ */
public void onShow(DialogInterface dialog) {
mMetricsLogger.visible(MetricsEvent.POWER_MENU);
}
/**
- * The adapter used for the list within the global actions dialog, taking
- * into account whether the keyguard is showing via
- * {@link com.android.systemui.globalactions.GlobalActionsDialog#mKeyguardShowing} and whether
- * the device is provisioned
- * via {@link com.android.systemui.globalactions.GlobalActionsDialog#mDeviceProvisioned}.
+ * The adapter used for the list within the global actions dialog, taking into account whether
+ * the keyguard is showing via
+ * {@link com.android.systemui.globalactions.GlobalActionsDialog#mKeyguardShowing}
+ * and whether the device is provisioned via
+ * {@link com.android.systemui.globalactions.GlobalActionsDialog#mDeviceProvisioned}.
*/
public class MyAdapter extends MultiListAdapter {
private int countItems(boolean separated) {
@@ -1073,8 +1090,7 @@
*/
public interface Action {
/**
- * @return Text that will be announced when dialog is created. null
- * for none.
+ * @return Text that will be announced when dialog is created. null for none.
*/
CharSequence getLabelForAccessibility(Context context);
@@ -1083,15 +1099,13 @@
void onPress();
/**
- * @return whether this action should appear in the dialog when the keygaurd
- * is showing.
+ * @return whether this action should appear in the dialog when the keygaurd is showing.
*/
boolean showDuringKeyguard();
/**
- * @return whether this action should appear in the dialog before the
- * device is provisioned.onlongpress
- *
+ * @return whether this action should appear in the dialog before the device is
+ * provisioned.onlongpress
*/
boolean showBeforeProvisioning();
@@ -1110,8 +1124,7 @@
}
/**
- * A single press action maintains no state, just responds to a press
- * and takes an action.
+ * A single press action maintains no state, just responds to a press and takes an action.
*/
private abstract class SinglePressAction implements Action {
@@ -1185,8 +1198,8 @@
}
/**
- * A toggle action knows whether it is on or off, and displays an icon
- * and status message accordingly.
+ * A toggle action knows whether it is on or off, and displays an icon and status message
+ * accordingly.
*/
private static abstract class ToggleAction implements Action {
@@ -1236,8 +1249,7 @@
}
/**
- * Override to make changes to resource IDs just before creating the
- * View.
+ * Override to make changes to resource IDs just before creating the View.
*/
void willCreate() {
@@ -1293,9 +1305,9 @@
}
/**
- * Implementations may override this if their state can be in on of the intermediate
- * states until some notification is received (e.g airplane mode is 'turning off' until
- * we know the wireless connections are back online
+ * Implementations may override this if their state can be in on of the intermediate states
+ * until some notification is received (e.g airplane mode is 'turning off' until we know the
+ * wireless connections are back online
*
* @param buttonOn Whether the button was turned on or off
*/
@@ -1313,12 +1325,13 @@
private class AirplaneModeAction extends ToggleAction {
AirplaneModeAction() {
super(
- R.drawable.ic_lock_airplane_mode,
- R.drawable.ic_lock_airplane_mode_off,
- R.string.global_actions_toggle_airplane_mode,
- R.string.global_actions_airplane_mode_on_status,
- R.string.global_actions_airplane_mode_off_status);
+ R.drawable.ic_lock_airplane_mode,
+ R.drawable.ic_lock_airplane_mode_off,
+ R.string.global_actions_toggle_airplane_mode,
+ R.string.global_actions_airplane_mode_on_status,
+ R.string.global_actions_airplane_mode_off_status);
}
+
void onToggle(boolean on) {
if (mHasTelephony && TelephonyProperties.in_ecm_mode().orElse(false)) {
mIsWaitingForEcmExit = true;
@@ -1570,25 +1583,27 @@
private ResetOrientationData mResetOrientationData;
private boolean mHadTopUi;
private final NotificationShadeWindowController mNotificationShadeWindowController;
+ private final NotificationShadeDepthController mDepthController;
private final BlurUtils mBlurUtils;
private ControlsUiController mControlsUiController;
private ViewGroup mControlsView;
- private ViewGroup mContainerView;
ActionsDialog(Context context, MyAdapter adapter,
- GlobalActionsPanelPlugin.PanelViewController plugin, BlurUtils blurUtils,
+ GlobalActionsPanelPlugin.PanelViewController plugin,
+ NotificationShadeDepthController depthController,
SysuiColorExtractor sysuiColorExtractor, IStatusBarService statusBarService,
NotificationShadeWindowController notificationShadeWindowController,
- ControlsUiController controlsUiController) {
+ ControlsUiController controlsUiController, BlurUtils blurUtils) {
super(context, com.android.systemui.R.style.Theme_SystemUI_Dialog_GlobalActions);
mContext = context;
mAdapter = adapter;
- mBlurUtils = blurUtils;
+ mDepthController = depthController;
mColorExtractor = sysuiColorExtractor;
mStatusBarService = statusBarService;
mNotificationShadeWindowController = notificationShadeWindowController;
mControlsUiController = controlsUiController;
+ mBlurUtils = blurUtils;
// Window initialization
Window window = getWindow();
@@ -1602,11 +1617,11 @@
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
window.addFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
- | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
- | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
- | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
- | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
- | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
+ | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+ | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
+ | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
+ | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
+ | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
window.setType(WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY);
window.getAttributes().setFitInsetsTypes(0 /* types */);
setTitle(R.string.global_actions);
@@ -1671,7 +1686,6 @@
mControlsView = findViewById(com.android.systemui.R.id.global_actions_controls);
mGlobalActionsLayout = findViewById(com.android.systemui.R.id.global_actions_view);
mGlobalActionsLayout.setOutsideTouchListener(view -> dismiss());
- ((View) mGlobalActionsLayout.getParent()).setOnClickListener(view -> dismiss());
mGlobalActionsLayout.setListViewAccessibilityDelegate(new View.AccessibilityDelegate() {
@Override
public boolean dispatchPopulateAccessibilityEvent(
@@ -1684,22 +1698,24 @@
mGlobalActionsLayout.setRotationListener(this::onRotate);
mGlobalActionsLayout.setAdapter(mAdapter);
+ View globalActionsParent = (View) mGlobalActionsLayout.getParent();
+ globalActionsParent.setOnClickListener(v -> dismiss());
+
+ // add fall-through dismiss handling to root view
+ View rootView = findViewById(com.android.systemui.R.id.global_actions_grid_root);
+ if (rootView != null) {
+ rootView.setOnClickListener(v -> dismiss());
+ }
+
if (shouldUsePanel()) {
initializePanel();
}
if (mBackgroundDrawable == null) {
mBackgroundDrawable = new ScrimDrawable();
- mScrimAlpha = ScrimController.BUSY_SCRIM_ALPHA;
+ mScrimAlpha = mBlurUtils.supportsBlursOnWindows()
+ ? ScrimController.BLUR_SCRIM_ALPHA : ScrimController.BUSY_SCRIM_ALPHA;
}
getWindow().setBackgroundDrawable(mBackgroundDrawable);
-
- if (mControlsView != null) {
- mContainerView = findViewById(com.android.systemui.R.id.global_actions_container);
- mContainerView.setOnTouchListener((v, e) -> {
- dismiss();
- return true;
- });
- }
}
private void fixNavBarClipping() {
@@ -1749,7 +1765,8 @@
/**
* Updates background and system bars according to current GradientColors.
- * @param colors Colors and hints to use.
+ *
+ * @param colors Colors and hints to use.
* @param animate Interpolates gradient if true, just sets otherwise.
*/
private void updateColors(GradientColors colors, boolean animate) {
@@ -1793,8 +1810,8 @@
float animatedValue = animation.getAnimatedFraction();
int alpha = (int) (animatedValue * mScrimAlpha * 255);
mBackgroundDrawable.setAlpha(alpha);
- mBlurUtils.applyBlur(mGlobalActionsLayout.getViewRootImpl(),
- mBlurUtils.radiusForRatio(animatedValue));
+ mDepthController.updateGlobalDialogVisibility(animatedValue,
+ mGlobalActionsLayout);
})
.start();
if (mControlsUiController != null) {
@@ -1823,8 +1840,8 @@
float animatedValue = 1f - animation.getAnimatedFraction();
int alpha = (int) (animatedValue * mScrimAlpha * 255);
mBackgroundDrawable.setAlpha(alpha);
- mBlurUtils.applyBlur(mGlobalActionsLayout.getViewRootImpl(),
- mBlurUtils.radiusForRatio(animatedValue));
+ mDepthController.updateGlobalDialogVisibility(animatedValue,
+ mGlobalActionsLayout);
})
.start();
dismissPanel();
@@ -1915,8 +1932,8 @@
}
/**
- * Determines whether or not the Global Actions menu should be forced to
- * use the newer grid-style layout.
+ * Determines whether or not the Global Actions menu should be forced to use the newer
+ * grid-style layout.
*/
private static boolean isForceGridEnabled(Context context) {
return isPanelDebugModeEnabled(context);
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
index 280a248..12955a1 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsImpl.java
@@ -149,9 +149,9 @@
}
if (mBlurUtils.supportsBlursOnWindows()) {
- background.setAlpha((int) (ScrimController.BUSY_SCRIM_ALPHA * 255));
+ background.setAlpha((int) (ScrimController.BLUR_SCRIM_ALPHA * 255));
mBlurUtils.applyBlur(d.getWindow().getDecorView().getViewRootImpl(),
- mBlurUtils.radiusForRatio(1));
+ mBlurUtils.blurRadiusOfRatio(1));
} else {
background.setAlpha((int) (SHUTDOWN_SCRIM_ALPHA * 255));
}
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/MinHeightScrollView.java b/packages/SystemUI/src/com/android/systemui/globalactions/MinHeightScrollView.java
new file mode 100644
index 0000000..622fa65
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/MinHeightScrollView.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2020 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.globalactions;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.ScrollView;
+
+/**
+ * When measured, this view sets the minimum height of its first child to be equal to its own
+ * target height.
+ *
+ * This ensures fall-through click handlers can be placed on this view's child component.
+ */
+public class MinHeightScrollView extends ScrollView {
+ public MinHeightScrollView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ @Override
+ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ View firstChild = getChildAt(0);
+ if (firstChild != null) {
+ firstChild.setMinimumHeight(MeasureSpec.getSize(heightMeasureSpec));
+ }
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index c129035..226ac16c 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -80,6 +80,7 @@
import com.android.keyguard.KeyguardSecurityView;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.keyguard.KeyguardUpdateMonitorCallback;
+import com.android.keyguard.KeyguardViewController;
import com.android.keyguard.ViewMediatorCallback;
import com.android.systemui.Dumpable;
import com.android.systemui.R;
@@ -90,12 +91,13 @@
import com.android.systemui.dump.DumpManager;
import com.android.systemui.keyguard.dagger.KeyguardModule;
import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.shared.system.QuickStepContract;
import com.android.systemui.statusbar.phone.BiometricUnlockController;
import com.android.systemui.statusbar.phone.KeyguardBypassController;
+import com.android.systemui.statusbar.phone.NavigationModeController;
import com.android.systemui.statusbar.phone.NotificationPanelViewController;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.StatusBar;
-import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
import com.android.systemui.util.DeviceConfigProxy;
import com.android.systemui.util.InjectionInflationController;
@@ -236,7 +238,7 @@
*/
private PowerManager.WakeLock mShowKeyguardWakeLock;
- private final Lazy<StatusBarKeyguardViewManager> mStatusBarKeyguardViewManagerLazy;
+ private final Lazy<KeyguardViewController> mKeyguardViewControllerLazy;
// these are protected by synchronized (this)
@@ -374,6 +376,7 @@
private boolean mLockLater;
private boolean mShowHomeOverLockscreen;
+ private boolean mInGestureNavigationMode;
private boolean mWakeAndUnlocking;
private IKeyguardDrawnCallback mDrawnCallback;
@@ -601,7 +604,7 @@
@Override
public void setNeedsInput(boolean needsInput) {
- mStatusBarKeyguardViewManagerLazy.get().setNeedsInput(needsInput);
+ mKeyguardViewControllerLazy.get().setNeedsInput(needsInput);
}
@Override
@@ -615,7 +618,7 @@
mKeyguardDonePending = true;
mHideAnimationRun = true;
mHideAnimationRunning = true;
- mStatusBarKeyguardViewManagerLazy.get()
+ mKeyguardViewControllerLazy.get()
.startPreHideAnimation(mHideAnimationFinishedRunnable);
mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
KEYGUARD_DONE_PENDING_TIMEOUT_MS);
@@ -647,7 +650,7 @@
@Override
public void onCancelClicked() {
- mStatusBarKeyguardViewManagerLazy.get().onCancelClicked();
+ mKeyguardViewControllerLazy.get().onCancelClicked();
}
@Override
@@ -715,18 +718,19 @@
LockPatternUtils lockPatternUtils,
BroadcastDispatcher broadcastDispatcher,
NotificationShadeWindowController notificationShadeWindowController,
- Lazy<StatusBarKeyguardViewManager> statusBarKeyguardViewManagerLazy,
+ Lazy<KeyguardViewController> statusBarKeyguardViewManagerLazy,
DismissCallbackRegistry dismissCallbackRegistry,
KeyguardUpdateMonitor keyguardUpdateMonitor, DumpManager dumpManager,
@UiBackground Executor uiBgExecutor, PowerManager powerManager,
TrustManager trustManager,
- DeviceConfigProxy deviceConfig) {
+ DeviceConfigProxy deviceConfig,
+ NavigationModeController navigationModeController) {
super(context);
mFalsingManager = falsingManager;
mLockPatternUtils = lockPatternUtils;
mBroadcastDispatcher = broadcastDispatcher;
mNotificationShadeWindowController = notificationShadeWindowController;
- mStatusBarKeyguardViewManagerLazy = statusBarKeyguardViewManagerLazy;
+ mKeyguardViewControllerLazy = statusBarKeyguardViewManagerLazy;
mDismissCallbackRegistry = dismissCallbackRegistry;
mUiBgExecutor = uiBgExecutor;
mUpdateMonitor = keyguardUpdateMonitor;
@@ -742,6 +746,10 @@
DeviceConfig.NAMESPACE_SYSTEMUI,
mHandler::post,
mOnPropertiesChangedListener);
+ mInGestureNavigationMode =
+ QuickStepContract.isGesturalMode(navigationModeController.addListener(mode -> {
+ mInGestureNavigationMode = QuickStepContract.isGesturalMode(mode);
+ }));
}
public void userActivity() {
@@ -1288,7 +1296,7 @@
if (mOccluded != isOccluded) {
mOccluded = isOccluded;
mUpdateMonitor.setKeyguardOccluded(isOccluded);
- mStatusBarKeyguardViewManagerLazy.get().setOccluded(isOccluded, animate
+ mKeyguardViewControllerLazy.get().setOccluded(isOccluded, animate
&& mDeviceInteractive);
adjustStatusBarLocked();
}
@@ -1359,7 +1367,7 @@
}
// if the keyguard is already showing, don't bother
- if (mStatusBarKeyguardViewManagerLazy.get().isShowing()) {
+ if (mKeyguardViewControllerLazy.get().isShowing()) {
if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
resetStateLocked();
return;
@@ -1423,7 +1431,7 @@
mDismissCallbackRegistry.addCallback(callback);
}
mCustomMessage = message;
- mStatusBarKeyguardViewManagerLazy.get().dismissAndCollapse();
+ mKeyguardViewControllerLazy.get().dismissAndCollapse();
} else if (callback != null) {
new DismissCallbackWrapper(callback).notifyDismissError();
}
@@ -1690,7 +1698,7 @@
} else if (!mHideAnimationRun) {
mHideAnimationRun = true;
mHideAnimationRunning = true;
- mStatusBarKeyguardViewManagerLazy.get()
+ mKeyguardViewControllerLazy.get()
.startPreHideAnimation(mHideAnimationFinishedRunnable);
}
}
@@ -1847,7 +1855,7 @@
mHiding = false;
mWakeAndUnlocking = false;
setShowingLocked(true);
- mStatusBarKeyguardViewManagerLazy.get().show(options);
+ mKeyguardViewControllerLazy.get().show(options);
resetKeyguardDonePendingLocked();
mHideAnimationRun = false;
adjustStatusBarLocked();
@@ -1872,22 +1880,22 @@
public void run() {
Trace.beginSection("KeyguardViewMediator.mKeyGuardGoingAwayRunnable");
if (DEBUG) Log.d(TAG, "keyguardGoingAway");
- mStatusBarKeyguardViewManagerLazy.get().keyguardGoingAway();
+ mKeyguardViewControllerLazy.get().keyguardGoingAway();
int flags = 0;
- if (mStatusBarKeyguardViewManagerLazy.get().shouldDisableWindowAnimationsForUnlock()
+ if (mKeyguardViewControllerLazy.get().shouldDisableWindowAnimationsForUnlock()
|| (mWakeAndUnlocking && !mPulsing)) {
flags |= WindowManagerPolicyConstants
.KEYGUARD_GOING_AWAY_FLAG_NO_WINDOW_ANIMATIONS;
}
- if (mStatusBarKeyguardViewManagerLazy.get().isGoingToNotificationShade()
+ if (mKeyguardViewControllerLazy.get().isGoingToNotificationShade()
|| (mWakeAndUnlocking && mPulsing)) {
flags |= WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE;
}
- if (mStatusBarKeyguardViewManagerLazy.get().isUnlockWithWallpaper()) {
+ if (mKeyguardViewControllerLazy.get().isUnlockWithWallpaper()) {
flags |= WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
}
- if (mStatusBarKeyguardViewManagerLazy.get().shouldSubtleWindowAnimationsForUnlock()) {
+ if (mKeyguardViewControllerLazy.get().shouldSubtleWindowAnimationsForUnlock()) {
flags |= WindowManagerPolicyConstants
.KEYGUARD_GOING_AWAY_FLAG_SUBTLE_WINDOW_ANIMATIONS;
}
@@ -1973,7 +1981,7 @@
// Hack level over 9000: To speed up wake-and-unlock sequence, force it to report
// the next draw from here so we don't have to wait for window manager to signal
// this to our ViewRootImpl.
- mStatusBarKeyguardViewManagerLazy.get().getViewRootImpl().setReportNextDraw();
+ mKeyguardViewControllerLazy.get().getViewRootImpl().setReportNextDraw();
notifyDrawn(mDrawnCallback);
mDrawnCallback = null;
}
@@ -1987,7 +1995,7 @@
setShowingLocked(false);
mWakeAndUnlocking = false;
mDismissCallbackRegistry.notifyDismissSucceeded();
- mStatusBarKeyguardViewManagerLazy.get().hide(startTime, fadeoutDuration);
+ mKeyguardViewControllerLazy.get().hide(startTime, fadeoutDuration);
resetKeyguardDonePendingLocked();
mHideAnimationRun = false;
adjustStatusBarLocked();
@@ -2013,7 +2021,7 @@
// windows that appear on top, ever
int flags = StatusBarManager.DISABLE_NONE;
if (forceHideHomeRecentsButtons || isShowingAndNotOccluded()) {
- if (!mShowHomeOverLockscreen) {
+ if (!mShowHomeOverLockscreen || !mInGestureNavigationMode) {
flags |= StatusBarManager.DISABLE_HOME;
}
flags |= StatusBarManager.DISABLE_RECENT;
@@ -2036,7 +2044,7 @@
private void handleReset() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleReset");
- mStatusBarKeyguardViewManagerLazy.get().reset(true /* hideBouncerWhenShowing */);
+ mKeyguardViewControllerLazy.get().reset(true /* hideBouncerWhenShowing */);
}
}
@@ -2049,7 +2057,7 @@
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
setShowingLocked(true);
- mStatusBarKeyguardViewManagerLazy.get().dismissAndCollapse();
+ mKeyguardViewControllerLazy.get().dismissAndCollapse();
}
Trace.endSection();
}
@@ -2057,7 +2065,7 @@
private void handleNotifyStartedGoingToSleep() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep");
- mStatusBarKeyguardViewManagerLazy.get().onStartedGoingToSleep();
+ mKeyguardViewControllerLazy.get().onStartedGoingToSleep();
}
}
@@ -2068,7 +2076,7 @@
private void handleNotifyFinishedGoingToSleep() {
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep");
- mStatusBarKeyguardViewManagerLazy.get().onFinishedGoingToSleep();
+ mKeyguardViewControllerLazy.get().onFinishedGoingToSleep();
}
}
@@ -2076,7 +2084,7 @@
Trace.beginSection("KeyguardViewMediator#handleMotifyStartedWakingUp");
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
- mStatusBarKeyguardViewManagerLazy.get().onStartedWakingUp();
+ mKeyguardViewControllerLazy.get().onStartedWakingUp();
}
Trace.endSection();
}
@@ -2085,7 +2093,7 @@
Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurningOn");
synchronized (KeyguardViewMediator.this) {
if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
- mStatusBarKeyguardViewManagerLazy.get().onScreenTurningOn();
+ mKeyguardViewControllerLazy.get().onScreenTurningOn();
if (callback != null) {
if (mWakeAndUnlocking) {
mDrawnCallback = callback;
@@ -2104,7 +2112,7 @@
}
synchronized (this) {
if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn");
- mStatusBarKeyguardViewManagerLazy.get().onScreenTurnedOn();
+ mKeyguardViewControllerLazy.get().onScreenTurnedOn();
}
Trace.endSection();
}
@@ -2148,14 +2156,26 @@
Trace.endSection();
}
- public StatusBarKeyguardViewManager registerStatusBar(StatusBar statusBar,
+ /**
+ * Registers the StatusBar to which the Keyguard View is mounted.
+ *
+ * @param statusBar
+ * @param container
+ * @param panelView
+ * @param biometricUnlockController
+ * @param lockIconContainer
+ * @param notificationContainer
+ * @param bypassController
+ * @return the View Controller for the Keyguard View this class is mediating.
+ */
+ public KeyguardViewController registerStatusBar(StatusBar statusBar,
ViewGroup container, NotificationPanelViewController panelView,
BiometricUnlockController biometricUnlockController, ViewGroup lockIconContainer,
View notificationContainer, KeyguardBypassController bypassController) {
- mStatusBarKeyguardViewManagerLazy.get().registerStatusBar(statusBar, container, panelView,
+ mKeyguardViewControllerLazy.get().registerStatusBar(statusBar, container, panelView,
biometricUnlockController, mDismissCallbackRegistry, lockIconContainer,
notificationContainer, bypassController, mFalsingManager);
- return mStatusBarKeyguardViewManagerLazy.get();
+ return mKeyguardViewControllerLazy.get();
}
public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivityController.java b/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivityController.java
index ae380b7..c281ece 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivityController.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivityController.java
@@ -93,7 +93,7 @@
return mIatm.startActivityAsUser(
mContext.getIApplicationThread() /*caller*/,
mContext.getBasePackageName() /*callingPackage*/,
- mContext.getFeatureId() /*callingFeatureId*/,
+ mContext.getAttributionTag() /*callingAttributionTag*/,
intent /*intent*/,
intent.resolveTypeIfNeeded(mContext.getContentResolver()) /*resolvedType*/,
null /*resultTo*/,
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
index 367f464..7a63a5e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java
@@ -22,15 +22,16 @@
import com.android.internal.widget.LockPatternUtils;
import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.keyguard.KeyguardViewController;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dagger.qualifiers.UiBackground;
import com.android.systemui.dump.DumpManager;
import com.android.systemui.keyguard.DismissCallbackRegistry;
import com.android.systemui.keyguard.KeyguardViewMediator;
import com.android.systemui.plugins.FalsingManager;
+import com.android.systemui.statusbar.phone.NavigationModeController;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.StatusBar;
-import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
import com.android.systemui.util.DeviceConfigProxy;
import java.util.concurrent.Executor;
@@ -57,14 +58,15 @@
LockPatternUtils lockPatternUtils,
BroadcastDispatcher broadcastDispatcher,
NotificationShadeWindowController notificationShadeWindowController,
- Lazy<StatusBarKeyguardViewManager> statusBarKeyguardViewManagerLazy,
+ Lazy<KeyguardViewController> statusBarKeyguardViewManagerLazy,
DismissCallbackRegistry dismissCallbackRegistry,
KeyguardUpdateMonitor updateMonitor,
DumpManager dumpManager,
PowerManager powerManager,
TrustManager trustManager,
@UiBackground Executor uiBgExecutor,
- DeviceConfigProxy deviceConfig) {
+ DeviceConfigProxy deviceConfig,
+ NavigationModeController navigationModeController) {
return new KeyguardViewMediator(
context,
falsingManager,
@@ -78,6 +80,7 @@
uiBgExecutor,
powerManager,
trustManager,
- deviceConfig);
+ deviceConfig,
+ navigationModeController);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java b/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java
new file mode 100644
index 0000000..a161d03
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/media/MediaControlPanel.java
@@ -0,0 +1,425 @@
+/*
+ * Copyright (C) 2020 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.media;
+
+import android.annotation.LayoutRes;
+import android.app.PendingIntent;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.res.ColorStateList;
+import android.graphics.Bitmap;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.GradientDrawable;
+import android.graphics.drawable.Icon;
+import android.graphics.drawable.RippleDrawable;
+import android.media.MediaMetadata;
+import android.media.session.MediaController;
+import android.media.session.MediaSession;
+import android.media.session.PlaybackState;
+import android.os.Handler;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageButton;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import androidx.core.graphics.drawable.RoundedBitmapDrawable;
+import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
+
+import com.android.settingslib.media.MediaDevice;
+import com.android.settingslib.media.MediaOutputSliceConstants;
+import com.android.settingslib.widget.AdaptiveIcon;
+import com.android.systemui.Dependency;
+import com.android.systemui.R;
+import com.android.systemui.plugins.ActivityStarter;
+import com.android.systemui.statusbar.NotificationMediaManager;
+
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * Base media control panel for System UI
+ */
+public class MediaControlPanel implements NotificationMediaManager.MediaListener {
+ private static final String TAG = "MediaControlPanel";
+ private final NotificationMediaManager mMediaManager;
+ private final Executor mBackgroundExecutor;
+
+ private Context mContext;
+ protected LinearLayout mMediaNotifView;
+ private View mSeamless;
+ private MediaSession.Token mToken;
+ private MediaController mController;
+ private int mForegroundColor;
+ private int mBackgroundColor;
+ protected ComponentName mRecvComponent;
+
+ private final int[] mActionIds;
+
+ // Button IDs used in notifications
+ protected static final int[] NOTIF_ACTION_IDS = {
+ com.android.internal.R.id.action0,
+ com.android.internal.R.id.action1,
+ com.android.internal.R.id.action2,
+ com.android.internal.R.id.action3,
+ com.android.internal.R.id.action4
+ };
+
+ private MediaController.Callback mSessionCallback = new MediaController.Callback() {
+ @Override
+ public void onSessionDestroyed() {
+ Log.d(TAG, "session destroyed");
+ mController.unregisterCallback(mSessionCallback);
+ clearControls();
+ }
+ };
+
+ /**
+ * Initialize a new control panel
+ * @param context
+ * @param parent
+ * @param manager
+ * @param layoutId layout resource to use for this control panel
+ * @param actionIds resource IDs for action buttons in the layout
+ * @param backgroundExecutor background executor, used for processing artwork
+ */
+ public MediaControlPanel(Context context, ViewGroup parent, NotificationMediaManager manager,
+ @LayoutRes int layoutId, int[] actionIds, Executor backgroundExecutor) {
+ mContext = context;
+ LayoutInflater inflater = LayoutInflater.from(mContext);
+ mMediaNotifView = (LinearLayout) inflater.inflate(layoutId, parent, false);
+ mMediaManager = manager;
+ mActionIds = actionIds;
+ mBackgroundExecutor = backgroundExecutor;
+ }
+
+ /**
+ * Get the view used to display media controls
+ * @return the view
+ */
+ public View getView() {
+ return mMediaNotifView;
+ }
+
+ /**
+ * Get the context
+ * @return context
+ */
+ public Context getContext() {
+ return mContext;
+ }
+
+ /**
+ * Update the media panel view for the given media session
+ * @param token
+ * @param icon
+ * @param iconColor
+ * @param bgColor
+ * @param contentIntent
+ * @param appNameString
+ * @param device
+ */
+ public void setMediaSession(MediaSession.Token token, Icon icon, int iconColor,
+ int bgColor, PendingIntent contentIntent, String appNameString, MediaDevice device) {
+ mToken = token;
+ mForegroundColor = iconColor;
+ mBackgroundColor = bgColor;
+ mController = new MediaController(mContext, mToken);
+
+ MediaMetadata mediaMetadata = mController.getMetadata();
+
+ // Try to find a receiver for the media button that matches this app
+ PackageManager pm = mContext.getPackageManager();
+ Intent it = new Intent(Intent.ACTION_MEDIA_BUTTON);
+ List<ResolveInfo> info = pm.queryBroadcastReceiversAsUser(it, 0, mContext.getUser());
+ if (info != null) {
+ for (ResolveInfo inf : info) {
+ if (inf.activityInfo.packageName.equals(mController.getPackageName())) {
+ mRecvComponent = inf.getComponentInfo().getComponentName();
+ }
+ }
+ }
+
+ mController.registerCallback(mSessionCallback);
+
+ if (mediaMetadata == null) {
+ Log.e(TAG, "Media metadata was null");
+ return;
+ }
+
+ ImageView albumView = mMediaNotifView.findViewById(R.id.album_art);
+ if (albumView != null) {
+ // Resize art in a background thread
+ mBackgroundExecutor.execute(() -> processAlbumArt(mediaMetadata, albumView));
+ }
+ mMediaNotifView.setBackgroundTintList(ColorStateList.valueOf(mBackgroundColor));
+
+ // Click action
+ mMediaNotifView.setOnClickListener(v -> {
+ try {
+ contentIntent.send();
+ // Also close shade
+ mContext.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
+ } catch (PendingIntent.CanceledException e) {
+ Log.e(TAG, "Pending intent was canceled", e);
+ }
+ });
+
+ // App icon
+ ImageView appIcon = mMediaNotifView.findViewById(R.id.icon);
+ Drawable iconDrawable = icon.loadDrawable(mContext);
+ iconDrawable.setTint(mForegroundColor);
+ appIcon.setImageDrawable(iconDrawable);
+
+ // Song name
+ TextView titleText = mMediaNotifView.findViewById(R.id.header_title);
+ String songName = mediaMetadata.getString(MediaMetadata.METADATA_KEY_TITLE);
+ titleText.setText(songName);
+ titleText.setTextColor(mForegroundColor);
+
+ // Not in mini player:
+ // App title
+ TextView appName = mMediaNotifView.findViewById(R.id.app_name);
+ if (appName != null) {
+ appName.setText(appNameString);
+ appName.setTextColor(mForegroundColor);
+ }
+
+ // Artist name
+ TextView artistText = mMediaNotifView.findViewById(R.id.header_artist);
+ if (artistText != null) {
+ String artistName = mediaMetadata.getString(MediaMetadata.METADATA_KEY_ARTIST);
+ artistText.setText(artistName);
+ artistText.setTextColor(mForegroundColor);
+ }
+
+ // Transfer chip
+ mSeamless = mMediaNotifView.findViewById(R.id.media_seamless);
+ if (mSeamless != null) {
+ mSeamless.setVisibility(View.VISIBLE);
+ updateDevice(device);
+ ActivityStarter mActivityStarter = Dependency.get(ActivityStarter.class);
+ mSeamless.setOnClickListener(v -> {
+ final Intent intent = new Intent()
+ .setAction(MediaOutputSliceConstants.ACTION_MEDIA_OUTPUT)
+ .putExtra(MediaOutputSliceConstants.EXTRA_PACKAGE_NAME,
+ mController.getPackageName())
+ .putExtra(MediaOutputSliceConstants.KEY_MEDIA_SESSION_TOKEN, mToken);
+ mActivityStarter.startActivity(intent, false, true /* dismissShade */,
+ Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
+ });
+ }
+
+ // Ensure is only added once
+ mMediaManager.removeCallback(this);
+ mMediaManager.addCallback(this);
+ }
+
+ /**
+ * Return the token for the current media session
+ * @return the token
+ */
+ public MediaSession.Token getMediaSessionToken() {
+ return mToken;
+ }
+
+ /**
+ * Get the current media controller
+ * @return the controller
+ */
+ public MediaController getController() {
+ return mController;
+ }
+
+ /**
+ * Get the name of the package associated with the current media controller
+ * @return the package name
+ */
+ public String getMediaPlayerPackage() {
+ return mController.getPackageName();
+ }
+
+ /**
+ * Check whether this player has an attached media session.
+ * @return whether there is a controller with a current media session.
+ */
+ public boolean hasMediaSession() {
+ return mController != null && mController.getPlaybackState() != null;
+ }
+
+ /**
+ * Check whether the media controlled by this player is currently playing
+ * @return whether it is playing, or false if no controller information
+ */
+ public boolean isPlaying() {
+ return isPlaying(mController);
+ }
+
+ /**
+ * Check whether the given controller is currently playing
+ * @param controller media controller to check
+ * @return whether it is playing, or false if no controller information
+ */
+ protected boolean isPlaying(MediaController controller) {
+ if (controller == null) {
+ return false;
+ }
+
+ PlaybackState state = controller.getPlaybackState();
+ if (state == null) {
+ return false;
+ }
+
+ return (state.getState() == PlaybackState.STATE_PLAYING);
+ }
+
+ /**
+ * Process album art for layout
+ * @param metadata media metadata
+ * @param albumView view to hold the album art
+ */
+ private void processAlbumArt(MediaMetadata metadata, ImageView albumView) {
+ Bitmap albumArt = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
+ float radius = mContext.getResources().getDimension(R.dimen.qs_media_corner_radius);
+ RoundedBitmapDrawable roundedDrawable = null;
+ if (albumArt != null) {
+ Bitmap original = albumArt.copy(Bitmap.Config.ARGB_8888, true);
+ int albumSize = (int) mContext.getResources().getDimension(
+ R.dimen.qs_media_album_size);
+ Bitmap scaled = Bitmap.createScaledBitmap(original, albumSize, albumSize, false);
+ roundedDrawable = RoundedBitmapDrawableFactory.create(mContext.getResources(), scaled);
+ roundedDrawable.setCornerRadius(radius);
+ } else {
+ Log.e(TAG, "No album art available");
+ }
+
+ // Now that it's resized, update the UI
+ final RoundedBitmapDrawable result = roundedDrawable;
+ albumView.getHandler().post(() -> {
+ if (result != null) {
+ albumView.setImageDrawable(result);
+ albumView.setVisibility(View.VISIBLE);
+ } else {
+ albumView.setImageDrawable(null);
+ albumView.setVisibility(View.GONE);
+ }
+ });
+ }
+
+ /**
+ * Update the current device information
+ * @param device device information to display
+ */
+ public void updateDevice(MediaDevice device) {
+ if (mSeamless == null) {
+ return;
+ }
+ Handler handler = mSeamless.getHandler();
+ handler.post(() -> {
+ updateChipInternal(device);
+ });
+ }
+
+ private void updateChipInternal(MediaDevice device) {
+ ColorStateList fgTintList = ColorStateList.valueOf(mForegroundColor);
+
+ // Update the outline color
+ LinearLayout viewLayout = (LinearLayout) mSeamless;
+ RippleDrawable bkgDrawable = (RippleDrawable) viewLayout.getBackground();
+ GradientDrawable rect = (GradientDrawable) bkgDrawable.getDrawable(0);
+ rect.setStroke(2, mForegroundColor);
+ rect.setColor(mBackgroundColor);
+
+ ImageView iconView = mSeamless.findViewById(R.id.media_seamless_image);
+ TextView deviceName = mSeamless.findViewById(R.id.media_seamless_text);
+ deviceName.setTextColor(fgTintList);
+
+ if (device != null) {
+ Drawable icon = device.getIcon();
+ iconView.setVisibility(View.VISIBLE);
+ iconView.setImageTintList(fgTintList);
+
+ if (icon instanceof AdaptiveIcon) {
+ AdaptiveIcon aIcon = (AdaptiveIcon) icon;
+ aIcon.setBackgroundColor(mBackgroundColor);
+ iconView.setImageDrawable(aIcon);
+ } else {
+ iconView.setImageDrawable(icon);
+ }
+ deviceName.setText(device.getName());
+ } else {
+ // Reset to default
+ iconView.setVisibility(View.GONE);
+ deviceName.setText(com.android.internal.R.string.ext_media_seamless_action);
+ }
+ }
+
+ /**
+ * Put controls into a resumption state
+ */
+ public void clearControls() {
+ // Hide all the old buttons
+ for (int i = 0; i < mActionIds.length; i++) {
+ ImageButton thisBtn = mMediaNotifView.findViewById(mActionIds[i]);
+ if (thisBtn != null) {
+ thisBtn.setVisibility(View.GONE);
+ }
+ }
+
+ // Add a restart button
+ ImageButton btn = mMediaNotifView.findViewById(mActionIds[0]);
+ btn.setOnClickListener(v -> {
+ Log.d(TAG, "Attempting to restart session");
+ // Send a media button event to previously found receiver
+ if (mRecvComponent != null) {
+ Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
+ intent.setComponent(mRecvComponent);
+ int keyCode = KeyEvent.KEYCODE_MEDIA_PLAY;
+ intent.putExtra(
+ Intent.EXTRA_KEY_EVENT,
+ new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
+ mContext.sendBroadcast(intent);
+ } else {
+ Log.d(TAG, "No receiver to restart");
+ // If we don't have a receiver, try relaunching the activity instead
+ try {
+ mController.getSessionActivity().send();
+ } catch (PendingIntent.CanceledException e) {
+ Log.e(TAG, "Pending intent was canceled", e);
+ }
+ }
+ });
+ btn.setImageDrawable(mContext.getResources().getDrawable(R.drawable.lb_ic_play));
+ btn.setImageTintList(ColorStateList.valueOf(mForegroundColor));
+ btn.setVisibility(View.VISIBLE);
+ }
+
+ @Override
+ public void onMetadataOrStateChanged(MediaMetadata metadata, int state) {
+ if (state == PlaybackState.STATE_NONE) {
+ clearControls();
+ mMediaManager.removeCallback(this);
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipAnimationController.java b/packages/SystemUI/src/com/android/systemui/pip/PipAnimationController.java
index 1fc1fe4..4bfcf22 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/PipAnimationController.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipAnimationController.java
@@ -19,11 +19,8 @@
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.IntDef;
-import android.annotation.MainThread;
import android.content.Context;
import android.graphics.Rect;
-import android.os.RemoteException;
-import android.view.IWindowContainer;
import android.view.SurfaceControl;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
@@ -33,6 +30,8 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import javax.inject.Inject;
+
/**
* Controller class of PiP animations (both from and to PiP mode).
*/
@@ -40,8 +39,6 @@
private static final float FRACTION_START = 0f;
private static final float FRACTION_END = 1f;
- public static final int DURATION_NONE = 0;
- public static final int DURATION_DEFAULT_MS = 425;
public static final int ANIM_TYPE_BOUNDS = 0;
public static final int ANIM_TYPE_ALPHA = 1;
@@ -52,40 +49,54 @@
@Retention(RetentionPolicy.SOURCE)
public @interface AnimationType {}
+ static final int TRANSITION_DIRECTION_NONE = 0;
+ static final int TRANSITION_DIRECTION_SAME = 1;
+ static final int TRANSITION_DIRECTION_TO_PIP = 2;
+ static final int TRANSITION_DIRECTION_TO_FULLSCREEN = 3;
+
+ @IntDef(prefix = { "TRANSITION_DIRECTION_" }, value = {
+ TRANSITION_DIRECTION_NONE,
+ TRANSITION_DIRECTION_SAME,
+ TRANSITION_DIRECTION_TO_PIP,
+ TRANSITION_DIRECTION_TO_FULLSCREEN
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ @interface TransitionDirection {}
+
private final Interpolator mFastOutSlowInInterpolator;
+ private final PipSurfaceTransactionHelper mSurfaceTransactionHelper;
private PipTransitionAnimator mCurrentAnimator;
- PipAnimationController(Context context) {
+ @Inject
+ PipAnimationController(Context context, PipSurfaceTransactionHelper helper) {
mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
com.android.internal.R.interpolator.fast_out_slow_in);
+ mSurfaceTransactionHelper = helper;
}
- @MainThread
- PipTransitionAnimator getAnimator(IWindowContainer wc, boolean scheduleFinishPip,
+ @SuppressWarnings("unchecked")
+ PipTransitionAnimator getAnimator(SurfaceControl leash,
Rect destinationBounds, float alphaStart, float alphaEnd) {
if (mCurrentAnimator == null) {
mCurrentAnimator = setupPipTransitionAnimator(
- PipTransitionAnimator.ofAlpha(wc, scheduleFinishPip,
- destinationBounds, alphaStart, alphaEnd));
+ PipTransitionAnimator.ofAlpha(leash, destinationBounds, alphaStart, alphaEnd));
} else if (mCurrentAnimator.getAnimationType() == ANIM_TYPE_ALPHA
&& mCurrentAnimator.isRunning()) {
mCurrentAnimator.updateEndValue(alphaEnd);
} else {
mCurrentAnimator.cancel();
mCurrentAnimator = setupPipTransitionAnimator(
- PipTransitionAnimator.ofAlpha(wc, scheduleFinishPip,
- destinationBounds, alphaStart, alphaEnd));
+ PipTransitionAnimator.ofAlpha(leash, destinationBounds, alphaStart, alphaEnd));
}
return mCurrentAnimator;
}
- @MainThread
- PipTransitionAnimator getAnimator(IWindowContainer wc, boolean scheduleFinishPip,
- Rect startBounds, Rect endBounds) {
+ @SuppressWarnings("unchecked")
+ PipTransitionAnimator getAnimator(SurfaceControl leash, Rect startBounds, Rect endBounds) {
if (mCurrentAnimator == null) {
mCurrentAnimator = setupPipTransitionAnimator(
- PipTransitionAnimator.ofBounds(wc, scheduleFinishPip, startBounds, endBounds));
+ PipTransitionAnimator.ofBounds(leash, startBounds, endBounds));
} else if (mCurrentAnimator.getAnimationType() == ANIM_TYPE_BOUNDS
&& mCurrentAnimator.isRunning()) {
mCurrentAnimator.setDestinationBounds(endBounds);
@@ -94,7 +105,7 @@
} else {
mCurrentAnimator.cancel();
mCurrentAnimator = setupPipTransitionAnimator(
- PipTransitionAnimator.ofBounds(wc, scheduleFinishPip, startBounds, endBounds));
+ PipTransitionAnimator.ofBounds(leash, startBounds, endBounds));
}
return mCurrentAnimator;
}
@@ -104,6 +115,7 @@
}
private PipTransitionAnimator setupPipTransitionAnimator(PipTransitionAnimator animator) {
+ animator.setSurfaceTransactionHelper(mSurfaceTransactionHelper);
animator.setInterpolator(mFastOutSlowInInterpolator);
animator.setFloatValues(FRACTION_START, FRACTION_END);
return animator;
@@ -116,18 +128,18 @@
/**
* Called when PiP animation is started.
*/
- public void onPipAnimationStart(IWindowContainer wc, PipTransitionAnimator animator) {}
+ public void onPipAnimationStart(PipTransitionAnimator animator) {}
/**
* Called when PiP animation is ended.
*/
- public void onPipAnimationEnd(IWindowContainer wc, SurfaceControl.Transaction tx,
+ public void onPipAnimationEnd(SurfaceControl.Transaction tx,
PipTransitionAnimator animator) {}
/**
* Called when PiP animation is cancelled.
*/
- public void onPipAnimationCancel(IWindowContainer wc, PipTransitionAnimator animator) {}
+ public void onPipAnimationCancel(PipTransitionAnimator animator) {}
}
/**
@@ -137,8 +149,6 @@
public abstract static class PipTransitionAnimator<T> extends ValueAnimator implements
ValueAnimator.AnimatorUpdateListener,
ValueAnimator.AnimatorListener {
- private final IWindowContainer mWindowContainer;
- private final boolean mScheduleFinishPip;
private final SurfaceControl mLeash;
private final @AnimationType int mAnimationType;
private final Rect mDestinationBounds = new Rect();
@@ -147,25 +157,22 @@
private T mEndValue;
private T mCurrentValue;
private PipAnimationCallback mPipAnimationCallback;
- private SurfaceControlTransactionFactory mSurfaceControlTransactionFactory;
+ private PipSurfaceTransactionHelper.SurfaceControlTransactionFactory
+ mSurfaceControlTransactionFactory;
+ private PipSurfaceTransactionHelper mSurfaceTransactionHelper;
+ private @TransitionDirection int mTransitionDirection;
- private PipTransitionAnimator(IWindowContainer wc, boolean scheduleFinishPip,
- @AnimationType int animationType, Rect destinationBounds,
- T startValue, T endValue) {
- mWindowContainer = wc;
- mScheduleFinishPip = scheduleFinishPip;
- try {
- mLeash = wc.getLeash();
- mAnimationType = animationType;
- mDestinationBounds.set(destinationBounds);
- mStartValue = startValue;
- mEndValue = endValue;
- addListener(this);
- addUpdateListener(this);
- mSurfaceControlTransactionFactory = SurfaceControl.Transaction::new;
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
+ private PipTransitionAnimator(SurfaceControl leash, @AnimationType int animationType,
+ Rect destinationBounds, T startValue, T endValue) {
+ mLeash = leash;
+ mAnimationType = animationType;
+ mDestinationBounds.set(destinationBounds);
+ mStartValue = startValue;
+ mEndValue = endValue;
+ addListener(this);
+ addUpdateListener(this);
+ mSurfaceControlTransactionFactory = SurfaceControl.Transaction::new;
+ mTransitionDirection = TRANSITION_DIRECTION_NONE;
}
@Override
@@ -173,7 +180,7 @@
mCurrentValue = mStartValue;
applySurfaceControlTransaction(mLeash, newSurfaceControlTransaction(), FRACTION_START);
if (mPipAnimationCallback != null) {
- mPipAnimationCallback.onPipAnimationStart(mWindowContainer, this);
+ mPipAnimationCallback.onPipAnimationStart(this);
}
}
@@ -189,14 +196,14 @@
final SurfaceControl.Transaction tx = newSurfaceControlTransaction();
applySurfaceControlTransaction(mLeash, tx, FRACTION_END);
if (mPipAnimationCallback != null) {
- mPipAnimationCallback.onPipAnimationEnd(mWindowContainer, tx, this);
+ mPipAnimationCallback.onPipAnimationEnd(tx, this);
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (mPipAnimationCallback != null) {
- mPipAnimationCallback.onPipAnimationCancel(mWindowContainer, this);
+ mPipAnimationCallback.onPipAnimationCancel(this);
}
}
@@ -211,8 +218,15 @@
return this;
}
- boolean shouldScheduleFinishPip() {
- return mScheduleFinishPip;
+ @TransitionDirection int getTransitionDirection() {
+ return mTransitionDirection;
+ }
+
+ PipTransitionAnimator<T> setTransitionDirection(@TransitionDirection int direction) {
+ if (direction != TRANSITION_DIRECTION_SAME) {
+ mTransitionDirection = direction;
+ }
+ return this;
}
T getStartValue() {
@@ -235,6 +249,10 @@
mCurrentValue = value;
}
+ boolean shouldApplyCornerRadius() {
+ return mTransitionDirection != TRANSITION_DIRECTION_TO_FULLSCREEN;
+ }
+
/**
* Updates the {@link #mEndValue}.
*
@@ -253,38 +271,46 @@
}
@VisibleForTesting
- void setSurfaceControlTransactionFactory(SurfaceControlTransactionFactory factory) {
+ void setSurfaceControlTransactionFactory(
+ PipSurfaceTransactionHelper.SurfaceControlTransactionFactory factory) {
mSurfaceControlTransactionFactory = factory;
}
+ PipSurfaceTransactionHelper getSurfaceTransactionHelper() {
+ return mSurfaceTransactionHelper;
+ }
+
+ void setSurfaceTransactionHelper(PipSurfaceTransactionHelper helper) {
+ mSurfaceTransactionHelper = helper;
+ }
+
abstract void applySurfaceControlTransaction(SurfaceControl leash,
SurfaceControl.Transaction tx, float fraction);
- static PipTransitionAnimator<Float> ofAlpha(IWindowContainer wc, boolean scheduleFinishPip,
+ static PipTransitionAnimator<Float> ofAlpha(SurfaceControl leash,
Rect destinationBounds, float startValue, float endValue) {
- return new PipTransitionAnimator<Float>(wc, scheduleFinishPip, ANIM_TYPE_ALPHA,
+ return new PipTransitionAnimator<Float>(leash, ANIM_TYPE_ALPHA,
destinationBounds, startValue, endValue) {
@Override
void applySurfaceControlTransaction(SurfaceControl leash,
SurfaceControl.Transaction tx, float fraction) {
final float alpha = getStartValue() * (1 - fraction) + getEndValue() * fraction;
setCurrentValue(alpha);
- tx.setAlpha(leash, alpha);
+ getSurfaceTransactionHelper().alpha(tx, leash, alpha);
if (Float.compare(fraction, FRACTION_START) == 0) {
- // Ensure the start condition
- final Rect bounds = getDestinationBounds();
- tx.setPosition(leash, bounds.left, bounds.top)
- .setWindowCrop(leash, bounds.width(), bounds.height());
+ getSurfaceTransactionHelper()
+ .crop(tx, leash, getDestinationBounds())
+ .round(tx, leash, shouldApplyCornerRadius());
}
tx.apply();
}
};
}
- static PipTransitionAnimator<Rect> ofBounds(IWindowContainer wc, boolean scheduleFinishPip,
+ static PipTransitionAnimator<Rect> ofBounds(SurfaceControl leash,
Rect startValue, Rect endValue) {
// construct new Rect instances in case they are recycled
- return new PipTransitionAnimator<Rect>(wc, scheduleFinishPip, ANIM_TYPE_BOUNDS,
+ return new PipTransitionAnimator<Rect>(leash, ANIM_TYPE_BOUNDS,
endValue, new Rect(startValue), new Rect(endValue)) {
private final Rect mTmpRect = new Rect();
@@ -303,19 +329,16 @@
getCastedFractionValue(start.right, end.right, fraction),
getCastedFractionValue(start.bottom, end.bottom, fraction));
setCurrentValue(mTmpRect);
- tx.setPosition(leash, mTmpRect.left, mTmpRect.top)
- .setWindowCrop(leash, mTmpRect.width(), mTmpRect.height());
+ getSurfaceTransactionHelper().crop(tx, leash, mTmpRect);
if (Float.compare(fraction, FRACTION_START) == 0) {
// Ensure the start condition
- tx.setAlpha(leash, 1f);
+ getSurfaceTransactionHelper()
+ .alpha(tx, leash, 1f)
+ .round(tx, leash, shouldApplyCornerRadius());
}
tx.apply();
}
};
}
}
-
- interface SurfaceControlTransactionFactory {
- SurfaceControl.Transaction getTransaction();
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java b/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java
index fb348f4..88491b7 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipBoundsHandler.java
@@ -67,7 +67,7 @@
private ComponentName mLastPipComponentName;
private float mReentrySnapFraction = INVALID_SNAP_FRACTION;
- private Size mReentrySize = null;
+ private Size mReentrySize;
private float mDefaultAspectRatio;
private float mMinAspectRatio;
@@ -77,6 +77,7 @@
private int mDefaultMinSize;
private Point mScreenEdgeInsets;
private int mCurrentMinSize;
+ private Size mOverrideMinimalSize;
private boolean mIsImeShowing;
private int mImeHeight;
@@ -226,11 +227,14 @@
/**
* @return {@link Rect} of the destination PiP window bounds.
*/
- Rect getDestinationBounds(float aspectRatio, Rect bounds) {
+ Rect getDestinationBounds(float aspectRatio, Rect bounds, Size minimalSize) {
final Rect destinationBounds;
final Rect defaultBounds = getDefaultBounds(mReentrySnapFraction, mReentrySize);
if (bounds == null) {
destinationBounds = new Rect(defaultBounds);
+ if (mReentrySnapFraction == INVALID_SNAP_FRACTION && mReentrySize == null) {
+ mOverrideMinimalSize = minimalSize;
+ }
} else {
destinationBounds = new Rect(bounds);
}
@@ -335,7 +339,6 @@
*/
private void transformBoundsToAspectRatio(Rect stackBounds, float aspectRatio,
boolean useCurrentMinEdgeSize) {
-
// Save the snap fraction and adjust the size based on the new aspect ratio.
final float snapFraction = mSnapAlgorithm.getSnapFraction(stackBounds,
getMovementBounds(stackBounds));
@@ -354,10 +357,38 @@
final int left = (int) (stackBounds.centerX() - size.getWidth() / 2f);
final int top = (int) (stackBounds.centerY() - size.getHeight() / 2f);
stackBounds.set(left, top, left + size.getWidth(), top + size.getHeight());
+ // apply the override minimal size if applicable, this minimal size is specified by app
+ if (mOverrideMinimalSize != null) {
+ transformBoundsToMinimalSize(stackBounds, aspectRatio, mOverrideMinimalSize);
+ }
mSnapAlgorithm.applySnapFraction(stackBounds, getMovementBounds(stackBounds), snapFraction);
}
/**
+ * Transforms a given bounds to meet the minimal size constraints.
+ * This function assumes the given {@param stackBounds} qualifies {@param aspectRatio}.
+ */
+ private void transformBoundsToMinimalSize(Rect stackBounds, float aspectRatio,
+ Size minimalSize) {
+ if (minimalSize == null) return;
+ final Size adjustedMinimalSize;
+ final float minimalSizeAspectRatio =
+ minimalSize.getWidth() / (float) minimalSize.getHeight();
+ if (minimalSizeAspectRatio > aspectRatio) {
+ // minimal size is wider, fixed the width and increase the height
+ adjustedMinimalSize = new Size(
+ minimalSize.getWidth(), (int) (minimalSize.getWidth() / aspectRatio));
+ } else {
+ adjustedMinimalSize = new Size(
+ (int) (minimalSize.getHeight() * aspectRatio), minimalSize.getHeight());
+ }
+ final Rect containerBounds = new Rect(stackBounds);
+ Gravity.apply(mDefaultStackGravity,
+ adjustedMinimalSize.getWidth(), adjustedMinimalSize.getHeight(),
+ containerBounds, stackBounds);
+ }
+
+ /**
* @return the default bounds to show the PIP, if a {@param snapFraction} and {@param size} are
* provided, then it will apply the default bounds to the provided snap fraction and size.
*/
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipSurfaceTransactionHelper.java b/packages/SystemUI/src/com/android/systemui/pip/PipSurfaceTransactionHelper.java
new file mode 100644
index 0000000..21f9301
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipSurfaceTransactionHelper.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2020 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.pip;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Rect;
+import android.view.SurfaceControl;
+
+import com.android.systemui.R;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+/**
+ * Abstracts the common operations on {@link SurfaceControl.Transaction} for PiP transition.
+ */
+@Singleton
+public class PipSurfaceTransactionHelper {
+
+ private final boolean mEnableCornerRadius;
+ private final int mCornerRadius;
+
+ @Inject
+ public PipSurfaceTransactionHelper(Context context) {
+ final Resources res = context.getResources();
+ mEnableCornerRadius = res.getBoolean(R.bool.config_pipEnableRoundCorner);
+ mCornerRadius = res.getDimensionPixelSize(R.dimen.pip_corner_radius);
+ }
+
+ /**
+ * Operates the alpha on a given transaction and leash
+ * @return same {@link PipSurfaceTransactionHelper} instance for method chaining
+ */
+ PipSurfaceTransactionHelper alpha(SurfaceControl.Transaction tx, SurfaceControl leash,
+ float alpha) {
+ tx.setAlpha(leash, alpha);
+ return this;
+ }
+
+ /**
+ * Operates the crop (and position) on a given transaction and leash
+ * @return same {@link PipSurfaceTransactionHelper} instance for method chaining
+ */
+ PipSurfaceTransactionHelper crop(SurfaceControl.Transaction tx, SurfaceControl leash,
+ Rect destinationBounds) {
+ tx.setWindowCrop(leash, destinationBounds.width(), destinationBounds.height())
+ .setPosition(leash, destinationBounds.left, destinationBounds.top);
+ return this;
+ }
+
+ /**
+ * Operates the round corner radius on a given transaction and leash
+ * @return same {@link PipSurfaceTransactionHelper} instance for method chaining
+ */
+ PipSurfaceTransactionHelper round(SurfaceControl.Transaction tx, SurfaceControl leash,
+ boolean applyCornerRadius) {
+ if (mEnableCornerRadius) {
+ tx.setCornerRadius(leash, applyCornerRadius ? mCornerRadius : 0);
+ }
+ return this;
+ }
+
+ interface SurfaceControlTransactionFactory {
+ SurfaceControl.Transaction getTransaction();
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/PipTaskOrganizer.java b/packages/SystemUI/src/com/android/systemui/pip/PipTaskOrganizer.java
index 836485a..dc1b5d7 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/PipTaskOrganizer.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/PipTaskOrganizer.java
@@ -18,7 +18,10 @@
import static com.android.systemui.pip.PipAnimationController.ANIM_TYPE_ALPHA;
import static com.android.systemui.pip.PipAnimationController.ANIM_TYPE_BOUNDS;
-import static com.android.systemui.pip.PipAnimationController.DURATION_DEFAULT_MS;
+import static com.android.systemui.pip.PipAnimationController.TRANSITION_DIRECTION_NONE;
+import static com.android.systemui.pip.PipAnimationController.TRANSITION_DIRECTION_SAME;
+import static com.android.systemui.pip.PipAnimationController.TRANSITION_DIRECTION_TO_FULLSCREEN;
+import static com.android.systemui.pip.PipAnimationController.TRANSITION_DIRECTION_TO_PIP;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -27,20 +30,29 @@
import android.app.ITaskOrganizerController;
import android.app.PictureInPictureParams;
import android.content.Context;
+import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.os.Handler;
+import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
-import android.view.DisplayInfo;
+import android.util.Size;
import android.view.ITaskOrganizer;
import android.view.IWindowContainer;
import android.view.SurfaceControl;
import android.view.WindowContainerTransaction;
+import com.android.internal.os.SomeArgs;
+import com.android.systemui.R;
+import com.android.systemui.pip.phone.PipUpdateThread;
+
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
+import java.util.function.Consumer;
/**
* Manages PiP tasks such as resize and offset.
@@ -56,19 +68,27 @@
public class PipTaskOrganizer extends ITaskOrganizer.Stub {
private static final String TAG = PipTaskOrganizer.class.getSimpleName();
+ private static final int MSG_RESIZE_IMMEDIATE = 1;
+ private static final int MSG_RESIZE_ANIMATE = 2;
+ private static final int MSG_OFFSET_ANIMATE = 3;
+ private static final int MSG_FINISH_RESIZE = 4;
+
private final Handler mMainHandler;
+ private final Handler mUpdateHandler;
private final ITaskOrganizerController mTaskOrganizerController;
private final PipBoundsHandler mPipBoundsHandler;
private final PipAnimationController mPipAnimationController;
private final List<PipTransitionCallback> mPipTransitionCallbacks = new ArrayList<>();
- private final Rect mDisplayBounds = new Rect();
private final Rect mLastReportedBounds = new Rect();
+ private final int mEnterExitAnimationDuration;
+ private final PipSurfaceTransactionHelper mSurfaceTransactionHelper;
+ private final Map<IBinder, Rect> mBoundsToRestore = new HashMap<>();
+ // These callbacks are called on the update thread
private final PipAnimationController.PipAnimationCallback mPipAnimationCallback =
new PipAnimationController.PipAnimationCallback() {
@Override
- public void onPipAnimationStart(IWindowContainer wc,
- PipAnimationController.PipTransitionAnimator animator) {
+ public void onPipAnimationStart(PipAnimationController.PipTransitionAnimator animator) {
mMainHandler.post(() -> {
for (int i = mPipTransitionCallbacks.size() - 1; i >= 0; i--) {
final PipTransitionCallback callback = mPipTransitionCallbacks.get(i);
@@ -78,7 +98,7 @@
}
@Override
- public void onPipAnimationEnd(IWindowContainer wc, SurfaceControl.Transaction tx,
+ public void onPipAnimationEnd(SurfaceControl.Transaction tx,
PipAnimationController.PipTransitionAnimator animator) {
mMainHandler.post(() -> {
for (int i = mPipTransitionCallbacks.size() - 1; i >= 0; i--) {
@@ -86,13 +106,11 @@
callback.onPipTransitionFinished();
}
});
- final Rect destinationBounds = animator.getDestinationBounds();
- finishResizeInternal(destinationBounds, wc, tx, animator.shouldScheduleFinishPip());
+ finishResize(tx, animator.getDestinationBounds(), animator.getTransitionDirection());
}
@Override
- public void onPipAnimationCancel(IWindowContainer wc,
- PipAnimationController.PipTransitionAnimator animator) {
+ public void onPipAnimationCancel(PipAnimationController.PipTransitionAnimator animator) {
mMainHandler.post(() -> {
for (int i = mPipTransitionCallbacks.size() - 1; i >= 0; i--) {
final PipTransitionCallback callback = mPipTransitionCallbacks.get(i);
@@ -102,28 +120,78 @@
}
};
- private ActivityManager.RunningTaskInfo mTaskInfo;
- private @PipAnimationController.AnimationType int mOneShotAnimationType = ANIM_TYPE_BOUNDS;
+ @SuppressWarnings("unchecked")
+ private Handler.Callback mUpdateCallbacks = (msg) -> {
+ SomeArgs args = (SomeArgs) msg.obj;
+ Consumer<Rect> updateBoundsCallback = (Consumer<Rect>) args.arg1;
+ switch (msg.what) {
+ case MSG_RESIZE_IMMEDIATE: {
+ Rect toBounds = (Rect) args.arg2;
+ resizePip(toBounds);
+ if (updateBoundsCallback != null) {
+ updateBoundsCallback.accept(toBounds);
+ }
+ break;
+ }
+ case MSG_RESIZE_ANIMATE: {
+ Rect currentBounds = (Rect) args.arg2;
+ Rect toBounds = (Rect) args.arg3;
+ int duration = args.argi2;
+ animateResizePip(currentBounds, toBounds, args.argi1 /* direction */, duration);
+ if (updateBoundsCallback != null) {
+ updateBoundsCallback.accept(toBounds);
+ }
+ break;
+ }
+ case MSG_OFFSET_ANIMATE: {
+ Rect originalBounds = (Rect) args.arg2;
+ final int offset = args.argi1;
+ final int duration = args.argi2;
+ offsetPip(originalBounds, 0 /* xOffset */, offset, duration);
+ Rect toBounds = new Rect(originalBounds);
+ toBounds.offset(0, offset);
+ if (updateBoundsCallback != null) {
+ updateBoundsCallback.accept(toBounds);
+ }
+ break;
+ }
+ case MSG_FINISH_RESIZE: {
+ SurfaceControl.Transaction tx = (SurfaceControl.Transaction) args.arg2;
+ Rect toBounds = (Rect) args.arg3;
+ finishResize(tx, toBounds, args.argi1 /* direction */);
+ if (updateBoundsCallback != null) {
+ updateBoundsCallback.accept(toBounds);
+ }
+ break;
+ }
+ }
+ args.recycle();
+ return true;
+ };
- public PipTaskOrganizer(Context context, @NonNull PipBoundsHandler boundsHandler) {
+ private ActivityManager.RunningTaskInfo mTaskInfo;
+ private IWindowContainer mToken;
+ private SurfaceControl mLeash;
+ private boolean mInPip;
+ private @PipAnimationController.AnimationType int mOneShotAnimationType = ANIM_TYPE_BOUNDS;
+ private PipSurfaceTransactionHelper.SurfaceControlTransactionFactory
+ mSurfaceControlTransactionFactory;
+
+ public PipTaskOrganizer(Context context, @NonNull PipBoundsHandler boundsHandler,
+ @NonNull PipSurfaceTransactionHelper surfaceTransactionHelper) {
mMainHandler = new Handler(Looper.getMainLooper());
+ mUpdateHandler = new Handler(PipUpdateThread.get().getLooper(), mUpdateCallbacks);
mTaskOrganizerController = ActivityTaskManager.getTaskOrganizerController();
mPipBoundsHandler = boundsHandler;
- mPipAnimationController = new PipAnimationController(context);
+ mEnterExitAnimationDuration = context.getResources()
+ .getInteger(R.integer.config_pipResizeAnimationDuration);
+ mSurfaceTransactionHelper = surfaceTransactionHelper;
+ mPipAnimationController = new PipAnimationController(context, surfaceTransactionHelper);
+ mSurfaceControlTransactionFactory = SurfaceControl.Transaction::new;
}
- /**
- * Offset the PiP window, animate if the given duration is not {@link #DURATION_NONE}
- */
- public void offsetPinnedStack(Rect originalBounds, int xOffset, int yOffset, int durationMs) {
- if (mTaskInfo == null) {
- Log.w(TAG, "mTaskInfo is not set");
- return;
- }
- final Rect destinationBounds = new Rect(originalBounds);
- destinationBounds.offset(xOffset, yOffset);
- animateResizePipInternal(mTaskInfo.token, false /* scheduleFinishPip*/,
- originalBounds, destinationBounds, durationMs);
+ public Handler getUpdateHandler() {
+ return mUpdateHandler;
}
/**
@@ -135,66 +203,39 @@
/**
* Sets the preferred animation type for one time.
- * This is typically used to set the animation type to {@link #ANIM_TYPE_ALPHA}.
+ * This is typically used to set the animation type to
+ * {@link PipAnimationController#ANIM_TYPE_ALPHA}.
*/
public void setOneShotAnimationType(@PipAnimationController.AnimationType int animationType) {
mOneShotAnimationType = animationType;
}
- /**
- * Updates the display dimension with given {@link DisplayInfo}
- */
- public void onDisplayInfoChanged(DisplayInfo displayInfo) {
- final Rect newDisplayBounds = new Rect(0, 0,
- displayInfo.logicalWidth, displayInfo.logicalHeight);
- if (!mDisplayBounds.equals(newDisplayBounds)) {
- // Updates the exiting PiP animation in case the screen rotation changes in the middle.
- // It's a legit case that PiP window is in portrait mode on home screen and
- // the application requests landscape onces back to fullscreen mode.
- final PipAnimationController.PipTransitionAnimator animator =
- mPipAnimationController.getCurrentAnimator();
- if (animator != null
- && animator.getAnimationType() == ANIM_TYPE_BOUNDS
- && animator.getDestinationBounds().equals(mDisplayBounds)) {
- animator.updateEndValue(newDisplayBounds);
- animator.setDestinationBounds(newDisplayBounds);
- }
- }
- mDisplayBounds.set(newDisplayBounds);
- }
-
- /**
- * Callback to issue the final {@link WindowContainerTransaction} on end of movements.
- * @param destinationBounds the final bounds.
- */
- public void onMotionMovementEnd(Rect destinationBounds) {
- try {
- mLastReportedBounds.set(destinationBounds);
- final WindowContainerTransaction wct = new WindowContainerTransaction();
- wct.setBounds(mTaskInfo.token, destinationBounds);
- mTaskOrganizerController.applyContainerTransaction(wct, null /* ITaskOrganizer */);
- } catch (RemoteException e) {
- Log.w(TAG, "Failed to apply window container transaction", e);
- }
- }
-
@Override
public void taskAppeared(ActivityManager.RunningTaskInfo info) {
Objects.requireNonNull(info, "Requires RunningTaskInfo");
final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
- getAspectRatioOrDefault(info.pictureInPictureParams), null /* bounds */);
+ getAspectRatioOrDefault(info.pictureInPictureParams),
+ null /* bounds */, getMinimalSize(info.topActivityInfo));
Objects.requireNonNull(destinationBounds, "Missing destination bounds");
mTaskInfo = info;
+ mToken = mTaskInfo.token;
+ mInPip = true;
+ try {
+ mLeash = mToken.getLeash();
+ } catch (RemoteException e) {
+ throw new RuntimeException("Unable to get leash", e);
+ }
+ final Rect currentBounds = mTaskInfo.configuration.windowConfiguration.getBounds();
+ mBoundsToRestore.put(mToken.asBinder(), currentBounds);
if (mOneShotAnimationType == ANIM_TYPE_BOUNDS) {
- final Rect currentBounds = mTaskInfo.configuration.windowConfiguration.getBounds();
- animateResizePipInternal(mTaskInfo.token, true /* scheduleFinishPip */,
- currentBounds, destinationBounds, DURATION_DEFAULT_MS);
+ scheduleAnimateResizePip(currentBounds, destinationBounds,
+ TRANSITION_DIRECTION_TO_PIP, mEnterExitAnimationDuration, null);
} else if (mOneShotAnimationType == ANIM_TYPE_ALPHA) {
- mMainHandler.post(() -> mPipAnimationController
- .getAnimator(mTaskInfo.token, true /* scheduleFinishPip */,
- destinationBounds, 0f, 1f)
+ mUpdateHandler.post(() -> mPipAnimationController
+ .getAnimator(mLeash, destinationBounds, 0f, 1f)
+ .setTransitionDirection(TRANSITION_DIRECTION_TO_PIP)
.setPipAnimationCallback(mPipAnimationCallback)
- .setDuration(DURATION_DEFAULT_MS)
+ .setDuration(mEnterExitAnimationDuration)
.start());
mOneShotAnimationType = ANIM_TYPE_BOUNDS;
} else {
@@ -203,14 +244,17 @@
}
@Override
- public void taskVanished(IWindowContainer token) {
+ public void taskVanished(ActivityManager.RunningTaskInfo info) {
+ IWindowContainer token = info.token;
Objects.requireNonNull(token, "Requires valid IWindowContainer");
- if (token.asBinder() != mTaskInfo.token.asBinder()) {
+ if (token.asBinder() != mToken.asBinder()) {
Log.wtf(TAG, "Unrecognized token: " + token);
return;
}
- animateResizePipInternal(token, false /* scheduleFinishPip */,
- mLastReportedBounds, mDisplayBounds, DURATION_DEFAULT_MS);
+ final Rect boundsToRestore = mBoundsToRestore.remove(token.asBinder());
+ scheduleAnimateResizePip(mLastReportedBounds, boundsToRestore,
+ TRANSITION_DIRECTION_TO_FULLSCREEN, mEnterExitAnimationDuration, null);
+ mInPip = false;
}
@Override
@@ -225,9 +269,10 @@
return;
}
final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
- getAspectRatioOrDefault(newParams), null /* bounds */);
+ getAspectRatioOrDefault(newParams),
+ null /* bounds */, getMinimalSize(info.topActivityInfo));
Objects.requireNonNull(destinationBounds, "Missing destination bounds");
- animateResizePip(destinationBounds, DURATION_DEFAULT_MS);
+ scheduleAnimateResizePip(destinationBounds, mEnterExitAnimationDuration, null);
}
/**
@@ -243,101 +288,165 @@
}
/**
- * Directly perform manipulation/resize on the leash. This will not perform any
- * {@link WindowContainerTransaction} until {@link #finishResize} is called.
+ * Animates resizing of the pinned stack given the duration.
*/
- public void resizePip(Rect destinationBounds) {
- Objects.requireNonNull(mTaskInfo, "Requires valid IWindowContainer");
- resizePipInternal(mTaskInfo.token, destinationBounds);
+ public void scheduleAnimateResizePip(Rect toBounds, int duration,
+ Consumer<Rect> updateBoundsCallback) {
+ scheduleAnimateResizePip(mLastReportedBounds, toBounds,
+ TRANSITION_DIRECTION_NONE, duration, updateBoundsCallback);
}
- private void resizePipInternal(IWindowContainer wc,
- Rect destinationBounds) {
- Objects.requireNonNull(mTaskInfo, "Requires valid IWindowContainer");
- try {
- // Could happen when dismissPip
- if (wc == null || wc.getLeash() == null) {
- Log.w(TAG, "Abort animation, invalid leash");
- return;
- }
- final SurfaceControl leash = wc.getLeash();
- new SurfaceControl.Transaction()
- .setPosition(leash, destinationBounds.left, destinationBounds.top)
- .setWindowCrop(leash, destinationBounds.width(), destinationBounds.height())
- .apply();
- } catch (RemoteException e) {
- Log.w(TAG, "Abort animation, invalid window container", e);
- } catch (Exception e) {
- Log.e(TAG, "Should not reach here, terrible thing happened", e);
+ private void scheduleAnimateResizePip(Rect currentBounds, Rect destinationBounds,
+ @PipAnimationController.TransitionDirection int direction, int durationMs,
+ Consumer<Rect> updateBoundsCallback) {
+ if (!mInPip) {
+ // Ignore animation when we are no longer in PIP
+ return;
}
+ SomeArgs args = SomeArgs.obtain();
+ args.arg1 = updateBoundsCallback;
+ args.arg2 = currentBounds;
+ args.arg3 = destinationBounds;
+ args.argi1 = direction;
+ args.argi2 = durationMs;
+ mUpdateHandler.sendMessage(mUpdateHandler.obtainMessage(MSG_RESIZE_ANIMATE, args));
}
/**
- * Finish a intermediate resize operation. This is expected to be called after
- * {@link #resizePip}.
+ * Directly perform manipulation/resize on the leash. This will not perform any
+ * {@link WindowContainerTransaction} until {@link #scheduleFinishResizePip} is called.
*/
- public void finishResize(Rect destinationBounds) {
- try {
- final IWindowContainer wc = mTaskInfo.token;
- SurfaceControl.Transaction tx = new SurfaceControl.Transaction()
- .setPosition(wc.getLeash(), destinationBounds.left,
- destinationBounds.top)
- .setWindowCrop(wc.getLeash(), destinationBounds.width(),
- destinationBounds.height());
- finishResizeInternal(destinationBounds, wc, tx, false);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to obtain leash");
- }
+ public void scheduleResizePip(Rect toBounds, Consumer<Rect> updateBoundsCallback) {
+ SomeArgs args = SomeArgs.obtain();
+ args.arg1 = updateBoundsCallback;
+ args.arg2 = toBounds;
+ mUpdateHandler.sendMessage(mUpdateHandler.obtainMessage(MSG_RESIZE_IMMEDIATE, args));
}
- private void finishResizeInternal(Rect destinationBounds, IWindowContainer wc,
- SurfaceControl.Transaction tx, boolean shouldScheduleFinishPip) {
+ /**
+ * Finish an intermediate resize operation. This is expected to be called after
+ * {@link #scheduleResizePip}.
+ */
+ public void scheduleFinishResizePip(Rect destinationBounds) {
+ final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
+ mSurfaceTransactionHelper
+ .crop(tx, mLeash, destinationBounds)
+ .round(tx, mLeash, mInPip);
+ scheduleFinishResizePip(tx, destinationBounds, TRANSITION_DIRECTION_NONE, null);
+ }
+
+ private void scheduleFinishResizePip(SurfaceControl.Transaction tx,
+ Rect destinationBounds, @PipAnimationController.TransitionDirection int direction,
+ Consumer<Rect> updateBoundsCallback) {
+ SomeArgs args = SomeArgs.obtain();
+ args.arg1 = updateBoundsCallback;
+ args.arg2 = tx;
+ args.arg3 = destinationBounds;
+ args.argi1 = direction;
+ mUpdateHandler.sendMessage(mUpdateHandler.obtainMessage(MSG_FINISH_RESIZE, args));
+ }
+
+ /**
+ * Offset the PiP window by a given offset on Y-axis, triggered also from screen rotation.
+ */
+ public void scheduleOffsetPip(Rect originalBounds, int offset, int duration,
+ Consumer<Rect> updateBoundsCallback) {
+ if (!mInPip) {
+ // Ignore offsets when we are no longer in PIP
+ return;
+ }
+ SomeArgs args = SomeArgs.obtain();
+ args.arg1 = updateBoundsCallback;
+ args.arg2 = originalBounds;
+ // offset would be zero if triggered from screen rotation.
+ args.argi1 = offset;
+ args.argi2 = duration;
+ mUpdateHandler.sendMessage(mUpdateHandler.obtainMessage(MSG_OFFSET_ANIMATE, args));
+ }
+
+ private void offsetPip(Rect originalBounds, int xOffset, int yOffset, int durationMs) {
+ if (Looper.myLooper() != mUpdateHandler.getLooper()) {
+ throw new RuntimeException("Callers should call scheduleOffsetPip() instead of this "
+ + "directly");
+ }
+ if (mTaskInfo == null) {
+ Log.w(TAG, "mTaskInfo is not set");
+ return;
+ }
+ final Rect destinationBounds = new Rect(originalBounds);
+ destinationBounds.offset(xOffset, yOffset);
+ animateResizePip(originalBounds, destinationBounds, TRANSITION_DIRECTION_SAME, durationMs);
+ }
+
+ private void resizePip(Rect destinationBounds) {
+ if (Looper.myLooper() != mUpdateHandler.getLooper()) {
+ throw new RuntimeException("Callers should call scheduleResizePip() instead of this "
+ + "directly");
+ }
+ // Could happen when dismissPip
+ if (mToken == null || mLeash == null) {
+ Log.w(TAG, "Abort animation, invalid leash");
+ return;
+ }
+ final SurfaceControl.Transaction tx = mSurfaceControlTransactionFactory.getTransaction();
+ mSurfaceTransactionHelper
+ .crop(tx, mLeash, destinationBounds)
+ .round(tx, mLeash, mInPip);
+ tx.apply();
+ }
+
+ private void finishResize(SurfaceControl.Transaction tx, Rect destinationBounds,
+ @PipAnimationController.TransitionDirection int direction) {
+ if (Looper.myLooper() != mUpdateHandler.getLooper()) {
+ throw new RuntimeException("Callers should call scheduleResizePip() instead of this "
+ + "directly");
+ }
mLastReportedBounds.set(destinationBounds);
try {
+ // If we are animating to fullscreen, then we need to reset the override bounds on the
+ // task to ensure that the task "matches" the parent's bounds
+ Rect taskBounds = direction == TRANSITION_DIRECTION_TO_FULLSCREEN
+ ? null
+ : destinationBounds;
final WindowContainerTransaction wct = new WindowContainerTransaction();
- if (shouldScheduleFinishPip) {
- wct.scheduleFinishEnterPip(wc, destinationBounds);
+ if (direction == TRANSITION_DIRECTION_TO_PIP) {
+ wct.scheduleFinishEnterPip(mToken, taskBounds);
} else {
- wct.setBounds(wc, destinationBounds);
+ wct.setBounds(mToken, taskBounds);
}
- wct.setBoundsChangeTransaction(mTaskInfo.token, tx);
+ wct.setBoundsChangeTransaction(mToken, tx);
mTaskOrganizerController.applyContainerTransaction(wct, null /* ITaskOrganizer */);
} catch (RemoteException e) {
Log.e(TAG, "Failed to apply container transaction", e);
}
}
- /**
- * Animates resizing of the pinned stack given the duration.
- */
- public void animateResizePip(Rect destinationBounds, int durationMs) {
- Objects.requireNonNull(mTaskInfo, "Requires valid IWindowContainer");
- animateResizePipInternal(mTaskInfo.token, false, mLastReportedBounds,
- destinationBounds, durationMs);
- }
-
- private void animateResizePipInternal(IWindowContainer wc, boolean scheduleFinishPip,
- Rect currentBounds, Rect destinationBounds, int durationMs) {
- try {
- // Could happen when dismissPip
- if (wc == null || wc.getLeash() == null) {
- Log.w(TAG, "Abort animation, invalid leash");
- return;
- }
- final SurfaceControl leash = wc.getLeash();
-
- mMainHandler.post(() -> mPipAnimationController
- .getAnimator(wc, scheduleFinishPip, currentBounds, destinationBounds)
- .setPipAnimationCallback(mPipAnimationCallback)
- .setDuration(durationMs)
- .start());
- } catch (RemoteException e) {
- Log.w(TAG, "Abort animation, invalid window container", e);
- } catch (Exception e) {
- Log.e(TAG, "Should not reach here, terrible thing happened", e);
+ private void animateResizePip(Rect currentBounds, Rect destinationBounds,
+ @PipAnimationController.TransitionDirection int direction, int durationMs) {
+ if (Looper.myLooper() != mUpdateHandler.getLooper()) {
+ throw new RuntimeException("Callers should call scheduleAnimateResizePip() instead of "
+ + "this directly");
}
+ // Could happen when dismissPip
+ if (mToken == null || mLeash == null) {
+ Log.w(TAG, "Abort animation, invalid leash");
+ return;
+ }
+ mUpdateHandler.post(() -> mPipAnimationController
+ .getAnimator(mLeash, currentBounds, destinationBounds)
+ .setTransitionDirection(direction)
+ .setPipAnimationCallback(mPipAnimationCallback)
+ .setDuration(durationMs)
+ .start());
}
+ private Size getMinimalSize(ActivityInfo activityInfo) {
+ if (activityInfo == null || activityInfo.windowLayout == null) {
+ return null;
+ }
+ final ActivityInfo.WindowLayout windowLayout = activityInfo.windowLayout;
+ return new Size(windowLayout.minWidth, windowLayout.minHeight);
+ }
private float getAspectRatioOrDefault(@Nullable PictureInPictureParams params) {
return params == null
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipAppOpsListener.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipAppOpsListener.java
index b09d6e1..7dfd99c 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipAppOpsListener.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipAppOpsListener.java
@@ -44,7 +44,7 @@
try {
// Dismiss the PiP once the user disables the app ops setting for that package
final Pair<ComponentName, Integer> topPipActivityInfo =
- PipUtils.getTopPinnedActivity(mContext, mActivityManager);
+ PipUtils.getTopPipActivity(mContext, mActivityManager);
if (topPipActivityInfo.first != null) {
final ApplicationInfo appInfo = mContext.getPackageManager()
.getApplicationInfoAsUser(packageName, 0, topPipActivityInfo.second);
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
index 4b97d13..020627a 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipManager.java
@@ -42,6 +42,7 @@
import com.android.systemui.pip.BasePipManager;
import com.android.systemui.pip.PipBoundsHandler;
import com.android.systemui.pip.PipSnapAlgorithm;
+import com.android.systemui.pip.PipSurfaceTransactionHelper;
import com.android.systemui.pip.PipTaskOrganizer;
import com.android.systemui.shared.recents.IPinnedStackAnimationListener;
import com.android.systemui.shared.system.ActivityManagerWrapper;
@@ -115,7 +116,7 @@
@Override
public void onActivityUnpinned() {
- final Pair<ComponentName, Integer> topPipActivityInfo = PipUtils.getTopPinnedActivity(
+ final Pair<ComponentName, Integer> topPipActivityInfo = PipUtils.getTopPipActivity(
mContext, mActivityManager);
final ComponentName topActivity = topPipActivityInfo.first;
mMenuController.onActivityUnpinned();
@@ -128,7 +129,12 @@
}
@Override
- public void onPinnedActivityRestartAttempt(boolean clearedTask) {
+ public void onActivityRestartAttempt(ActivityManager.RunningTaskInfo task,
+ boolean homeTaskVisible, boolean clearedTask) {
+ if (task.configuration.windowConfiguration.getWindowingMode()
+ != WINDOWING_MODE_PINNED) {
+ return;
+ }
mTouchHandler.getMotionHelper().expandPip(clearedTask /* skipAnimation */);
}
};
@@ -185,10 +191,7 @@
@Override
public void onDisplayInfoChanged(DisplayInfo displayInfo) {
- mHandler.post(() -> {
- mPipBoundsHandler.onDisplayInfoChanged(displayInfo);
- mPipTaskOrganizer.onDisplayInfoChanged(displayInfo);
- });
+ mHandler.post(() -> mPipBoundsHandler.onDisplayInfoChanged(displayInfo));
}
@Override
@@ -208,7 +211,8 @@
FloatingContentCoordinator floatingContentCoordinator,
DeviceConfigProxy deviceConfig,
PipBoundsHandler pipBoundsHandler,
- PipSnapAlgorithm pipSnapAlgorithm) {
+ PipSnapAlgorithm pipSnapAlgorithm,
+ PipSurfaceTransactionHelper surfaceTransactionHelper) {
mContext = context;
mActivityManager = ActivityManager.getService();
@@ -222,7 +226,8 @@
final IActivityTaskManager activityTaskManager = ActivityTaskManager.getService();
mPipBoundsHandler = pipBoundsHandler;
- mPipTaskOrganizer = new PipTaskOrganizer(mContext, mPipBoundsHandler);
+ mPipTaskOrganizer = new PipTaskOrganizer(context, pipBoundsHandler,
+ surfaceTransactionHelper);
mPipTaskOrganizer.registerPipTransitionCallback(this);
mInputConsumerController = InputConsumerController.getPipInputConsumer();
mMediaController = new PipMediaController(context, mActivityManager, broadcastDispatcher);
@@ -235,6 +240,12 @@
mTouchHandler.getMotionHelper());
displayController.addDisplayChangingController(mRotationController);
+ // Ensure that we have the display info in case we get calls to update the bounds before the
+ // listener calls back
+ final DisplayInfo displayInfo = new DisplayInfo();
+ context.getDisplay().getDisplayInfo(displayInfo);
+ mPipBoundsHandler.onDisplayInfoChanged(displayInfo);
+
try {
ActivityTaskManager.getTaskOrganizerController().registerTaskOrganizer(
mPipTaskOrganizer, WINDOWING_MODE_PINNED);
@@ -352,7 +363,6 @@
mTouchHandler.onMovementBoundsChanged(mTmpInsetBounds, mTmpNormalBounds,
animatingBounds, fromImeAdjustment, fromShelfAdjustment,
mTmpDisplayInfo.rotation);
- mPipTaskOrganizer.onDisplayInfoChanged(mTmpDisplayInfo);
}
public void dump(PrintWriter pw) {
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMediaController.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMediaController.java
index e57b416..849a62a 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMediaController.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMediaController.java
@@ -231,7 +231,7 @@
*/
private void resolveActiveMediaController(List<MediaController> controllers) {
if (controllers != null) {
- final ComponentName topActivity = PipUtils.getTopPinnedActivity(mContext,
+ final ComponentName topActivity = PipUtils.getTopPipActivity(mContext,
mActivityManager).first;
if (topActivity != null) {
for (int i = 0; i < controllers.size(); i++) {
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
index fc04f79..2b9b171 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMenuActivity.java
@@ -569,7 +569,7 @@
private void showSettings() {
final Pair<ComponentName, Integer> topPipActivityInfo =
- PipUtils.getTopPinnedActivity(this, ActivityManager.getService());
+ PipUtils.getTopPipActivity(this, ActivityManager.getService());
if (topPipActivityInfo.first != null) {
final UserHandle user = UserHandle.of(topPipActivityInfo.second);
final Intent settingsIntent = new Intent(ACTION_PICTURE_IN_PICTURE_SETTINGS,
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
index fdaf66a..449a2bc 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipMotionHelper.java
@@ -28,16 +28,11 @@
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Debug;
-import android.os.Handler;
-import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
-import android.view.Choreographer;
import androidx.dynamicanimation.animation.SpringForce;
-import com.android.internal.graphics.SfVsyncFrameCallbackProvider;
-import com.android.internal.os.SomeArgs;
import com.android.systemui.pip.PipSnapAlgorithm;
import com.android.systemui.pip.PipTaskOrganizer;
import com.android.systemui.shared.system.WindowManagerWrapper;
@@ -47,11 +42,12 @@
import com.android.systemui.util.animation.PhysicsAnimator;
import java.io.PrintWriter;
+import java.util.function.Consumer;
/**
* A helper to animate and manipulate the PiP.
*/
-public class PipMotionHelper implements Handler.Callback, PipAppOpsListener.Callback,
+public class PipMotionHelper implements PipAppOpsListener.Callback,
FloatingContentCoordinator.FloatingContent {
private static final String TAG = "PipMotionHelper";
@@ -68,14 +64,9 @@
// The fraction of the stack height that the user has to drag offscreen to dismiss the PiP
private static final float DISMISS_OFFSCREEN_FRACTION = 0.3f;
- private static final int MSG_RESIZE_IMMEDIATE = 1;
- private static final int MSG_RESIZE_ANIMATE = 2;
- private static final int MSG_OFFSET_ANIMATE = 3;
-
private final Context mContext;
private final IActivityTaskManager mActivityTaskManager;
private final PipTaskOrganizer mPipTaskOrganizer;
- private final Handler mHandler;
private PipMenuActivityController mMenuController;
private PipSnapAlgorithm mSnapAlgorithm;
@@ -87,13 +78,10 @@
private final Rect mBounds = new Rect();
/** The bounds within which PIP's top-left coordinate is allowed to move. */
- private Rect mMovementBounds = new Rect();
+ private final Rect mMovementBounds = new Rect();
/** The region that all of PIP must stay within. */
- private Rect mFloatingAllowedArea = new Rect();
-
- private final SfVsyncFrameCallbackProvider mSfVsyncFrameProvider =
- new SfVsyncFrameCallbackProvider();
+ private final Rect mFloatingAllowedArea = new Rect();
/**
* Bounds that are animated using the physics animator.
@@ -101,7 +89,7 @@
private final Rect mAnimatedBounds = new Rect();
/** The destination bounds to which PIP is animating. */
- private Rect mAnimatingToBounds = new Rect();
+ private final Rect mAnimatingToBounds = new Rect();
/** Coordinator instance for resolving conflicts with other floating content. */
private FloatingContentCoordinator mFloatingContentCoordinator;
@@ -112,16 +100,11 @@
private PhysicsAnimator<Rect> mAnimatedBoundsPhysicsAnimator = PhysicsAnimator.getInstance(
mAnimatedBounds);
- /** Callback that re-sizes PIP to the animated bounds. */
- private final Choreographer.FrameCallback mResizePipVsyncCallback =
- l -> resizePipUnchecked(mAnimatedBounds);
-
/**
- * Update listener that posts a vsync frame callback to resize PIP to {@link #mAnimatedBounds}.
+ * Update listener that resizes the PIP to {@link #mAnimatedBounds}.
*/
- private final PhysicsAnimator.UpdateListener<Rect> mResizePipVsyncUpdateListener =
- (target, values) ->
- mSfVsyncFrameProvider.postFrameCallback(mResizePipVsyncCallback);
+ private final PhysicsAnimator.UpdateListener<Rect> mResizePipUpdateListener =
+ (target, values) -> resizePipUnchecked(mAnimatedBounds);
/** FlingConfig instances provided to PhysicsAnimator for fling gestures. */
private PhysicsAnimator.FlingConfig mFlingConfigX;
@@ -137,12 +120,13 @@
new PhysicsAnimator.SpringConfig(
SpringForce.STIFFNESS_LOW, SpringForce.DAMPING_RATIO_LOW_BOUNCY);
+ private final Consumer<Rect> mUpdateBoundsCallback = mBounds::set;
+
public PipMotionHelper(Context context, IActivityTaskManager activityTaskManager,
PipTaskOrganizer pipTaskOrganizer, PipMenuActivityController menuController,
PipSnapAlgorithm snapAlgorithm, FlingAnimationUtils flingAnimationUtils,
FloatingContentCoordinator floatingContentCoordinator) {
mContext = context;
- mHandler = new Handler(ForegroundThread.get().getLooper(), this);
mActivityTaskManager = activityTaskManager;
mPipTaskOrganizer = pipTaskOrganizer;
mMenuController = menuController;
@@ -234,7 +218,7 @@
}
cancelAnimations();
mMenuController.hideMenuWithoutResize();
- mHandler.post(() -> {
+ mPipTaskOrganizer.getUpdateHandler().post(() -> {
try {
mActivityTaskManager.dismissPip(!skipAnimation, EXPAND_STACK_TO_FULLSCREEN_DURATION);
} catch (RemoteException e) {
@@ -253,7 +237,7 @@
}
cancelAnimations();
mMenuController.hideMenuWithoutResize();
- mHandler.post(() -> {
+ mPipTaskOrganizer.getUpdateHandler().post(() -> {
try {
mActivityTaskManager.removeStacksInWindowingModes(
new int[]{ WINDOWING_MODE_PINNED });
@@ -406,17 +390,13 @@
* Animates the PiP to offset it from the IME or shelf.
*/
void animateToOffset(Rect originalBounds, int offset) {
+ if (DEBUG) {
+ Log.d(TAG, "animateToOffset: originalBounds=" + originalBounds + " offset=" + offset
+ + " callers=\n" + Debug.getCallers(5, " "));
+ }
cancelAnimations();
- adjustAndAnimatePipOffset(originalBounds, offset, SHIFT_DURATION);
- }
-
- private void adjustAndAnimatePipOffset(Rect originalBounds, int offset, int duration) {
- SomeArgs args = SomeArgs.obtain();
- args.arg1 = originalBounds;
- // offset would be zero if triggered from screen rotation.
- args.argi1 = offset;
- args.argi2 = duration;
- mHandler.sendMessage(mHandler.obtainMessage(MSG_OFFSET_ANIMATE, args));
+ mPipTaskOrganizer.scheduleOffsetPip(originalBounds, offset, SHIFT_DURATION,
+ mUpdateBoundsCallback);
}
/**
@@ -437,8 +417,7 @@
/**
* Starts the physics animator which will update the animated PIP bounds using physics
- * animations, as well as the TimeAnimator which will apply those bounds to PIP at intervals
- * synchronized with the SurfaceFlinger vsync frame provider.
+ * animations, as well as the TimeAnimator which will apply those bounds to PIP.
*
* This will also add end actions to the bounds animator that cancel the TimeAnimator and update
* the 'real' bounds to equal the final animated bounds.
@@ -447,8 +426,8 @@
cancelAnimations();
mAnimatedBoundsPhysicsAnimator
- .withEndActions(() -> mPipTaskOrganizer.onMotionMovementEnd(mAnimatedBounds))
- .addUpdateListener(mResizePipVsyncUpdateListener)
+ .withEndActions(() -> mPipTaskOrganizer.scheduleFinishResizePip(mAnimatedBounds))
+ .addUpdateListener(mResizePipUpdateListener)
.start();
}
@@ -458,7 +437,7 @@
* {@link FloatingContentCoordinator.FloatingContent#getFloatingBoundsOnScreen()}.
*/
private void setAnimatingToBounds(Rect bounds) {
- mAnimatingToBounds = bounds;
+ mAnimatingToBounds.set(bounds);
mFloatingContentCoordinator.onContentMoved(this);
}
@@ -471,9 +450,7 @@
+ " callers=\n" + Debug.getCallers(5, " "));
}
if (!toBounds.equals(mBounds)) {
- SomeArgs args = SomeArgs.obtain();
- args.arg1 = toBounds;
- mHandler.sendMessage(mHandler.obtainMessage(MSG_RESIZE_IMMEDIATE, args));
+ mPipTaskOrganizer.scheduleResizePip(toBounds, mUpdateBoundsCallback);
}
}
@@ -486,10 +463,7 @@
+ " duration=" + duration + " callers=\n" + Debug.getCallers(5, " "));
}
if (!toBounds.equals(mBounds)) {
- SomeArgs args = SomeArgs.obtain();
- args.arg1 = toBounds;
- args.argi1 = duration;
- mHandler.sendMessage(mHandler.obtainMessage(MSG_RESIZE_ANIMATE, args));
+ mPipTaskOrganizer.scheduleAnimateResizePip(toBounds, duration, mUpdateBoundsCallback);
setAnimatingToBounds(toBounds);
}
}
@@ -538,70 +512,6 @@
return dismissArea.contains(endpoint.x, endpoint.y);
}
- /**
- * Handles messages to be processed on the background thread.
- */
- public boolean handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_RESIZE_IMMEDIATE: {
- SomeArgs args = (SomeArgs) msg.obj;
- Rect toBounds = (Rect) args.arg1;
- mPipTaskOrganizer.resizePip(toBounds);
- mBounds.set(toBounds);
- return true;
- }
-
- case MSG_RESIZE_ANIMATE: {
- SomeArgs args = (SomeArgs) msg.obj;
- Rect toBounds = (Rect) args.arg1;
- int duration = args.argi1;
- try {
- StackInfo stackInfo = mActivityTaskManager.getStackInfo(
- WINDOWING_MODE_PINNED, ACTIVITY_TYPE_UNDEFINED);
- if (stackInfo == null) {
- // In the case where we've already re-expanded or dismissed the PiP, then
- // just skip the resize
- return true;
- }
-
- mPipTaskOrganizer.animateResizePip(toBounds, duration);
- mBounds.set(toBounds);
- } catch (RemoteException e) {
- Log.e(TAG, "Could not animate resize pinned stack to bounds: " + toBounds, e);
- }
- return true;
- }
-
- case MSG_OFFSET_ANIMATE: {
- SomeArgs args = (SomeArgs) msg.obj;
- Rect originalBounds = (Rect) args.arg1;
- final int offset = args.argi1;
- final int duration = args.argi2;
- try {
- StackInfo stackInfo = mActivityTaskManager.getStackInfo(
- WINDOWING_MODE_PINNED, ACTIVITY_TYPE_UNDEFINED);
- if (stackInfo == null) {
- // In the case where we've already re-expanded or dismissed the PiP, then
- // just skip the resize
- return true;
- }
-
- mPipTaskOrganizer.offsetPinnedStack(originalBounds,
- 0 /* xOffset */, offset, duration);
- Rect toBounds = new Rect(originalBounds);
- toBounds.offset(0, offset);
- mBounds.set(toBounds);
- } catch (RemoteException e) {
- Log.e(TAG, "Could not animate offset pinned stack with offset: " + offset, e);
- }
- return true;
- }
-
- default:
- return false;
- }
- }
-
public void dump(PrintWriter pw, String prefix) {
final String innerPrefix = prefix + " ";
pw.println(prefix + TAG);
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
index 90db91a..b5fb1a9 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipTouchHandler.java
@@ -31,6 +31,7 @@
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
+import android.util.Pair;
import android.util.Size;
import android.view.IPinnedStackController;
import android.view.InputEvent;
@@ -148,8 +149,11 @@
@Override
public void onPipDismiss() {
- MetricsLoggerWrapper.logPictureInPictureDismissByTap(mContext,
- PipUtils.getTopPinnedActivity(mContext, mActivityManager));
+ Pair<ComponentName, Integer> topPipActivity = PipUtils.getTopPipActivity(mContext,
+ mActivityManager);
+ if (topPipActivity.first != null) {
+ MetricsLoggerWrapper.logPictureInPictureDismissByTap(mContext, topPipActivity);
+ }
mMotionHelper.dismissPip();
}
@@ -653,7 +657,7 @@
// Check if the user dragged or flung the PiP offscreen to dismiss it
if (mMotionHelper.shouldDismissPip() || isFlingToBot) {
MetricsLoggerWrapper.logPictureInPictureDismissByDrag(mContext,
- PipUtils.getTopPinnedActivity(mContext, mActivityManager));
+ PipUtils.getTopPipActivity(mContext, mActivityManager));
mMotionHelper.animateDismiss(
vel.x, vel.y,
PipTouchHandler.this::updateDismissFraction /* updateAction */);
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/ForegroundThread.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipUpdateThread.java
similarity index 70%
rename from packages/SystemUI/src/com/android/systemui/pip/phone/ForegroundThread.java
rename to packages/SystemUI/src/com/android/systemui/pip/phone/PipUpdateThread.java
index 9bf46bb..6c5d846 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/ForegroundThread.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipUpdateThread.java
@@ -21,33 +21,38 @@
/**
* Similar to {@link com.android.internal.os.BackgroundThread}, this is a shared singleton
- * foreground thread for each process.
+ * foreground thread for each process for updating PIP.
*/
-public final class ForegroundThread extends HandlerThread {
- private static ForegroundThread sInstance;
+public final class PipUpdateThread extends HandlerThread {
+ private static PipUpdateThread sInstance;
private static Handler sHandler;
- private ForegroundThread() {
- super("recents.fg");
+ private PipUpdateThread() {
+ super("pip");
}
private static void ensureThreadLocked() {
if (sInstance == null) {
- sInstance = new ForegroundThread();
+ sInstance = new PipUpdateThread();
sInstance.start();
sHandler = new Handler(sInstance.getLooper());
}
}
- public static ForegroundThread get() {
- synchronized (ForegroundThread.class) {
+ /**
+ * @return the static update thread instance
+ */
+ public static PipUpdateThread get() {
+ synchronized (PipUpdateThread.class) {
ensureThreadLocked();
return sInstance;
}
}
-
+ /**
+ * @return the static update thread handler instance
+ */
public static Handler getHandler() {
- synchronized (ForegroundThread.class) {
+ synchronized (PipUpdateThread.class) {
ensureThreadLocked();
return sHandler;
}
diff --git a/packages/SystemUI/src/com/android/systemui/pip/phone/PipUtils.java b/packages/SystemUI/src/com/android/systemui/pip/phone/PipUtils.java
index 1ed1904..4cfec01 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/phone/PipUtils.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/phone/PipUtils.java
@@ -36,7 +36,7 @@
* @return the ComponentName and user id of the top non-SystemUI activity in the pinned stack.
* The component name may be null if no such activity exists.
*/
- public static Pair<ComponentName, Integer> getTopPinnedActivity(Context context,
+ public static Pair<ComponentName, Integer> getTopPipActivity(Context context,
IActivityManager activityManager) {
try {
final String sysUiPackageName = context.getPackageName();
diff --git a/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java b/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
index ca44f6b..050acd5 100644
--- a/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
+++ b/packages/SystemUI/src/com/android/systemui/pip/tv/PipManager.java
@@ -50,8 +50,8 @@
import com.android.systemui.UiOffloadThread;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.pip.BasePipManager;
-import com.android.systemui.pip.PipAnimationController;
import com.android.systemui.pip.PipBoundsHandler;
+import com.android.systemui.pip.PipSurfaceTransactionHelper;
import com.android.systemui.pip.PipTaskOrganizer;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.shared.system.PinnedStackListenerForwarder.PinnedStackListener;
@@ -135,6 +135,7 @@
private String[] mLastPackagesResourceGranted;
private PipNotification mPipNotification;
private ParceledListSlice mCustomActions;
+ private int mResizeAnimationDuration;
// Used to calculate the movement bounds
private final DisplayInfo mTmpDisplayInfo = new DisplayInfo();
@@ -229,14 +230,19 @@
@Inject
public PipManager(Context context, BroadcastDispatcher broadcastDispatcher,
- PipBoundsHandler pipBoundsHandler) {
+ PipBoundsHandler pipBoundsHandler,
+ PipSurfaceTransactionHelper surfaceTransactionHelper) {
if (mInitialized) {
return;
}
+
mInitialized = true;
mContext = context;
mPipBoundsHandler = pipBoundsHandler;
- mPipTaskOrganizer = new PipTaskOrganizer(mContext, mPipBoundsHandler);
+ mResizeAnimationDuration = context.getResources()
+ .getInteger(R.integer.config_pipResizeAnimationDuration);
+ mPipTaskOrganizer = new PipTaskOrganizer(mContext, mPipBoundsHandler,
+ surfaceTransactionHelper);
mPipTaskOrganizer.registerPipTransitionCallback(this);
mActivityTaskManager = ActivityTaskManager.getService();
ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener);
@@ -434,8 +440,8 @@
mCurrentPipBounds = mPipBounds;
break;
}
- mPipTaskOrganizer.animateResizePip(mCurrentPipBounds,
- PipAnimationController.DURATION_DEFAULT_MS);
+ mPipTaskOrganizer.scheduleAnimateResizePip(mCurrentPipBounds, mResizeAnimationDuration,
+ null);
}
/**
@@ -679,7 +685,12 @@
}
@Override
- public void onPinnedActivityRestartAttempt(boolean clearedTask) {
+ public void onActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask) {
+ if (task.configuration.windowConfiguration.getWindowingMode()
+ != WINDOWING_MODE_PINNED) {
+ return;
+ }
if (DEBUG) Log.d(TAG, "onPinnedActivityRestartAttempt()");
// If PIPed activity is launched again by Launcher or intent, make it fullscreen.
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSMediaPlayer.java b/packages/SystemUI/src/com/android/systemui/qs/QSMediaPlayer.java
index 011893d..837256b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSMediaPlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSMediaPlayer.java
@@ -17,158 +17,53 @@
package com.android.systemui.qs;
import android.app.Notification;
-import android.app.PendingIntent;
-import android.content.ComponentName;
import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.content.res.ColorStateList;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Matrix;
-import android.graphics.Paint;
import android.graphics.drawable.Drawable;
-import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.Icon;
-import android.graphics.drawable.RippleDrawable;
-import android.media.MediaMetadata;
-import android.media.session.MediaController;
import android.media.session.MediaSession;
-import android.media.session.PlaybackState;
-import android.os.Handler;
import android.util.Log;
-import android.view.KeyEvent;
-import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
-import android.widget.ImageView;
import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import androidx.core.graphics.drawable.RoundedBitmapDrawable;
-import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import com.android.settingslib.media.MediaDevice;
-import com.android.settingslib.media.MediaOutputSliceConstants;
-import com.android.settingslib.widget.AdaptiveIcon;
-import com.android.systemui.Dependency;
import com.android.systemui.R;
-import com.android.systemui.plugins.ActivityStarter;
+import com.android.systemui.media.MediaControlPanel;
+import com.android.systemui.statusbar.NotificationMediaManager;
-import java.util.List;
+import java.util.concurrent.Executor;
/**
* Single media player for carousel in QSPanel
*/
-public class QSMediaPlayer {
+public class QSMediaPlayer extends MediaControlPanel {
private static final String TAG = "QSMediaPlayer";
- private Context mContext;
- private LinearLayout mMediaNotifView;
- private View mSeamless;
- private MediaSession.Token mToken;
- private MediaController mController;
- private int mForegroundColor;
- private int mBackgroundColor;
- private ComponentName mRecvComponent;
- private QSPanel mParent;
-
- private MediaController.Callback mSessionCallback = new MediaController.Callback() {
- @Override
- public void onSessionDestroyed() {
- Log.d(TAG, "session destroyed");
- mController.unregisterCallback(mSessionCallback);
-
- // Hide all the old buttons
- final int[] actionIds = {
- R.id.action0,
- R.id.action1,
- R.id.action2,
- R.id.action3,
- R.id.action4
- };
- for (int i = 0; i < actionIds.length; i++) {
- ImageButton thisBtn = mMediaNotifView.findViewById(actionIds[i]);
- if (thisBtn != null) {
- thisBtn.setVisibility(View.GONE);
- }
- }
-
- // Add a restart button
- ImageButton btn = mMediaNotifView.findViewById(actionIds[0]);
- btn.setOnClickListener(v -> {
- Log.d(TAG, "Attempting to restart session");
- // Send a media button event to previously found receiver
- if (mRecvComponent != null) {
- Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
- intent.setComponent(mRecvComponent);
- int keyCode = KeyEvent.KEYCODE_MEDIA_PLAY;
- intent.putExtra(
- Intent.EXTRA_KEY_EVENT,
- new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
- mContext.sendBroadcast(intent);
- } else {
- Log.d(TAG, "No receiver to restart");
- // If we don't have a receiver, try relaunching the activity instead
- try {
- mController.getSessionActivity().send();
- } catch (PendingIntent.CanceledException e) {
- Log.e(TAG, "Pending intent was canceled");
- e.printStackTrace();
- }
- }
- });
- btn.setImageDrawable(mContext.getResources().getDrawable(R.drawable.lb_ic_play));
- btn.setImageTintList(ColorStateList.valueOf(mForegroundColor));
- btn.setVisibility(View.VISIBLE);
-
- // Add long-click option to remove the player
- ViewGroup mMediaCarousel = (ViewGroup) mMediaNotifView.getParent();
- mMediaNotifView.setOnLongClickListener(v -> {
- // Replace player view with delete/cancel view
- v.setVisibility(View.GONE);
-
- View options = LayoutInflater.from(mContext).inflate(
- R.layout.qs_media_panel_options, null, false);
- ImageButton btnDelete = options.findViewById(R.id.remove);
- btnDelete.setOnClickListener(b -> {
- mMediaCarousel.removeView(options);
- mParent.removeMediaPlayer(QSMediaPlayer.this);
- });
- ImageButton btnCancel = options.findViewById(R.id.cancel);
- btnCancel.setOnClickListener(b -> {
- mMediaCarousel.removeView(options);
- v.setVisibility(View.VISIBLE);
- });
-
- int pos = mMediaCarousel.indexOfChild(v);
- mMediaCarousel.addView(options, pos, v.getLayoutParams());
- return true; // consumed click
- });
- }
+ // Button IDs for QS controls
+ static final int[] QS_ACTION_IDS = {
+ R.id.action0,
+ R.id.action1,
+ R.id.action2,
+ R.id.action3,
+ R.id.action4
};
/**
- *
+ * Initialize quick shade version of player
* @param context
* @param parent
+ * @param manager
+ * @param backgroundExecutor
*/
- public QSMediaPlayer(Context context, ViewGroup parent) {
- mContext = context;
- LayoutInflater inflater = LayoutInflater.from(mContext);
- mMediaNotifView = (LinearLayout) inflater.inflate(R.layout.qs_media_panel, parent, false);
- }
-
- public View getView() {
- return mMediaNotifView;
+ public QSMediaPlayer(Context context, ViewGroup parent, NotificationMediaManager manager,
+ Executor backgroundExecutor) {
+ super(context, parent, manager, R.layout.qs_media_panel, QS_ACTION_IDS, backgroundExecutor);
}
/**
- * Create or update the player view for the given media session
- * @param parent the parent QSPanel
+ * Update media panel view for the given media session
* @param token token for this media session
* @param icon app notification icon
* @param iconColor foreground color (for text, icons)
@@ -177,114 +72,20 @@
* @param notif reference to original notification
* @param device current playback device
*/
- public void setMediaSession(QSPanel parent, MediaSession.Token token, Icon icon, int iconColor,
+ public void setMediaSession(MediaSession.Token token, Icon icon, int iconColor,
int bgColor, View actionsContainer, Notification notif, MediaDevice device) {
- mParent = parent;
- mToken = token;
- mForegroundColor = iconColor;
- mBackgroundColor = bgColor;
- mController = new MediaController(mContext, token);
- // Try to find a receiver for the media button that matches this app
- PackageManager pm = mContext.getPackageManager();
- Intent it = new Intent(Intent.ACTION_MEDIA_BUTTON);
- List<ResolveInfo> info = pm.queryBroadcastReceiversAsUser(it, 0, mContext.getUser());
- if (info != null) {
- for (ResolveInfo inf : info) {
- if (inf.activityInfo.packageName.equals(mController.getPackageName())) {
- mRecvComponent = inf.getComponentInfo().getComponentName();
- }
- }
- }
-
- // reset in case we had previously restarted the stream
- mMediaNotifView.setOnLongClickListener(null);
- mController.registerCallback(mSessionCallback);
- MediaMetadata mMediaMetadata = mController.getMetadata();
- if (mMediaMetadata == null) {
- Log.e(TAG, "Media metadata was null");
- return;
- }
-
- Notification.Builder builder = Notification.Builder.recoverBuilder(mContext, notif);
-
- // Album art
- addAlbumArt(mMediaMetadata, bgColor);
-
- LinearLayout headerView = mMediaNotifView.findViewById(R.id.header);
-
- // App icon
- ImageView appIcon = headerView.findViewById(R.id.icon);
- Drawable iconDrawable = icon.loadDrawable(mContext);
- iconDrawable.setTint(iconColor);
- appIcon.setImageDrawable(iconDrawable);
-
- // App title
- TextView appName = headerView.findViewById(R.id.app_name);
- String appNameString = builder.loadHeaderAppName();
- appName.setText(appNameString);
- appName.setTextColor(iconColor);
-
- // Action
- mMediaNotifView.setOnClickListener(v -> {
- try {
- notif.contentIntent.send();
- // Also close shade
- mContext.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
- } catch (PendingIntent.CanceledException e) {
- Log.e(TAG, "Pending intent was canceled");
- e.printStackTrace();
- }
- });
-
- // Transfer chip
- mSeamless = headerView.findViewById(R.id.media_seamless);
- mSeamless.setVisibility(View.VISIBLE);
- updateChip(device);
- ActivityStarter mActivityStarter = Dependency.get(ActivityStarter.class);
- mSeamless.setOnClickListener(v -> {
- final Intent intent = new Intent()
- .setAction(MediaOutputSliceConstants.ACTION_MEDIA_OUTPUT)
- .putExtra(MediaOutputSliceConstants.EXTRA_PACKAGE_NAME,
- mController.getPackageName())
- .putExtra(MediaOutputSliceConstants.KEY_MEDIA_SESSION_TOKEN, token);
- mActivityStarter.startActivity(intent, false, true /* dismissShade */,
- Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
- });
-
- // Artist name
- TextView artistText = headerView.findViewById(R.id.header_artist);
- String artistName = mMediaMetadata.getString(MediaMetadata.METADATA_KEY_ARTIST);
- artistText.setText(artistName);
- artistText.setTextColor(iconColor);
-
- // Song name
- TextView titleText = headerView.findViewById(R.id.header_text);
- String songName = mMediaMetadata.getString(MediaMetadata.METADATA_KEY_TITLE);
- titleText.setText(songName);
- titleText.setTextColor(iconColor);
+ String appName = Notification.Builder.recoverBuilder(getContext(), notif)
+ .loadHeaderAppName();
+ super.setMediaSession(token, icon, iconColor, bgColor, notif.contentIntent,
+ appName, device);
// Media controls
LinearLayout parentActionsLayout = (LinearLayout) actionsContainer;
- final int[] actionIds = {
- R.id.action0,
- R.id.action1,
- R.id.action2,
- R.id.action3,
- R.id.action4
- };
- final int[] notifActionIds = {
- com.android.internal.R.id.action0,
- com.android.internal.R.id.action1,
- com.android.internal.R.id.action2,
- com.android.internal.R.id.action3,
- com.android.internal.R.id.action4
- };
-
int i = 0;
- for (; i < parentActionsLayout.getChildCount() && i < actionIds.length; i++) {
- ImageButton thisBtn = mMediaNotifView.findViewById(actionIds[i]);
- ImageButton thatBtn = parentActionsLayout.findViewById(notifActionIds[i]);
+ for (; i < parentActionsLayout.getChildCount() && i < QS_ACTION_IDS.length; i++) {
+ ImageButton thisBtn = mMediaNotifView.findViewById(QS_ACTION_IDS[i]);
+ ImageButton thatBtn = parentActionsLayout.findViewById(NOTIF_ACTION_IDS[i]);
if (thatBtn == null || thatBtn.getDrawable() == null
|| thatBtn.getVisibility() != View.VISIBLE) {
thisBtn.setVisibility(View.GONE);
@@ -301,116 +102,9 @@
}
// Hide any unused buttons
- for (; i < actionIds.length; i++) {
- ImageButton thisBtn = mMediaNotifView.findViewById(actionIds[i]);
+ for (; i < QS_ACTION_IDS.length; i++) {
+ ImageButton thisBtn = mMediaNotifView.findViewById(QS_ACTION_IDS[i]);
thisBtn.setVisibility(View.GONE);
}
}
-
- public MediaSession.Token getMediaSessionToken() {
- return mToken;
- }
-
- public String getMediaPlayerPackage() {
- return mController.getPackageName();
- }
-
- /**
- * Check whether the media controlled by this player is currently playing
- * @return whether it is playing, or false if no controller information
- */
- public boolean isPlaying() {
- if (mController == null) {
- return false;
- }
-
- PlaybackState state = mController.getPlaybackState();
- if (state == null) {
- return false;
- }
-
- return (state.getState() == PlaybackState.STATE_PLAYING);
- }
-
- private void addAlbumArt(MediaMetadata metadata, int bgColor) {
- Bitmap albumArt = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
- float radius = mContext.getResources().getDimension(R.dimen.qs_media_corner_radius);
- ImageView albumView = mMediaNotifView.findViewById(R.id.album_art);
- if (albumArt != null) {
- Log.d(TAG, "updating album art");
- Bitmap original = albumArt.copy(Bitmap.Config.ARGB_8888, true);
- int albumSize = (int) mContext.getResources().getDimension(R.dimen.qs_media_album_size);
- Bitmap scaled = scaleBitmap(original, albumSize, albumSize);
- RoundedBitmapDrawable roundedDrawable = RoundedBitmapDrawableFactory.create(
- mContext.getResources(), scaled);
- roundedDrawable.setCornerRadius(radius);
- albumView.setImageDrawable(roundedDrawable);
- } else {
- Log.e(TAG, "No album art available");
- albumView.setImageDrawable(null);
- }
-
- mMediaNotifView.setBackgroundTintList(ColorStateList.valueOf(bgColor));
- }
-
- private Bitmap scaleBitmap(Bitmap original, int width, int height) {
- Bitmap cropped = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
- Canvas canvas = new Canvas(cropped);
-
- float scale = (float) cropped.getWidth() / (float) original.getWidth();
- float dy = (cropped.getHeight() - original.getHeight() * scale) / 2.0f;
- Matrix transformation = new Matrix();
- transformation.postTranslate(0, dy);
- transformation.preScale(scale, scale);
-
- Paint paint = new Paint();
- paint.setFilterBitmap(true);
- canvas.drawBitmap(original, transformation, paint);
-
- return cropped;
- }
-
- protected void updateChip(MediaDevice device) {
- if (mSeamless == null) {
- return;
- }
- Handler handler = mSeamless.getHandler();
- handler.post(() -> {
- updateChipInternal(device);
- });
- }
-
- private void updateChipInternal(MediaDevice device) {
- ColorStateList fgTintList = ColorStateList.valueOf(mForegroundColor);
-
- // Update the outline color
- LinearLayout viewLayout = (LinearLayout) mSeamless;
- RippleDrawable bkgDrawable = (RippleDrawable) viewLayout.getBackground();
- GradientDrawable rect = (GradientDrawable) bkgDrawable.getDrawable(0);
- rect.setStroke(2, mForegroundColor);
- rect.setColor(mBackgroundColor);
-
- ImageView iconView = mSeamless.findViewById(R.id.media_seamless_image);
- TextView deviceName = mSeamless.findViewById(R.id.media_seamless_text);
- deviceName.setTextColor(fgTintList);
-
- if (device != null) {
- Drawable icon = device.getIcon();
- iconView.setVisibility(View.VISIBLE);
- iconView.setImageTintList(fgTintList);
-
- if (icon instanceof AdaptiveIcon) {
- AdaptiveIcon aIcon = (AdaptiveIcon) icon;
- aIcon.setBackgroundColor(mBackgroundColor);
- iconView.setImageDrawable(aIcon);
- } else {
- iconView.setImageDrawable(icon);
- }
- deviceName.setText(device.getName());
- } else {
- // Reset to default
- iconView.setVisibility(View.GONE);
- deviceName.setText(com.android.internal.R.string.ext_media_seamless_action);
- }
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
index d2d9092..bf72b33 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
@@ -44,12 +44,15 @@
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settingslib.Utils;
+import com.android.settingslib.bluetooth.LocalBluetoothManager;
+import com.android.settingslib.media.InfoMediaManager;
import com.android.settingslib.media.LocalMediaManager;
import com.android.settingslib.media.MediaDevice;
import com.android.systemui.Dependency;
import com.android.systemui.Dumpable;
import com.android.systemui.R;
import com.android.systemui.broadcast.BroadcastDispatcher;
+import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.dump.DumpManager;
import com.android.systemui.plugins.qs.DetailAdapter;
import com.android.systemui.plugins.qs.QSTile;
@@ -60,6 +63,7 @@
import com.android.systemui.qs.logging.QSLogger;
import com.android.systemui.settings.BrightnessController;
import com.android.systemui.settings.ToggleSliderView;
+import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.statusbar.policy.BrightnessMirrorController;
import com.android.systemui.statusbar.policy.BrightnessMirrorController.BrightnessMirrorListener;
import com.android.systemui.tuner.TunerService;
@@ -70,6 +74,7 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import javax.inject.Inject;
@@ -94,6 +99,9 @@
private final LinearLayout mMediaCarousel;
private final ArrayList<QSMediaPlayer> mMediaPlayers = new ArrayList<>();
+ private final NotificationMediaManager mNotificationMediaManager;
+ private final LocalBluetoothManager mLocalBluetoothManager;
+ private final Executor mBackgroundExecutor;
private LocalMediaManager mLocalMediaManager;
private MediaDevice mDevice;
private boolean mUpdateCarousel = false;
@@ -128,7 +136,7 @@
if (mDevice == null || !mDevice.equals(currentDevice)) {
mDevice = currentDevice;
for (QSMediaPlayer p : mMediaPlayers) {
- p.updateChip(mDevice);
+ p.updateDevice(mDevice);
}
}
}
@@ -138,7 +146,7 @@
if (mDevice == null || !mDevice.equals(device)) {
mDevice = device;
for (QSMediaPlayer p : mMediaPlayers) {
- p.updateChip(mDevice);
+ p.updateDevice(mDevice);
}
}
}
@@ -150,12 +158,18 @@
AttributeSet attrs,
DumpManager dumpManager,
BroadcastDispatcher broadcastDispatcher,
- QSLogger qsLogger
+ QSLogger qsLogger,
+ NotificationMediaManager notificationMediaManager,
+ @Background Executor backgroundExecutor,
+ @Nullable LocalBluetoothManager localBluetoothManager
) {
super(context, attrs);
mContext = context;
mQSLogger = qsLogger;
mDumpManager = dumpManager;
+ mNotificationMediaManager = notificationMediaManager;
+ mBackgroundExecutor = backgroundExecutor;
+ mLocalBluetoothManager = localBluetoothManager;
setOrientation(VERTICAL);
@@ -255,7 +269,8 @@
if (player == null) {
Log.d(TAG, "creating new player");
- player = new QSMediaPlayer(mContext, this);
+ player = new QSMediaPlayer(mContext, this, mNotificationMediaManager,
+ mBackgroundExecutor);
if (player.isPlaying()) {
mMediaCarousel.addView(player.getView(), 0, lp); // add in front
@@ -268,7 +283,7 @@
}
Log.d(TAG, "setting player session");
- player.setMediaSession(this, token, icon, iconColor, bgColor, actionsContainer,
+ player.setMediaSession(token, icon, iconColor, bgColor, actionsContainer,
notif.getNotification(), mDevice);
if (mMediaPlayers.size() > 0) {
@@ -276,7 +291,9 @@
// Set up listener for device changes
// TODO: integrate with MediaTransferManager?
- mLocalMediaManager = new LocalMediaManager(mContext, null, null);
+ InfoMediaManager imm =
+ new InfoMediaManager(mContext, null, null, mLocalBluetoothManager);
+ mLocalMediaManager = new LocalMediaManager(mContext, mLocalBluetoothManager, imm, null);
mLocalMediaManager.startScan();
mDevice = mLocalMediaManager.getCurrentConnectedDevice();
mLocalMediaManager.registerCallback(mDeviceCallback);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java b/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
index 17ac5e5..fab7191 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTileHost.java
@@ -274,8 +274,8 @@
try {
tile = createTile(tileSpec);
if (tile != null) {
+ tile.setTileSpec(tileSpec);
if (tile.isAvailable()) {
- tile.setTileSpec(tileSpec);
newTiles.put(tileSpec, tile);
mQSLogger.logTileAdded(tileSpec);
} else {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java
index 9018a37..4512afb 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSMediaPlayer.java
@@ -17,108 +17,47 @@
package com.android.systemui.qs;
import android.app.PendingIntent;
-import android.content.ComponentName;
import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
-import android.media.MediaMetadata;
import android.media.session.MediaController;
import android.media.session.MediaSession;
-import android.media.session.PlaybackState;
-import android.util.Log;
-import android.view.KeyEvent;
-import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
-import android.widget.ImageView;
import android.widget.LinearLayout;
-import android.widget.TextView;
import com.android.systemui.R;
+import com.android.systemui.media.MediaControlPanel;
+import com.android.systemui.statusbar.NotificationMediaManager;
-import java.util.List;
+import java.util.concurrent.Executor;
/**
* QQS mini media player
*/
-public class QuickQSMediaPlayer {
+public class QuickQSMediaPlayer extends MediaControlPanel {
private static final String TAG = "QQSMediaPlayer";
- private Context mContext;
- private LinearLayout mMediaNotifView;
- private MediaSession.Token mToken;
- private MediaController mController;
- private int mForegroundColor;
- private ComponentName mRecvComponent;
-
- private MediaController.Callback mSessionCallback = new MediaController.Callback() {
- @Override
- public void onSessionDestroyed() {
- Log.d(TAG, "session destroyed");
- mController.unregisterCallback(mSessionCallback);
-
- // Hide all the old buttons
- final int[] actionIds = {R.id.action0, R.id.action1, R.id.action2};
- for (int i = 0; i < actionIds.length; i++) {
- ImageButton thisBtn = mMediaNotifView.findViewById(actionIds[i]);
- if (thisBtn != null) {
- thisBtn.setVisibility(View.GONE);
- }
- }
-
- // Add a restart button
- ImageButton btn = mMediaNotifView.findViewById(actionIds[0]);
- btn.setOnClickListener(v -> {
- Log.d(TAG, "Attempting to restart session");
- // Send a media button event to previously found receiver
- if (mRecvComponent != null) {
- Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
- intent.setComponent(mRecvComponent);
- int keyCode = KeyEvent.KEYCODE_MEDIA_PLAY;
- intent.putExtra(
- Intent.EXTRA_KEY_EVENT,
- new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
- mContext.sendBroadcast(intent);
- } else {
- Log.d(TAG, "No receiver to restart");
- // If we don't have a receiver, try relaunching the activity instead
- try {
- mController.getSessionActivity().send();
- } catch (PendingIntent.CanceledException e) {
- Log.e(TAG, "Pending intent was canceled");
- e.printStackTrace();
- }
- }
- });
- btn.setImageDrawable(mContext.getResources().getDrawable(R.drawable.lb_ic_play));
- btn.setImageTintList(ColorStateList.valueOf(mForegroundColor));
- btn.setVisibility(View.VISIBLE);
- }
- };
+ // Button IDs for QS controls
+ private static final int[] QQS_ACTION_IDS = {R.id.action0, R.id.action1, R.id.action2};
/**
- *
+ * Initialize mini media player for QQS
* @param context
* @param parent
+ * @param manager
+ * @param backgroundExecutor
*/
- public QuickQSMediaPlayer(Context context, ViewGroup parent) {
- mContext = context;
- LayoutInflater inflater = LayoutInflater.from(mContext);
- mMediaNotifView = (LinearLayout) inflater.inflate(R.layout.qqs_media_panel, parent, false);
- }
-
- public View getView() {
- return mMediaNotifView;
+ public QuickQSMediaPlayer(Context context, ViewGroup parent, NotificationMediaManager manager,
+ Executor backgroundExecutor) {
+ super(context, parent, manager, R.layout.qqs_media_panel, QQS_ACTION_IDS,
+ backgroundExecutor);
}
/**
- *
+ * Update media panel view for the given media session
* @param token token for this media session
* @param icon app notification icon
* @param iconColor foreground color (for text, icons)
@@ -130,84 +69,30 @@
*/
public void setMediaSession(MediaSession.Token token, Icon icon, int iconColor, int bgColor,
View actionsContainer, int[] actionsToShow, PendingIntent contentIntent) {
- mToken = token;
- mForegroundColor = iconColor;
-
+ // Only update if this is a different session and currently playing
String oldPackage = "";
- if (mController != null) {
- oldPackage = mController.getPackageName();
+ if (getController() != null) {
+ oldPackage = getController().getPackageName();
}
- MediaController controller = new MediaController(mContext, token);
- boolean samePlayer = mToken.equals(token) && oldPackage.equals(controller.getPackageName());
- if (mController != null && !samePlayer && !isPlaying(controller)) {
- // Only update if this is a different session and currently playing
- return;
- }
- mController = controller;
- MediaMetadata mMediaMetadata = mController.getMetadata();
-
- // Try to find a receiver for the media button that matches this app
- PackageManager pm = mContext.getPackageManager();
- Intent it = new Intent(Intent.ACTION_MEDIA_BUTTON);
- List<ResolveInfo> info = pm.queryBroadcastReceiversAsUser(it, 0, mContext.getUser());
- if (info != null) {
- for (ResolveInfo inf : info) {
- if (inf.activityInfo.packageName.equals(mController.getPackageName())) {
- mRecvComponent = inf.getComponentInfo().getComponentName();
- }
- }
- }
- mController.registerCallback(mSessionCallback);
-
- if (mMediaMetadata == null) {
- Log.e(TAG, "Media metadata was null");
+ MediaController controller = new MediaController(getContext(), token);
+ MediaSession.Token currentToken = getMediaSessionToken();
+ boolean samePlayer = currentToken != null
+ && currentToken.equals(token)
+ && oldPackage.equals(controller.getPackageName());
+ if (getController() != null && !samePlayer && !isPlaying(controller)) {
return;
}
- // Action
- mMediaNotifView.setOnClickListener(v -> {
- try {
- contentIntent.send();
- mContext.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
- } catch (PendingIntent.CanceledException e) {
- Log.e(TAG, "Pending intent was canceled: " + e.getMessage());
- }
- });
+ super.setMediaSession(token, icon, iconColor, bgColor, contentIntent, null, null);
- mMediaNotifView.setBackgroundTintList(ColorStateList.valueOf(bgColor));
-
- // App icon
- ImageView appIcon = mMediaNotifView.findViewById(R.id.icon);
- Drawable iconDrawable = icon.loadDrawable(mContext);
- iconDrawable.setTint(mForegroundColor);
- appIcon.setImageDrawable(iconDrawable);
-
- // Song name
- TextView titleText = mMediaNotifView.findViewById(R.id.header_title);
- String songName = mMediaMetadata.getString(MediaMetadata.METADATA_KEY_TITLE);
- titleText.setText(songName);
- titleText.setTextColor(mForegroundColor);
-
- // Buttons we can display
- final int[] actionIds = {R.id.action0, R.id.action1, R.id.action2};
-
- // Existing buttons in the notification
LinearLayout parentActionsLayout = (LinearLayout) actionsContainer;
- final int[] notifActionIds = {
- com.android.internal.R.id.action0,
- com.android.internal.R.id.action1,
- com.android.internal.R.id.action2,
- com.android.internal.R.id.action3,
- com.android.internal.R.id.action4
- };
-
int i = 0;
if (actionsToShow != null) {
int maxButtons = Math.min(actionsToShow.length, parentActionsLayout.getChildCount());
- maxButtons = Math.min(maxButtons, actionIds.length);
+ maxButtons = Math.min(maxButtons, QQS_ACTION_IDS.length);
for (; i < maxButtons; i++) {
- ImageButton thisBtn = mMediaNotifView.findViewById(actionIds[i]);
- int thatId = notifActionIds[actionsToShow[i]];
+ ImageButton thisBtn = mMediaNotifView.findViewById(QQS_ACTION_IDS[i]);
+ int thatId = NOTIF_ACTION_IDS[actionsToShow[i]];
ImageButton thatBtn = parentActionsLayout.findViewById(thatId);
if (thatBtn == null || thatBtn.getDrawable() == null
|| thatBtn.getVisibility() != View.VISIBLE) {
@@ -225,38 +110,9 @@
}
// Hide any unused buttons
- for (; i < actionIds.length; i++) {
- ImageButton thisBtn = mMediaNotifView.findViewById(actionIds[i]);
+ for (; i < QQS_ACTION_IDS.length; i++) {
+ ImageButton thisBtn = mMediaNotifView.findViewById(QQS_ACTION_IDS[i]);
thisBtn.setVisibility(View.GONE);
}
}
-
- public MediaSession.Token getMediaSessionToken() {
- return mToken;
- }
-
- /**
- * Check whether the media controlled by this player is currently playing
- * @return whether it is playing, or false if no controller information
- */
- public boolean isPlaying(MediaController controller) {
- if (controller == null) {
- return false;
- }
-
- PlaybackState state = controller.getPlaybackState();
- if (state == null) {
- return false;
- }
-
- return (state.getState() == PlaybackState.STATE_PLAYING);
- }
-
- /**
- * Check whether this player has an attached media session.
- * @return whether there is a controller with a current media session.
- */
- public boolean hasMediaSession() {
- return mController != null && mController.getPlaybackState() != null;
- }
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
index 20efbcb..6654b7a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
@@ -18,6 +18,7 @@
import static com.android.systemui.util.InjectionInflationController.VIEW_CONTEXT;
+import android.annotation.Nullable;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
@@ -26,21 +27,25 @@
import android.view.View;
import android.widget.LinearLayout;
+import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.systemui.Dependency;
import com.android.systemui.R;
import com.android.systemui.broadcast.BroadcastDispatcher;
+import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.dump.DumpManager;
import com.android.systemui.plugins.qs.QSTile;
import com.android.systemui.plugins.qs.QSTile.SignalState;
import com.android.systemui.plugins.qs.QSTile.State;
import com.android.systemui.qs.customize.QSCustomizer;
import com.android.systemui.qs.logging.QSLogger;
+import com.android.systemui.statusbar.NotificationMediaManager;
import com.android.systemui.tuner.TunerService;
import com.android.systemui.tuner.TunerService.Tunable;
import com.android.systemui.util.Utils;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
@@ -72,9 +77,13 @@
AttributeSet attrs,
DumpManager dumpManager,
BroadcastDispatcher broadcastDispatcher,
- QSLogger qsLogger
+ QSLogger qsLogger,
+ NotificationMediaManager notificationMediaManager,
+ @Background Executor backgroundExecutor,
+ @Nullable LocalBluetoothManager localBluetoothManager
) {
- super(context, attrs, dumpManager, broadcastDispatcher, qsLogger);
+ super(context, attrs, dumpManager, broadcastDispatcher, qsLogger, notificationMediaManager,
+ backgroundExecutor, localBluetoothManager);
if (mFooter != null) {
removeView(mFooter.getView());
}
@@ -93,7 +102,8 @@
mHorizontalLinearLayout.setClipToPadding(false);
int marginSize = (int) mContext.getResources().getDimension(R.dimen.qqs_media_spacing);
- mMediaPlayer = new QuickQSMediaPlayer(mContext, mHorizontalLinearLayout);
+ mMediaPlayer = new QuickQSMediaPlayer(mContext, mHorizontalLinearLayout,
+ notificationMediaManager, backgroundExecutor);
LayoutParams lp2 = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1);
lp2.setMarginEnd(marginSize);
lp2.setMarginStart(0);
@@ -148,8 +158,6 @@
Dependency.get(TunerService.class).removeTunable(mNumTiles);
}
-
-
@Override
protected String getDumpableTag() {
return TAG;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyRecentsImpl.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyRecentsImpl.java
index f3e2f10..5bf44c6 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyRecentsImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyRecentsImpl.java
@@ -20,6 +20,8 @@
import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
+import static com.android.systemui.shared.system.WindowManagerWrapper.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
+
import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.trust.TrustManager;
@@ -37,6 +39,7 @@
import com.android.systemui.R;
import com.android.systemui.shared.recents.IOverviewProxy;
import com.android.systemui.shared.system.ActivityManagerWrapper;
+import com.android.systemui.shared.system.TaskStackChangeListener;
import com.android.systemui.stackdivider.Divider;
import com.android.systemui.statusbar.phone.StatusBar;
@@ -63,6 +66,21 @@
private TrustManager mTrustManager;
private OverviewProxyService mOverviewProxyService;
+ private TaskStackChangeListener mListener = new TaskStackChangeListener() {
+ @Override
+ public void onActivityRestartAttempt(ActivityManager.RunningTaskInfo task,
+ boolean homeTaskVisible, boolean clearedTask) {
+ if (task.configuration.windowConfiguration.getWindowingMode()
+ != WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
+ return;
+ }
+
+ if (homeTaskVisible) {
+ showRecentApps(false /* triggeredFromAltTab */);
+ }
+ }
+ };
+
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Inject
public OverviewProxyRecentsImpl(Optional<Lazy<StatusBar>> statusBarLazy,
@@ -77,6 +95,7 @@
mHandler = new Handler();
mTrustManager = (TrustManager) context.getSystemService(Context.TRUST_SERVICE);
mOverviewProxyService = Dependency.get(OverviewProxyService.class);
+ ActivityManagerWrapper.getInstance().registerTaskStackListener(mListener);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
index 37a8ca5..8b8b6f8 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
@@ -16,10 +16,6 @@
package com.android.systemui.screenshot;
-import static android.provider.DeviceConfig.NAMESPACE_SYSTEMUI;
-
-import static com.android.internal.config.sysui.SystemUiDeviceConfigFlags.SCREENSHOT_CORNER_FLOW;
-
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
@@ -33,7 +29,6 @@
import android.os.Messenger;
import android.os.RemoteException;
import android.os.UserManager;
-import android.provider.DeviceConfig;
import android.util.Log;
import android.view.WindowManager;
@@ -70,8 +65,7 @@
}
// TODO (mkephart): clean up once notifications flow is fully deprecated
- boolean useCornerFlow = DeviceConfig.getBoolean(
- NAMESPACE_SYSTEMUI, SCREENSHOT_CORNER_FLOW, true);
+ boolean useCornerFlow = true;
switch (msg.what) {
case WindowManager.TAKE_SCREENSHOT_FULLSCREEN:
if (useCornerFlow) {
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java b/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
index 333fa3c..d7eab3a 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/Divider.java
@@ -17,6 +17,8 @@
package com.android.systemui.stackdivider;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
+import static android.content.res.Configuration.SCREEN_HEIGHT_DP_UNDEFINED;
+import static android.content.res.Configuration.SCREEN_WIDTH_DP_UNDEFINED;
import static android.view.Display.DEFAULT_DISPLAY;
import android.animation.Animator;
@@ -29,7 +31,6 @@
import android.os.Handler;
import android.os.RemoteException;
import android.provider.Settings;
-import android.util.Log;
import android.util.Slog;
import android.view.IWindowContainer;
import android.view.LayoutInflater;
@@ -71,7 +72,7 @@
DisplayController.OnDisplaysChangedListener {
private static final String TAG = "Divider";
- static final boolean DEBUG = true;
+ static final boolean DEBUG = false;
static final int DEFAULT_APP_TRANSITION_DURATION = 336;
static final float ADJUSTED_NONFOCUS_DIM = 0.3f;
@@ -127,203 +128,291 @@
}
};
- private DisplayImeController.ImePositionProcessor mImePositionProcessor =
- new DisplayImeController.ImePositionProcessor() {
- /**
- * These are the y positions of the top of the IME surface when it is hidden and
- * when it is shown respectively. These are NOT necessarily the top of the visible
- * IME itself.
- */
- private int mHiddenTop = 0;
- private int mShownTop = 0;
+ private class DividerImeController implements DisplayImeController.ImePositionProcessor {
+ /**
+ * These are the y positions of the top of the IME surface when it is hidden and when it is
+ * shown respectively. These are NOT necessarily the top of the visible IME itself.
+ */
+ private int mHiddenTop = 0;
+ private int mShownTop = 0;
- // The following are target states (what we are curretly animating towards).
- /**
- * {@code true} if, at the end of the animation, the split task positions should be
- * adjusted by height of the IME. This happens when the secondary split is the IME
- * target.
- */
- private boolean mTargetAdjusted = false;
- /**
- * {@code true} if, at the end of the animation, the IME should be shown/visible
- * regardless of what has focus.
- */
- private boolean mTargetShown = false;
+ // The following are target states (what we are curretly animating towards).
+ /**
+ * {@code true} if, at the end of the animation, the split task positions should be
+ * adjusted by height of the IME. This happens when the secondary split is the IME target.
+ */
+ private boolean mTargetAdjusted = false;
+ /**
+ * {@code true} if, at the end of the animation, the IME should be shown/visible
+ * regardless of what has focus.
+ */
+ private boolean mTargetShown = false;
+ private float mTargetPrimaryDim = 0.f;
+ private float mTargetSecondaryDim = 0.f;
- // The following are the current (most recent) states set during animation
- /**
- * {@code true} if the secondary split has IME focus.
- */
- private boolean mSecondaryHasFocus = false;
- /** The dimming currently applied to the primary/secondary splits. */
- private float mLastPrimaryDim = 0.f;
- private float mLastSecondaryDim = 0.f;
- /** The most recent y position of the top of the IME surface */
- private int mLastAdjustTop = -1;
+ // The following are the current (most recent) states set during animation
+ /** {@code true} if the secondary split has IME focus. */
+ private boolean mSecondaryHasFocus = false;
+ /** The dimming currently applied to the primary/secondary splits. */
+ private float mLastPrimaryDim = 0.f;
+ private float mLastSecondaryDim = 0.f;
+ /** The most recent y position of the top of the IME surface */
+ private int mLastAdjustTop = -1;
- // The following are states reached last time an animation fully completed.
- /** {@code true} if the IME was shown/visible by the last-completed animation. */
- private boolean mImeWasShown = false;
- /**
- * {@code true} if the split positions were adjusted by the last-completed
- * animation.
- */
- private boolean mAdjusted = false;
+ // The following are states reached last time an animation fully completed.
+ /** {@code true} if the IME was shown/visible by the last-completed animation. */
+ private boolean mImeWasShown = false;
+ /** {@code true} if the split positions were adjusted by the last-completed animation. */
+ private boolean mAdjusted = false;
- /**
- * When some aspect of split-screen needs to animate independent from the IME,
- * this will be non-null and control split animation.
- */
- @Nullable
- private ValueAnimator mAnimation = null;
+ /**
+ * When some aspect of split-screen needs to animate independent from the IME,
+ * this will be non-null and control split animation.
+ */
+ @Nullable
+ private ValueAnimator mAnimation = null;
- private boolean getSecondaryHasFocus(int displayId) {
- try {
- IWindowContainer imeSplit = ActivityTaskManager.getTaskOrganizerController()
- .getImeTarget(displayId);
- return imeSplit != null
- && (imeSplit.asBinder() == mSplits.mSecondary.token.asBinder());
- } catch (RemoteException e) {
- Slog.w(TAG, "Failed to get IME target", e);
- }
- return false;
- }
+ private boolean mPaused = true;
+ private boolean mPausedTargetAdjusted = false;
- @Override
- public void onImeStartPositioning(int displayId, int hiddenTop, int shownTop,
- boolean imeShouldShow, SurfaceControl.Transaction t) {
- mSecondaryHasFocus = getSecondaryHasFocus(displayId);
- mTargetAdjusted = imeShouldShow && mSecondaryHasFocus
- && !mSplitLayout.mDisplayLayout.isLandscape();
- mHiddenTop = hiddenTop;
- mShownTop = shownTop;
- mTargetShown = imeShouldShow;
- if (mLastAdjustTop < 0) {
- mLastAdjustTop = imeShouldShow ? hiddenTop : shownTop;
- }
- if (mAnimation != null || (mImeWasShown && imeShouldShow
- && mTargetAdjusted != mAdjusted)) {
- // We need to animate adjustment independently of the IME position, so
- // start our own animation to drive adjustment. This happens when a
- // different split's editor has gained focus while the IME is still visible.
- startAsyncAnimation();
- }
- // Reposition the server's secondary split position so that it evaluates
- // insets properly.
- WindowContainerTransaction wct = new WindowContainerTransaction();
- if (mTargetAdjusted) {
- mSplitLayout.updateAdjustedBounds(mShownTop, mHiddenTop, mShownTop);
- wct.setBounds(mSplits.mSecondary.token, mSplitLayout.mAdjustedSecondary);
- } else {
- wct.setBounds(mSplits.mSecondary.token, mSplitLayout.mSecondary);
- }
- try {
- ActivityTaskManager.getTaskOrganizerController()
- .applyContainerTransaction(wct, null /* organizer */);
- } catch (RemoteException e) {
- }
+ private boolean getSecondaryHasFocus(int displayId) {
+ try {
+ IWindowContainer imeSplit = ActivityTaskManager.getTaskOrganizerController()
+ .getImeTarget(displayId);
+ return imeSplit != null
+ && (imeSplit.asBinder() == mSplits.mSecondary.token.asBinder());
+ } catch (RemoteException e) {
+ Slog.w(TAG, "Failed to get IME target", e);
+ }
+ return false;
+ }
- // Update all the adjusted-for-ime states
- mView.setAdjustedForIme(mTargetShown, mTargetShown
- ? DisplayImeController.ANIMATION_DURATION_SHOW_MS
- : DisplayImeController.ANIMATION_DURATION_HIDE_MS);
- setAdjustedForIme(mTargetShown);
- }
+ private void updateDimTargets() {
+ final boolean splitIsVisible = !mView.isHidden();
+ mTargetPrimaryDim = (mSecondaryHasFocus && mTargetShown && splitIsVisible)
+ ? ADJUSTED_NONFOCUS_DIM : 0.f;
+ mTargetSecondaryDim = (!mSecondaryHasFocus && mTargetShown && splitIsVisible)
+ ? ADJUSTED_NONFOCUS_DIM : 0.f;
+ }
- @Override
- public void onImePositionChanged(int displayId, int imeTop,
- SurfaceControl.Transaction t) {
- if (mAnimation != null) {
- // Not synchronized with IME anymore, so return.
- return;
- }
- final float fraction = ((float) imeTop - mHiddenTop) / (mShownTop - mHiddenTop);
- final float progress = mTargetShown ? fraction : 1.f - fraction;
- onProgress(progress, t);
- }
-
- @Override
- public void onImeEndPositioning(int displayId, boolean cancelled,
- SurfaceControl.Transaction t) {
- if (mAnimation != null) {
- // Not synchronized with IME anymore, so return.
- return;
- }
- onEnd(cancelled, t);
- }
-
- private void onProgress(float progress, SurfaceControl.Transaction t) {
- if (mTargetAdjusted != mAdjusted) {
- final float fraction = mTargetAdjusted ? progress : 1.f - progress;
- mLastAdjustTop =
- (int) (fraction * mShownTop + (1.f - fraction) * mHiddenTop);
- mSplitLayout.updateAdjustedBounds(mLastAdjustTop, mHiddenTop, mShownTop);
- mView.resizeSplitSurfaces(t, mSplitLayout.mAdjustedPrimary,
- mSplitLayout.mAdjustedSecondary);
- }
- final float invProg = 1.f - progress;
- final float targetPrimaryDim = (mSecondaryHasFocus && mTargetShown)
- ? ADJUSTED_NONFOCUS_DIM : 0.f;
- final float targetSecondaryDim = (!mSecondaryHasFocus && mTargetShown)
- ? ADJUSTED_NONFOCUS_DIM : 0.f;
- mView.setResizeDimLayer(t, true /* primary */,
- mLastPrimaryDim * invProg + progress * targetPrimaryDim);
- mView.setResizeDimLayer(t, false /* primary */,
- mLastSecondaryDim * invProg + progress * targetSecondaryDim);
- }
-
- private void onEnd(boolean cancelled, SurfaceControl.Transaction t) {
- if (!cancelled) {
- onProgress(1.f, t);
+ @Override
+ public void onImeStartPositioning(int displayId, int hiddenTop, int shownTop,
+ boolean imeShouldShow, SurfaceControl.Transaction t) {
+ if (!inSplitMode()) {
+ return;
+ }
+ final boolean splitIsVisible = !mView.isHidden();
+ mSecondaryHasFocus = getSecondaryHasFocus(displayId);
+ final boolean targetAdjusted = splitIsVisible && imeShouldShow && mSecondaryHasFocus
+ && !mSplitLayout.mDisplayLayout.isLandscape();
+ mHiddenTop = hiddenTop;
+ mShownTop = shownTop;
+ mTargetShown = imeShouldShow;
+ if (mLastAdjustTop < 0) {
+ mLastAdjustTop = imeShouldShow ? hiddenTop : shownTop;
+ } else {
+ // Check for an "interruption" of an existing animation. In this case, we need to
+ // fake-flip the last-known state direction so that the animation completes in the
+ // other direction.
+ if (mTargetAdjusted != targetAdjusted && targetAdjusted == mAdjusted) {
+ if (mLastAdjustTop != (imeShouldShow ? mShownTop : mHiddenTop)) {
mAdjusted = mTargetAdjusted;
- mImeWasShown = mTargetShown;
- mLastAdjustTop = mAdjusted ? mShownTop : mHiddenTop;
- mLastPrimaryDim =
- (mSecondaryHasFocus && mTargetShown) ? ADJUSTED_NONFOCUS_DIM : 0.f;
- mLastSecondaryDim =
- (!mSecondaryHasFocus && mTargetShown) ? ADJUSTED_NONFOCUS_DIM : 0.f;
}
}
+ }
+ if (mPaused) {
+ mPausedTargetAdjusted = targetAdjusted;
+ if (DEBUG) Slog.d(TAG, " ime starting but paused " + dumpState());
+ return;
+ }
+ mTargetAdjusted = targetAdjusted;
+ updateDimTargets();
+ if (DEBUG) Slog.d(TAG, " ime starting. vis:" + splitIsVisible + " " + dumpState());
+ if (mAnimation != null || (mImeWasShown && imeShouldShow
+ && mTargetAdjusted != mAdjusted)) {
+ // We need to animate adjustment independently of the IME position, so
+ // start our own animation to drive adjustment. This happens when a
+ // different split's editor has gained focus while the IME is still visible.
+ startAsyncAnimation();
+ }
+ if (splitIsVisible) {
+ // If split is hidden, we don't want to trigger any relayouts that would cause the
+ // divider to show again.
+ updateImeAdjustState();
+ }
+ }
- private void startAsyncAnimation() {
- if (mAnimation != null) {
- mAnimation.cancel();
- }
- mAnimation = ValueAnimator.ofFloat(0.f, 1.f);
- mAnimation.setDuration(DisplayImeController.ANIMATION_DURATION_SHOW_MS);
- if (mTargetAdjusted != mAdjusted) {
- final float fraction =
- ((float) mLastAdjustTop - mHiddenTop) / (mShownTop - mHiddenTop);
- final float progress = mTargetAdjusted ? fraction : 1.f - fraction;
- mAnimation.setCurrentFraction(progress);
- }
+ private void updateImeAdjustState() {
+ // Reposition the server's secondary split position so that it evaluates
+ // insets properly.
+ WindowContainerTransaction wct = new WindowContainerTransaction();
+ if (mTargetAdjusted) {
+ mSplitLayout.updateAdjustedBounds(mShownTop, mHiddenTop, mShownTop);
+ wct.setBounds(mSplits.mSecondary.token, mSplitLayout.mAdjustedSecondary);
+ // "Freeze" the configuration size so that the app doesn't get a config
+ // or relaunch. This is required because normally nav-bar contributes
+ // to configuration bounds (via nondecorframe).
+ Rect adjustAppBounds = new Rect(mSplits.mSecondary.configuration
+ .windowConfiguration.getAppBounds());
+ adjustAppBounds.offset(0, mSplitLayout.mAdjustedSecondary.top
+ - mSplitLayout.mSecondary.top);
+ wct.setAppBounds(mSplits.mSecondary.token, adjustAppBounds);
+ wct.setScreenSizeDp(mSplits.mSecondary.token,
+ mSplits.mSecondary.configuration.screenWidthDp,
+ mSplits.mSecondary.configuration.screenHeightDp);
+ } else {
+ wct.setBounds(mSplits.mSecondary.token, mSplitLayout.mSecondary);
+ wct.setAppBounds(mSplits.mSecondary.token, null);
+ wct.setScreenSizeDp(mSplits.mSecondary.token,
+ SCREEN_WIDTH_DP_UNDEFINED, SCREEN_HEIGHT_DP_UNDEFINED);
+ }
+ try {
+ ActivityTaskManager.getTaskOrganizerController()
+ .applyContainerTransaction(wct, null /* organizer */);
+ } catch (RemoteException e) {
+ }
- mAnimation.addUpdateListener(animation -> {
- SurfaceControl.Transaction t = mTransactionPool.acquire();
- float value = (float) animation.getAnimatedValue();
- onProgress(value, t);
- t.apply();
- mTransactionPool.release(t);
- });
- mAnimation.setInterpolator(DisplayImeController.INTERPOLATOR);
- mAnimation.addListener(new AnimatorListenerAdapter() {
- private boolean mCancel = false;
- @Override
- public void onAnimationCancel(Animator animation) {
- mCancel = true;
- }
- @Override
- public void onAnimationEnd(Animator animation) {
- SurfaceControl.Transaction t = mTransactionPool.acquire();
- onEnd(mCancel, t);
- t.apply();
- mTransactionPool.release(t);
- mAnimation = null;
- }
- });
- mAnimation.start();
+ // Update all the adjusted-for-ime states
+ mView.setAdjustedForIme(mTargetShown, mTargetShown
+ ? DisplayImeController.ANIMATION_DURATION_SHOW_MS
+ : DisplayImeController.ANIMATION_DURATION_HIDE_MS);
+ setAdjustedForIme(mTargetShown);
+ }
+
+ @Override
+ public void onImePositionChanged(int displayId, int imeTop,
+ SurfaceControl.Transaction t) {
+ if (mAnimation != null || !inSplitMode() || mPaused) {
+ // Not synchronized with IME anymore, so return.
+ return;
+ }
+ final float fraction = ((float) imeTop - mHiddenTop) / (mShownTop - mHiddenTop);
+ final float progress = mTargetShown ? fraction : 1.f - fraction;
+ onProgress(progress, t);
+ }
+
+ @Override
+ public void onImeEndPositioning(int displayId, boolean cancelled,
+ SurfaceControl.Transaction t) {
+ if (mAnimation != null || !inSplitMode() || mPaused) {
+ // Not synchronized with IME anymore, so return.
+ return;
+ }
+ onEnd(cancelled, t);
+ }
+
+ private void onProgress(float progress, SurfaceControl.Transaction t) {
+ if (mTargetAdjusted != mAdjusted && !mPaused) {
+ final float fraction = mTargetAdjusted ? progress : 1.f - progress;
+ mLastAdjustTop = (int) (fraction * mShownTop + (1.f - fraction) * mHiddenTop);
+ mSplitLayout.updateAdjustedBounds(mLastAdjustTop, mHiddenTop, mShownTop);
+ mView.resizeSplitSurfaces(t, mSplitLayout.mAdjustedPrimary,
+ mSplitLayout.mAdjustedSecondary);
+ }
+ final float invProg = 1.f - progress;
+ mView.setResizeDimLayer(t, true /* primary */,
+ mLastPrimaryDim * invProg + progress * mTargetPrimaryDim);
+ mView.setResizeDimLayer(t, false /* primary */,
+ mLastSecondaryDim * invProg + progress * mTargetSecondaryDim);
+ }
+
+ private void onEnd(boolean cancelled, SurfaceControl.Transaction t) {
+ if (!cancelled) {
+ onProgress(1.f, t);
+ mAdjusted = mTargetAdjusted;
+ mImeWasShown = mTargetShown;
+ mLastAdjustTop = mAdjusted ? mShownTop : mHiddenTop;
+ mLastPrimaryDim = mTargetPrimaryDim;
+ mLastSecondaryDim = mTargetSecondaryDim;
+ }
+ }
+
+ private void startAsyncAnimation() {
+ if (mAnimation != null) {
+ mAnimation.cancel();
+ }
+ mAnimation = ValueAnimator.ofFloat(0.f, 1.f);
+ mAnimation.setDuration(DisplayImeController.ANIMATION_DURATION_SHOW_MS);
+ if (mTargetAdjusted != mAdjusted) {
+ final float fraction =
+ ((float) mLastAdjustTop - mHiddenTop) / (mShownTop - mHiddenTop);
+ final float progress = mTargetAdjusted ? fraction : 1.f - fraction;
+ mAnimation.setCurrentFraction(progress);
+ }
+
+ mAnimation.addUpdateListener(animation -> {
+ SurfaceControl.Transaction t = mTransactionPool.acquire();
+ float value = (float) animation.getAnimatedValue();
+ onProgress(value, t);
+ t.apply();
+ mTransactionPool.release(t);
+ });
+ mAnimation.setInterpolator(DisplayImeController.INTERPOLATOR);
+ mAnimation.addListener(new AnimatorListenerAdapter() {
+ private boolean mCancel = false;
+ @Override
+ public void onAnimationCancel(Animator animation) {
+ mCancel = true;
}
- };
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ SurfaceControl.Transaction t = mTransactionPool.acquire();
+ onEnd(mCancel, t);
+ t.apply();
+ mTransactionPool.release(t);
+ mAnimation = null;
+ }
+ });
+ mAnimation.start();
+ }
+
+ private String dumpState() {
+ return "top:" + mHiddenTop + "->" + mShownTop
+ + " adj:" + mAdjusted + "->" + mTargetAdjusted + "(" + mLastAdjustTop + ")"
+ + " shw:" + mImeWasShown + "->" + mTargetShown
+ + " dims:" + mLastPrimaryDim + "," + mLastSecondaryDim
+ + "->" + mTargetPrimaryDim + "," + mTargetSecondaryDim
+ + " shf:" + mSecondaryHasFocus + " desync:" + (mAnimation != null)
+ + " paus:" + mPaused + "[" + mPausedTargetAdjusted + "]";
+ }
+
+ /** Completely aborts/resets adjustment state */
+ public void pause(int displayId) {
+ if (DEBUG) Slog.d(TAG, "ime pause posting " + dumpState());
+ mHandler.post(() -> {
+ if (DEBUG) Slog.d(TAG, "ime pause run posted " + dumpState());
+ if (mPaused) {
+ return;
+ }
+ mPaused = true;
+ mPausedTargetAdjusted = mTargetAdjusted;
+ mTargetAdjusted = false;
+ mTargetPrimaryDim = mTargetSecondaryDim = 0.f;
+ updateImeAdjustState();
+ startAsyncAnimation();
+ });
+ }
+
+ public void resume(int displayId) {
+ if (DEBUG) Slog.d(TAG, "ime resume posting " + dumpState());
+ mHandler.post(() -> {
+ if (DEBUG) Slog.d(TAG, "ime resume run posted " + dumpState());
+ if (!mPaused) {
+ return;
+ }
+ mPaused = false;
+ mTargetAdjusted = mPausedTargetAdjusted;
+ updateDimTargets();
+ if ((mTargetAdjusted != mAdjusted) && !mMinimized && mView != null) {
+ // End unminimize animations since they conflict with adjustment animations.
+ mView.finishAnimations();
+ }
+ updateImeAdjustState();
+ startAsyncAnimation();
+ });
+ }
+ }
+ private final DividerImeController mImePositionProcessor = new DividerImeController();
public Divider(Context context, Optional<Lazy<Recents>> recentsOptionalLazy,
DisplayController displayController, SystemWindows systemWindows,
@@ -473,6 +562,7 @@
}
void updateVisibility(final boolean visible) {
+ if (DEBUG) Slog.d(TAG, "Updating visibility " + mVisible + "->" + visible);
if (mVisible != visible) {
mVisible = visible;
mView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
@@ -497,44 +587,58 @@
}
}
- private void setHomeStackResizable(boolean resizable) {
- if (mHomeStackResizable == resizable) {
- return;
- }
- mHomeStackResizable = resizable;
- if (!inSplitMode()) {
- return;
- }
- WindowManagerProxy.applyHomeTasksMinimized(mSplitLayout, mSplits.mSecondary.token);
- }
-
- private void updateMinimizedDockedStack(final boolean minimized, final long animDuration,
- final boolean isHomeStackResizable) {
- setHomeStackResizable(isHomeStackResizable);
- if (animDuration > 0) {
- mView.setMinimizedDockStack(minimized, animDuration, isHomeStackResizable);
- } else {
- mView.setMinimizedDockStack(minimized, isHomeStackResizable);
- }
- updateTouchable();
- }
-
/** Switch to minimized state if appropriate */
public void setMinimized(final boolean minimized) {
+ if (DEBUG) Slog.d(TAG, "posting ext setMinimized " + minimized + " vis:" + mVisible);
mHandler.post(() -> {
- if (!inSplitMode()) {
+ if (DEBUG) Slog.d(TAG, "run posted ext setMinimized " + minimized + " vis:" + mVisible);
+ if (!mVisible) {
return;
}
- if (mMinimized == minimized) {
- return;
- }
- mMinimized = minimized;
- WindowManagerProxy.applyPrimaryFocusable(mSplits, !mMinimized);
- mView.setMinimizedDockStack(minimized, getAnimDuration(), mHomeStackResizable);
- updateTouchable();
+ setHomeMinimized(minimized, mHomeStackResizable);
});
}
+ private void setHomeMinimized(final boolean minimized, boolean homeStackResizable) {
+ if (DEBUG) {
+ Slog.d(TAG, "setHomeMinimized min:" + mMinimized + "->" + minimized + " hrsz:"
+ + mHomeStackResizable + "->" + homeStackResizable + " split:" + inSplitMode());
+ }
+ WindowContainerTransaction wct = new WindowContainerTransaction();
+ // Update minimized state
+ if (mMinimized != minimized) {
+ mMinimized = minimized;
+ }
+ // Always set this because we could be entering split when mMinimized is already true
+ wct.setFocusable(mSplits.mPrimary.token, !mMinimized);
+
+ // Update home-stack resizability
+ if (mHomeStackResizable != homeStackResizable) {
+ mHomeStackResizable = homeStackResizable;
+ if (inSplitMode()) {
+ WindowManagerProxy.applyHomeTasksMinimized(
+ mSplitLayout, mSplits.mSecondary.token, wct);
+ }
+ }
+
+ // Sync state to DividerView if it exists.
+ if (mView != null) {
+ final int displayId = mView.getDisplay() != null
+ ? mView.getDisplay().getDisplayId() : DEFAULT_DISPLAY;
+ // pause ime here (before updateMinimizedDockedStack)
+ if (mMinimized) {
+ mImePositionProcessor.pause(displayId);
+ }
+ mView.setMinimizedDockStack(minimized, getAnimDuration(), homeStackResizable);
+ if (!mMinimized) {
+ // afterwards so it can end any animations started in view
+ mImePositionProcessor.resume(displayId);
+ }
+ }
+ updateTouchable();
+ WindowManagerProxy.applyContainerTransaction(wct);
+ }
+
void setAdjustedForIme(boolean adjustedForIme) {
if (mAdjustedForIme == adjustedForIme) {
return;
@@ -630,46 +734,24 @@
}
void ensureMinimizedSplit() {
- final boolean wasMinimized = mMinimized;
- mMinimized = true;
- setHomeStackResizable(mSplits.mSecondary.isResizable());
- WindowManagerProxy.applyPrimaryFocusable(mSplits, false /* focusable */);
+ setHomeMinimized(true /* minimized */, mSplits.mSecondary.isResizable());
if (!inSplitMode()) {
// Wasn't in split-mode yet, so enter now.
if (DEBUG) {
- Log.d(TAG, " entering split mode with minimized=true");
+ Slog.d(TAG, " entering split mode with minimized=true");
}
updateVisibility(true /* visible */);
- } else if (!wasMinimized) {
- if (DEBUG) {
- Log.d(TAG, " in split mode, but minimizing ");
- }
- // Was already in split-mode, update just minimized state.
- updateMinimizedDockedStack(mMinimized, getAnimDuration(),
- mHomeStackResizable);
}
}
void ensureNormalSplit() {
- if (mMinimized) {
- WindowManagerProxy.applyPrimaryFocusable(mSplits, true /* focusable */);
- }
+ setHomeMinimized(false /* minimized */, mHomeStackResizable);
if (!inSplitMode()) {
// Wasn't in split-mode, so enter now.
if (DEBUG) {
- Log.d(TAG, " enter split mode unminimized ");
+ Slog.d(TAG, " enter split mode unminimized ");
}
- mMinimized = false;
updateVisibility(true /* visible */);
}
- if (mMinimized) {
- // Was in minimized state, so leave that.
- if (DEBUG) {
- Log.d(TAG, " in split mode already, but unminimizing ");
- }
- mMinimized = false;
- updateMinimizedDockedStack(mMinimized, getAnimDuration(),
- mHomeStackResizable);
- }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
index 477cbb7..131f4e1 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerView.java
@@ -34,6 +34,7 @@
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
+import android.util.Slog;
import android.view.Choreographer;
import android.view.Display;
import android.view.InsetsState;
@@ -67,12 +68,15 @@
import com.android.systemui.shared.system.WindowManagerWrapper;
import com.android.systemui.statusbar.FlingAnimationUtils;
+import java.util.function.Consumer;
+
/**
* Docked stack divider.
*/
public class DividerView extends FrameLayout implements OnTouchListener,
OnComputeInternalInsetsListener {
private static final String TAG = "DividerView";
+ private static final boolean DEBUG = Divider.DEBUG;
public interface DividerCallbacks {
void onDraggingStart();
@@ -165,6 +169,10 @@
// The view is removed or in the process of been removed from the system.
private boolean mRemoved;
+ // Whether the surface for this view has been hidden regardless of actual visibility. This is
+ // used interact with keyguard.
+ private boolean mSurfaceHidden = false;
+
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
@@ -414,6 +422,10 @@
/** Unlike setVisible, this directly hides the surface without changing view visibility. */
void setHidden(boolean hidden) {
+ if (mSurfaceHidden == hidden) {
+ return;
+ }
+ mSurfaceHidden = hidden;
post(() -> {
final SurfaceControl sc = getWindowSurfaceControl();
if (sc == null) {
@@ -430,6 +442,10 @@
});
}
+ boolean isHidden() {
+ return mSurfaceHidden;
+ }
+
public boolean startDragging(boolean animate, boolean touching) {
cancelFlingAnimation();
if (touching) {
@@ -615,6 +631,7 @@
cancelFlingAnimation();
updateDockSide();
}
+ if (DEBUG) Slog.d(TAG, "Getting fling " + position + "->" + snapTarget.position);
final boolean taskPositionSameAtEnd = snapTarget.flag == SnapTarget.FLAG_NONE;
ValueAnimator anim = ValueAnimator.ofInt(position, snapTarget.position);
anim.addUpdateListener(animation -> resizeStackDelayed((int) animation.getAnimatedValue(),
@@ -622,16 +639,21 @@
? TASK_POSITION_SAME
: snapTarget.taskPosition,
snapTarget));
- Runnable endAction = () -> {
+ Consumer<Boolean> endAction = cancelled -> {
+ if (DEBUG) Slog.d(TAG, "End Fling " + cancelled + " min:" + mIsInMinimizeInteraction);
+ final boolean wasMinimizeInteraction = mIsInMinimizeInteraction;
+ // Reset minimized divider position after unminimized state animation finishes.
+ if (!cancelled && !mDockedStackMinimized && mIsInMinimizeInteraction) {
+ mIsInMinimizeInteraction = false;
+ }
boolean dismissed = commitSnapFlags(snapTarget);
mWindowManagerProxy.setResizing(false);
updateDockSide();
mCurrentAnimator = null;
mEntranceAnimationRunning = false;
mExitAnimationRunning = false;
- if (!dismissed) {
- WindowManagerProxy.applyResizeSplits((mIsInMinimizeInteraction
- ? mSnapTargetBeforeMinimized : snapTarget).position, mSplitLayout);
+ if (!dismissed && !wasMinimizeInteraction) {
+ WindowManagerProxy.applyResizeSplits(snapTarget.position, mSplitLayout);
}
if (mCallback != null) {
mCallback.onDraggingEnd();
@@ -655,12 +677,6 @@
}
}
};
- Runnable notCancelledEndAction = () -> {
- // Reset minimized divider position after unminimized state animation finishes
- if (!mDockedStackMinimized && mIsInMinimizeInteraction) {
- mIsInMinimizeInteraction = false;
- }
- };
anim.addListener(new AnimatorListenerAdapter() {
private boolean mCancelled;
@@ -682,15 +698,11 @@
delay = mSfChoreographer.getSurfaceFlingerOffsetMs();
}
if (delay == 0) {
- if (!mCancelled) {
- notCancelledEndAction.run();
- }
- endAction.run();
+ endAction.accept(mCancelled);
} else {
- if (!mCancelled) {
- mHandler.postDelayed(notCancelledEndAction, delay);
- }
- mHandler.postDelayed(endAction, delay);
+ final Boolean cancelled = mCancelled;
+ if (DEBUG) Slog.d(TAG, "Posting endFling " + cancelled + " d:" + delay + "ms");
+ mHandler.postDelayed(() -> endAction.accept(cancelled), delay);
}
}
});
@@ -887,6 +899,7 @@
public void setMinimizedDockStack(boolean minimized, long animDuration,
boolean isHomeStackResizable) {
+ if (DEBUG) Slog.d(TAG, "setMinDock: " + mDockedStackMinimized + "->" + minimized);
mHomeStackResizable = isHomeStackResizable;
updateDockSide();
if (!isHomeStackResizable) {
@@ -934,6 +947,15 @@
.start();
}
+ // Needed to end any currently playing animations when they might compete with other anims
+ // (specifically, IME adjust animation immediately after leaving minimized). Someday maybe
+ // these can be unified, but not today.
+ void finishAnimations() {
+ if (mCurrentAnimator != null) {
+ mCurrentAnimator.end();
+ }
+ }
+
public void setAdjustedForIme(boolean adjustedForIme, long animDuration) {
if (mAdjustedForIme == adjustedForIme) {
return;
@@ -1049,6 +1071,11 @@
mDividerPositionX = dockedRect.right;
mDividerPositionY = dockedRect.bottom;
+ if (DEBUG) {
+ Slog.d(TAG, "Resizing split surfaces: " + dockedRect + " " + dockedTaskRect
+ + " " + otherRect + " " + otherTaskRect);
+ }
+
t.setPosition(mTiles.mPrimarySurface, dockedTaskRect.left, dockedTaskRect.top);
Rect crop = new Rect(dockedRect);
crop.offsetTo(-Math.min(dockedTaskRect.left - dockedRect.left, 0),
@@ -1071,7 +1098,7 @@
void setResizeDimLayer(Transaction t, boolean primary, float alpha) {
SurfaceControl dim = primary ? mTiles.mPrimaryDim : mTiles.mSecondaryDim;
- if (alpha <= 0.f) {
+ if (alpha <= 0.001f) {
t.hide(dim);
} else {
t.setAlpha(dim, alpha);
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerWindowManager.java b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerWindowManager.java
index 3020a25..729df38 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/DividerWindowManager.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/DividerWindowManager.java
@@ -88,6 +88,9 @@
}
public void setTouchable(boolean touchable) {
+ if (mView == null) {
+ return;
+ }
boolean changed = false;
if (!touchable && (mLp.flags & FLAG_NOT_TOUCHABLE) == 0) {
mLp.flags |= FLAG_NOT_TOUCHABLE;
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/SplitScreenTaskOrganizer.java b/packages/SystemUI/src/com/android/systemui/stackdivider/SplitScreenTaskOrganizer.java
index 5cc8799..48ea4ae 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/SplitScreenTaskOrganizer.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/SplitScreenTaskOrganizer.java
@@ -88,7 +88,7 @@
}
@Override
- public void taskVanished(IWindowContainer container) {
+ public void taskVanished(RunningTaskInfo taskInfo) {
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/stackdivider/WindowManagerProxy.java b/packages/SystemUI/src/com/android/systemui/stackdivider/WindowManagerProxy.java
index 167c33a..fea57a3 100644
--- a/packages/SystemUI/src/com/android/systemui/stackdivider/WindowManagerProxy.java
+++ b/packages/SystemUI/src/com/android/systemui/stackdivider/WindowManagerProxy.java
@@ -21,6 +21,7 @@
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
import static android.view.Display.DEFAULT_DISPLAY;
+import android.annotation.NonNull;
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
import android.graphics.Rect;
@@ -137,17 +138,13 @@
return resizable;
}
- static void applyHomeTasksMinimized(SplitDisplayLayout layout, IWindowContainer parent) {
- applyHomeTasksMinimized(layout, parent, null /* transaction */);
- }
-
/**
* Assign a fixed override-bounds to home tasks that reflect their geometry while the primary
* split is minimized. This actually "sticks out" of the secondary split area, but when in
* minimized mode, the secondary split gets a 'negative' crop to expose it.
*/
static boolean applyHomeTasksMinimized(SplitDisplayLayout layout, IWindowContainer parent,
- WindowContainerTransaction t) {
+ @NonNull WindowContainerTransaction wct) {
// Resize the home/recents stacks to the larger minimized-state size
final Rect homeBounds;
final ArrayList<IWindowContainer> homeStacks = new ArrayList<>();
@@ -158,19 +155,9 @@
homeBounds = new Rect(0, 0, layout.mDisplayLayout.width(),
layout.mDisplayLayout.height());
}
- WindowContainerTransaction wct = t != null ? t : new WindowContainerTransaction();
for (int i = homeStacks.size() - 1; i >= 0; --i) {
wct.setBounds(homeStacks.get(i), homeBounds);
}
- if (t != null) {
- return isHomeResizable;
- }
- try {
- ActivityTaskManager.getTaskOrganizerController().applyContainerTransaction(wct,
- null /* organizer */);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to resize home stacks ", e);
- }
return isHomeResizable;
}
@@ -301,10 +288,8 @@
}
}
- static void applyPrimaryFocusable(SplitScreenTaskOrganizer splits, boolean focusable) {
+ static void applyContainerTransaction(WindowContainerTransaction wct) {
try {
- WindowContainerTransaction wct = new WindowContainerTransaction();
- wct.setFocusable(splits.mPrimary.token, focusable);
ActivityTaskManager.getTaskOrganizerController().applyContainerTransaction(wct,
null /* organizer */);
} catch (RemoteException e) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BlurUtils.kt b/packages/SystemUI/src/com/android/systemui/statusbar/BlurUtils.kt
index 34c0860..8669804 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BlurUtils.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BlurUtils.kt
@@ -40,8 +40,10 @@
) : Dumpable {
private val minBlurRadius = resources.getDimensionPixelSize(R.dimen.min_window_blur_radius)
private val maxBlurRadius = resources.getDimensionPixelSize(R.dimen.max_window_blur_radius)
- private val blurSysProp = SystemProperties
+ private val blurSupportedSysProp = SystemProperties
.getBoolean("ro.surface_flinger.supports_background_blur", false)
+ private val blurDisabledSysProp = SystemProperties
+ .getBoolean("persist.sys.sf.disable_blurs", false)
init {
dumpManager.registerDumpable(javaClass.name, this)
@@ -50,7 +52,7 @@
/**
* Translates a ratio from 0 to 1 to a blur radius in pixels.
*/
- fun radiusForRatio(ratio: Float): Int {
+ fun blurRadiusOfRatio(ratio: Float): Int {
if (ratio == 0f) {
return 0
}
@@ -58,6 +60,17 @@
}
/**
+ * Translates a blur radius in pixels to a ratio between 0 to 1.
+ */
+ fun ratioOfBlurRadius(blur: Int): Float {
+ if (blur == 0) {
+ return 0f
+ }
+ return MathUtils.map(minBlurRadius.toFloat(), maxBlurRadius.toFloat(),
+ 0f /* maxStart */, 1f /* maxStop */, blur.toFloat())
+ }
+
+ /**
* Applies background blurs to a {@link ViewRootImpl}.
*
* @param viewRootImpl The window root.
@@ -86,7 +99,7 @@
* @return {@code true} when supported.
*/
open fun supportsBlursOnWindows(): Boolean {
- return blurSysProp && ActivityManager.isHighEndGfx()
+ return blurSupportedSysProp && !blurDisabledSysProp && ActivityManager.isHighEndGfx()
}
override fun dump(fd: FileDescriptor, pw: PrintWriter, args: Array<out String>) {
@@ -95,7 +108,8 @@
it.increaseIndent()
it.println("minBlurRadius: $minBlurRadius")
it.println("maxBlurRadius: $maxBlurRadius")
- it.println("blurSysProp: $blurSysProp")
+ it.println("blurSupportedSysProp: $blurSupportedSysProp")
+ it.println("blurDisabledSysProp: $blurDisabledSysProp")
it.println("supportsBlursOnWindows: ${supportsBlursOnWindows()}")
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
index 3fe348f..94afde78 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java
@@ -262,7 +262,8 @@
default void showAuthenticationDialog(Bundle bundle,
IBiometricServiceReceiverInternal receiver, int biometricModality,
- boolean requireConfirmation, int userId, String opPackageName) { }
+ boolean requireConfirmation, int userId, String opPackageName,
+ long operationId) { }
default void onBiometricAuthenticated() { }
default void onBiometricHelp(String message) { }
default void onBiometricError(int modality, int error, int vendorCode) { }
@@ -780,7 +781,8 @@
@Override
public void showAuthenticationDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
- int biometricModality, boolean requireConfirmation, int userId, String opPackageName) {
+ int biometricModality, boolean requireConfirmation, int userId, String opPackageName,
+ long operationId) {
synchronized (mLock) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = bundle;
@@ -789,6 +791,7 @@
args.arg3 = requireConfirmation;
args.argi2 = userId;
args.arg4 = opPackageName;
+ args.arg5 = operationId;
mHandler.obtainMessage(MSG_BIOMETRIC_SHOW, args)
.sendToTarget();
}
@@ -1164,7 +1167,8 @@
someArgs.argi1 /* biometricModality */,
(boolean) someArgs.arg3 /* requireConfirmation */,
someArgs.argi2 /* userId */,
- (String) someArgs.arg4 /* opPackageName */);
+ (String) someArgs.arg4 /* opPackageName */,
+ (long) someArgs.arg5 /* operationId */);
}
someArgs.recycle();
break;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java
index 4597b16..b33424c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/HeadsUpStatusBarView.java
@@ -33,6 +33,7 @@
import com.android.systemui.R;
import com.android.systemui.plugins.DarkIconDispatcher;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry.OnSensitivityChangedListener;
import java.util.List;
@@ -159,20 +160,30 @@
}
public void setEntry(NotificationEntry entry) {
- if (entry != null) {
- mShowingEntry = entry;
+ if (mShowingEntry != null) {
+ mShowingEntry.removeOnSensitivityChangedListener(mOnSensitivityChangedListener);
+ }
+ mShowingEntry = entry;
+
+ if (mShowingEntry != null) {
CharSequence text = entry.headsUpStatusBarText;
if (entry.isSensitive()) {
text = entry.headsUpStatusBarTextPublic;
}
mTextView.setText(text);
- mShowingEntry.setOnSensitiveChangedListener(() -> setEntry(entry));
- } else if (mShowingEntry != null){
- mShowingEntry.setOnSensitiveChangedListener(null);
- mShowingEntry = null;
+ mShowingEntry.addOnSensitivityChangedListener(mOnSensitivityChangedListener);
}
}
+ private final OnSensitivityChangedListener mOnSensitivityChangedListener = entry -> {
+ if (entry != mShowingEntry) {
+ throw new IllegalStateException("Got a sensitivity change for " + entry
+ + " but mShowingEntry is " + mShowingEntry);
+ }
+ // Update the text
+ setEntry(entry);
+ };
+
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/MediaTransferManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/MediaTransferManager.java
index 18574f0..ac3523b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/MediaTransferManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/MediaTransferManager.java
@@ -32,6 +32,8 @@
import android.widget.LinearLayout;
import android.widget.TextView;
+import com.android.settingslib.bluetooth.LocalBluetoothManager;
+import com.android.settingslib.media.InfoMediaManager;
import com.android.settingslib.media.LocalMediaManager;
import com.android.settingslib.media.MediaDevice;
import com.android.settingslib.media.MediaOutputSliceConstants;
@@ -106,7 +108,9 @@
public MediaTransferManager(Context context) {
mContext = context;
mActivityStarter = Dependency.get(ActivityStarter.class);
- mLocalMediaManager = new LocalMediaManager(mContext, null, null);
+ LocalBluetoothManager lbm = Dependency.get(LocalBluetoothManager.class);
+ InfoMediaManager imm = new InfoMediaManager(mContext, null, null, lbm);
+ mLocalMediaManager = new LocalMediaManager(mContext, lbm, imm, null);
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
index ebac4b2..1b752452 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NavigationBarController.java
@@ -165,6 +165,7 @@
private void removeNavigationBar(int displayId) {
NavigationBarFragment navBar = mNavigationBars.get(displayId);
if (navBar != null) {
+ navBar.setAutoHideController(/* autoHideController */ null);
View navigationWindow = navBar.getView().getRootView();
WindowManagerGlobal.getInstance()
.removeView(navigationWindow, true /* immediate */);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationHeaderUtil.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationHeaderUtil.java
index 0bfcdbd..4759d56 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationHeaderUtil.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationHeaderUtil.java
@@ -23,6 +23,7 @@
import android.text.TextUtils;
import android.view.NotificationHeaderView;
import android.view.View;
+import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
@@ -182,24 +183,24 @@
private void sanitizeChild(View child) {
if (child != null) {
- NotificationHeaderView header = (NotificationHeaderView) child.findViewById(
+ ViewGroup header = child.findViewById(
com.android.internal.R.id.notification_header);
sanitizeHeader(header);
}
}
- private void sanitizeHeader(NotificationHeaderView rowHeader) {
+ private void sanitizeHeader(ViewGroup rowHeader) {
if (rowHeader == null) {
return;
}
final int childCount = rowHeader.getChildCount();
View time = rowHeader.findViewById(com.android.internal.R.id.time);
boolean hasVisibleText = false;
- for (int i = 1; i < childCount - 1 ; i++) {
+ for (int i = 0; i < childCount; i++) {
View child = rowHeader.getChildAt(i);
if (child instanceof TextView
&& child.getVisibility() != View.GONE
- && !mDividers.contains(Integer.valueOf(child.getId()))
+ && !mDividers.contains(child.getId())
&& child != time) {
hasVisibleText = true;
break;
@@ -212,14 +213,14 @@
time.setVisibility(timeVisibility);
View left = null;
View right;
- for (int i = 1; i < childCount - 1 ; i++) {
+ for (int i = 0; i < childCount; i++) {
View child = rowHeader.getChildAt(i);
- if (mDividers.contains(Integer.valueOf(child.getId()))) {
+ if (mDividers.contains(child.getId())) {
boolean visible = false;
// Lets find the item to the right
- for (i++; i < childCount - 1; i++) {
+ for (i++; i < childCount; i++) {
right = rowHeader.getChildAt(i);
- if (mDividers.contains(Integer.valueOf(right.getId()))) {
+ if (mDividers.contains(right.getId())) {
// A divider was found, this needs to be hidden
i--;
break;
@@ -276,14 +277,18 @@
if (!mApply) {
return;
}
- NotificationHeaderView header = row.getContractedNotificationHeader();
- if (header == null) {
- // No header found. We still consider this to be the same to avoid weird flickering
+ View contractedChild = row.getPrivateLayout().getContractedChild();
+ if (contractedChild == null) {
+ return;
+ }
+ View ownView = contractedChild.findViewById(mId);
+ if (ownView == null) {
+ // No view found. We still consider this to be the same to avoid weird flickering
// when for example showing an undo notification
return;
}
Object childData = mExtractor == null ? null : mExtractor.extractData(row);
- mApply = mComparator.compare(mParentView, header.findViewById(mId),
+ mApply = mComparator.compare(mParentView, ownView,
mParentData, childData);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
index 047edd2..72d9d0e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationListener.java
@@ -206,7 +206,8 @@
false,
false,
false,
- null
+ null,
+ false
);
}
return ranking;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
index 87be739..d8fdf92 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationMediaManager.java
@@ -70,6 +70,7 @@
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -262,11 +263,11 @@
synchronized (mEntryManager) {
NotificationEntry entry = mEntryManager
.getActiveNotificationUnfiltered(mMediaNotificationKey);
- if (entry == null || entry.expandedIcon == null) {
+ if (entry == null || entry.getIcons().getShelfIcon() == null) {
return null;
}
- return entry.expandedIcon.getSourceIcon();
+ return entry.getIcons().getShelfIcon().getSourceIcon();
}
}
@@ -284,8 +285,7 @@
boolean metaDataChanged = false;
synchronized (mEntryManager) {
- Set<NotificationEntry> allNotifications =
- mEntryManager.getPendingAndActiveNotifications();
+ Collection<NotificationEntry> allNotifications = mEntryManager.getAllNotifs();
// Promote the media notification with a controller in 'playing' state, if any.
NotificationEntry mediaNotification = null;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeWindowBlurController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
similarity index 60%
rename from packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeWindowBlurController.kt
rename to packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
index aadc451..8945f36 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeWindowBlurController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
@@ -19,12 +19,18 @@
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
+import android.app.WallpaperManager
import android.view.Choreographer
import android.view.View
+import androidx.annotation.VisibleForTesting
+import androidx.dynamicanimation.animation.FloatPropertyCompat
+import androidx.dynamicanimation.animation.SpringAnimation
+import androidx.dynamicanimation.animation.SpringForce
import com.android.internal.util.IndentingPrintWriter
import com.android.systemui.Dumpable
import com.android.systemui.Interpolators
import com.android.systemui.dump.DumpManager
+import com.android.systemui.plugins.statusbar.StatusBarStateController
import com.android.systemui.statusbar.phone.BiometricUnlockController
import com.android.systemui.statusbar.phone.BiometricUnlockController.MODE_WAKE_AND_UNLOCK
import com.android.systemui.statusbar.phone.NotificationShadeWindowController
@@ -40,57 +46,78 @@
* Controller responsible for statusbar window blur.
*/
@Singleton
-class NotificationShadeWindowBlurController @Inject constructor(
- private val statusBarStateController: SysuiStatusBarStateController,
+class NotificationShadeDepthController @Inject constructor(
+ private val statusBarStateController: StatusBarStateController,
private val blurUtils: BlurUtils,
private val biometricUnlockController: BiometricUnlockController,
private val keyguardStateController: KeyguardStateController,
- private val notificationShadeWindowController: NotificationShadeWindowController,
private val choreographer: Choreographer,
+ private val wallpaperManager: WallpaperManager,
+ private val notificationShadeWindowController: NotificationShadeWindowController,
dumpManager: DumpManager
) : PanelExpansionListener, Dumpable {
companion object {
private const val WAKE_UP_ANIMATION_ENABLED = true
- private const val SHADE_BLUR_ENABLED = true
}
lateinit var root: View
+ private var blurRoot: View? = null
private var keyguardAnimator: Animator? = null
private var notificationAnimator: Animator? = null
private var updateScheduled: Boolean = false
- private var shadeExpansion = 1.0f
+ private var shadeExpansion = 0f
+ @VisibleForTesting
+ var shadeSpring = SpringAnimation(this, object :
+ FloatPropertyCompat<NotificationShadeDepthController>("shadeBlurRadius") {
+ override fun setValue(rect: NotificationShadeDepthController?, value: Float) {
+ shadeBlurRadius = value.toInt()
+ }
+
+ override fun getValue(rect: NotificationShadeDepthController?): Float {
+ return shadeBlurRadius.toFloat()
+ }
+ })
+ private val zoomInterpolator = Interpolators.ACCELERATE_DECELERATE
+
+ /**
+ * Radius that we're animating to.
+ */
+ private var pendingShadeBlurRadius = -1
+
+ /**
+ * Shade blur radius on the current frame.
+ */
private var shadeBlurRadius = 0
set(value) {
if (field == value) return
field = value
scheduleUpdate()
}
- private var wakeAndUnlockBlurRadius = 0
- set(value) {
- if (field == value) return
- field = value
- scheduleUpdate()
- }
- private var incomingNotificationBlurRadius = 0
- set(value) {
- if (field == value) return
- field = value
- scheduleUpdate()
- }
/**
+ * Blur radius of the wake-up animation on this frame.
+ */
+ private var wakeAndUnlockBlurRadius = 0
+ set(value) {
+ if (field == value) return
+ field = value
+ scheduleUpdate()
+ }
+ private var globalDialogVisibility = 0f
+
+ /**
* Callback that updates the window blur value and is called only once per frame.
*/
private val updateBlurCallback = Choreographer.FrameCallback {
updateScheduled = false
- var notificationBlur = 0
- if (statusBarStateController.state == StatusBarState.KEYGUARD) {
- notificationBlur = (incomingNotificationBlurRadius * shadeExpansion).toInt()
- }
-
- val blur = max(max(shadeBlurRadius, wakeAndUnlockBlurRadius), notificationBlur)
- blurUtils.applyBlur(root.viewRootImpl, blur)
+ val blur = max(shadeBlurRadius,
+ max(wakeAndUnlockBlurRadius, blurUtils.blurRadiusOfRatio(globalDialogVisibility)))
+ blurUtils.applyBlur(blurRoot?.viewRootImpl ?: root.viewRootImpl, blur)
+ val rawZoom = max(blurUtils.ratioOfBlurRadius(blur), globalDialogVisibility)
+ wallpaperManager.setWallpaperZoomOut(root.windowToken,
+ zoomInterpolator.getInterpolation(rawZoom))
+ notificationShadeWindowController.setBackgroundBlurRadius(blur)
}
/**
@@ -110,7 +137,7 @@
interpolator = Interpolators.DECELERATE_QUINT
addUpdateListener { animation: ValueAnimator ->
wakeAndUnlockBlurRadius =
- blurUtils.radiusForRatio(animation.animatedValue as Float)
+ blurUtils.blurRadiusOfRatio(animation.animatedValue as Float)
}
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
@@ -130,47 +157,77 @@
}
}
+ private val statusBarStateCallback = object : StatusBarStateController.StateListener {
+ override fun onStateChanged(newState: Int) {
+ updateShadeBlur()
+ }
+
+ override fun onDozingChanged(isDozing: Boolean) {
+ if (isDozing && shadeSpring.isRunning) {
+ shadeSpring.skipToEnd()
+ }
+ }
+ }
+
init {
dumpManager.registerDumpable(javaClass.name, this)
if (WAKE_UP_ANIMATION_ENABLED) {
keyguardStateController.addCallback(keyguardStateCallback)
}
+ shadeSpring.spring = SpringForce(0.0f)
+ shadeSpring.spring.dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY
+ shadeSpring.spring.stiffness = SpringForce.STIFFNESS_LOW
+ shadeSpring.addEndListener { _, _, _, _ -> pendingShadeBlurRadius = -1 }
+ statusBarStateController.addCallback(statusBarStateCallback)
}
/**
* Update blurs when pulling down the shade
*/
override fun onPanelExpansionChanged(expansion: Float, tracking: Boolean) {
- if (!SHADE_BLUR_ENABLED) {
+ if (expansion == shadeExpansion) {
return
}
-
- var newBlur = 0
- if (statusBarStateController.state == StatusBarState.SHADE) {
- newBlur = blurUtils.radiusForRatio(expansion)
- }
-
- if (shadeBlurRadius == newBlur) {
- return
- }
- shadeBlurRadius = newBlur
- scheduleUpdate()
+ shadeExpansion = expansion
+ updateShadeBlur()
}
- private fun scheduleUpdate() {
+ private fun updateShadeBlur() {
+ var newBlur = 0
+ if (statusBarStateController.state == StatusBarState.SHADE) {
+ newBlur = blurUtils.blurRadiusOfRatio(shadeExpansion)
+ }
+
+ if (pendingShadeBlurRadius == newBlur) {
+ return
+ }
+ pendingShadeBlurRadius = newBlur
+ shadeSpring.animateToFinalPosition(newBlur.toFloat())
+ }
+
+ private fun scheduleUpdate(viewToBlur: View? = null) {
if (updateScheduled) {
return
}
updateScheduled = true
+ blurRoot = viewToBlur
choreographer.postFrameCallback(updateBlurCallback)
}
+ fun updateGlobalDialogVisibility(visibility: Float, dialogView: View) {
+ if (visibility == globalDialogVisibility) {
+ return
+ }
+ globalDialogVisibility = visibility
+ scheduleUpdate(dialogView)
+ }
+
override fun dump(fd: FileDescriptor, pw: PrintWriter, args: Array<out String>) {
- IndentingPrintWriter(pw, " ").use {
+ IndentingPrintWriter(pw, " ").let {
it.println("StatusBarWindowBlurController:")
it.increaseIndent()
it.println("shadeBlurRadius: $shadeBlurRadius")
it.println("wakeAndUnlockBlur: $wakeAndUnlockBlurRadius")
}
}
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index 1a8454c..d7f2ae4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -329,7 +329,7 @@
expandableRow.setAboveShelf(false);
}
if (notGoneIndex == 0) {
- StatusBarIconView icon = expandableRow.getEntry().expandedIcon;
+ StatusBarIconView icon = expandableRow.getEntry().getIcons().getShelfIcon();
NotificationIconContainer.IconState iconState = getIconState(icon);
// The icon state might be null in rare cases where the notification is actually
// added to the layout, but not to the shelf. An example are replied messages,
@@ -432,7 +432,7 @@
// if the shelf is clipped, lets make sure we also clip the icon
maxTop = Math.max(maxTop, getTranslationY() + getClipTopAmount());
}
- StatusBarIconView icon = row.getEntry().expandedIcon;
+ StatusBarIconView icon = row.getEntry().getIcons().getShelfIcon();
float shelfIconPosition = getTranslationY() + icon.getTop() + icon.getTranslationY();
if (shelfIconPosition < maxTop && !mAmbientState.isFullyHidden()) {
int top = (int) (maxTop - shelfIconPosition);
@@ -444,7 +444,7 @@
}
private void updateContinuousClipping(final ExpandableNotificationRow row) {
- StatusBarIconView icon = row.getEntry().expandedIcon;
+ StatusBarIconView icon = row.getEntry().getIcons().getShelfIcon();
boolean needsContinuousClipping = ViewState.isAnimatingY(icon) && !mAmbientState.isDozing();
boolean isContinuousClipping = icon.getTag(TAG_CONTINUOUS_CLIPPING) != null;
if (needsContinuousClipping && !isContinuousClipping) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java b/packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java
index 04f1c32..7f30009 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ScrimView.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar;
+import static java.lang.Float.isNaN;
+
import android.annotation.NonNull;
import android.content.Context;
import android.graphics.Canvas;
@@ -179,6 +181,9 @@
* @param alpha Gradient alpha from 0 to 1.
*/
public void setViewAlpha(float alpha) {
+ if (isNaN(alpha)) {
+ throw new IllegalArgumentException("alpha cannot be NaN: " + alpha);
+ }
if (alpha != mViewAlpha) {
mViewAlpha = alpha;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ViewTransformationHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/ViewTransformationHelper.java
index 7b5a70e..2a45bc2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ViewTransformationHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ViewTransformationHelper.java
@@ -41,6 +41,7 @@
private static final int TAG_CONTAINS_TRANSFORMED_VIEW = R.id.contains_transformed_view;
private ArrayMap<Integer, View> mTransformedViews = new ArrayMap<>();
+ private ArraySet<Integer> mKeysTransformingToSimilar = new ArraySet<>();
private ArrayMap<Integer, CustomTransformation> mCustomTransformations = new ArrayMap<>();
private ValueAnimator mViewTransformationAnimation;
@@ -48,8 +49,22 @@
mTransformedViews.put(key, transformedView);
}
+ /**
+ * Add a view that transforms to a similar sibling, meaning that we should consider any mapping
+ * found treated as the same viewType. This is useful for imageViews, where it's hard to compare
+ * if the source images are the same when they are bitmap based.
+ *
+ * @param key The key how this is added
+ * @param transformedView the view that is added
+ */
+ public void addViewTransformingToSimilar(int key, View transformedView) {
+ addTransformedView(key, transformedView);
+ mKeysTransformingToSimilar.add(key);
+ }
+
public void reset() {
mTransformedViews.clear();
+ mKeysTransformingToSimilar.clear();
}
public void setCustomTransformation(CustomTransformation transformation, int viewType) {
@@ -60,7 +75,11 @@
public TransformState getCurrentState(int fadingView) {
View view = mTransformedViews.get(fadingView);
if (view != null && view.getVisibility() != View.GONE) {
- return TransformState.createFrom(view, this);
+ TransformState transformState = TransformState.createFrom(view, this);
+ if (mKeysTransformingToSimilar.contains(fadingView)) {
+ transformState.setIsSameAsAnyView(true);
+ }
+ return transformState;
}
return null;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java
index 53605e5..7c06157 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/ActivityLaunchAnimator.java
@@ -282,7 +282,7 @@
.withCornerRadius(mCornerRadius)
.withVisibility(true)
.build();
- mSyncRtTransactionApplier.scheduleApply(params);
+ mSyncRtTransactionApplier.scheduleApply(true /* earlyWakeup */, params);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/MessagingLayoutTransformState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/MessagingLayoutTransformState.java
index b732966..9383f53 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/MessagingLayoutTransformState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/MessagingLayoutTransformState.java
@@ -21,9 +21,9 @@
import android.view.View;
import android.view.ViewGroup;
+import com.android.internal.widget.IMessagingLayout;
import com.android.internal.widget.MessagingGroup;
import com.android.internal.widget.MessagingImageMessage;
-import com.android.internal.widget.MessagingLayout;
import com.android.internal.widget.MessagingLinearLayout;
import com.android.internal.widget.MessagingMessage;
import com.android.internal.widget.MessagingPropertyAnimator;
@@ -41,7 +41,7 @@
private static Pools.SimplePool<MessagingLayoutTransformState> sInstancePool
= new Pools.SimplePool<>(40);
private MessagingLinearLayout mMessageContainer;
- private MessagingLayout mMessagingLayout;
+ private IMessagingLayout mMessagingLayout;
private HashMap<MessagingGroup, MessagingGroup> mGroupMap = new HashMap<>();
private float mRelativeTranslationOffset;
@@ -266,8 +266,9 @@
transformView(transformationAmount, to, child, otherChild, false, /* sameAsAny */
useLinearTransformation);
boolean otherIsIsolated = otherGroup.getIsolatedMessage() == otherChild;
- if (transformationAmount == 0.0f && otherIsIsolated) {
- ownGroup.setTransformingImages(true);
+ if (transformationAmount == 0.0f
+ && (otherIsIsolated || otherGroup.isSingleLine())) {
+ ownGroup.setClippingDisabled(true);
}
if (otherChild == null) {
child.setTranslationY(previousTranslation);
@@ -291,11 +292,20 @@
if (useLinearTransformation) {
ownState.setDefaultInterpolator(Interpolators.LINEAR);
}
- ownState.setIsSameAsAnyView(sameAsAny);
+ ownState.setIsSameAsAnyView(sameAsAny && !isGone(otherView));
if (to) {
if (otherView != null) {
TransformState otherState = TransformState.createFrom(otherView, mTransformInfo);
- ownState.transformViewTo(otherState, transformationAmount);
+ if (!isGone(otherView)) {
+ ownState.transformViewTo(otherState, transformationAmount);
+ } else {
+ if (!isGone(ownView)) {
+ ownState.disappear(transformationAmount, null);
+ }
+ // We still want to transform vertically if the view is gone,
+ // since avatars serve as anchors for the rest of the layout transition
+ ownState.transformViewVerticalTo(otherState, transformationAmount);
+ }
otherState.recycle();
} else {
ownState.disappear(transformationAmount, null);
@@ -303,7 +313,16 @@
} else {
if (otherView != null) {
TransformState otherState = TransformState.createFrom(otherView, mTransformInfo);
- ownState.transformViewFrom(otherState, transformationAmount);
+ if (!isGone(otherView)) {
+ ownState.transformViewFrom(otherState, transformationAmount);
+ } else {
+ if (!isGone(ownView)) {
+ ownState.appear(transformationAmount, null);
+ }
+ // We still want to transform vertically if the view is gone,
+ // since avatars serve as anchors for the rest of the layout transition
+ ownState.transformViewVerticalFrom(otherState, transformationAmount);
+ }
otherState.recycle();
} else {
ownState.appear(transformationAmount, null);
@@ -337,6 +356,9 @@
}
private boolean isGone(View view) {
+ if (view == null) {
+ return true;
+ }
if (view.getVisibility() == View.GONE) {
return true;
}
@@ -408,7 +430,7 @@
ownGroup.getMessageContainer().setTranslationY(0);
ownGroup.getSenderView().setTranslationY(0);
}
- ownGroup.setTransformingImages(false);
+ ownGroup.setClippingDisabled(false);
ownGroup.updateClipRect();
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
index 7f0479c..c6d84ff 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationEntryManager.java
@@ -29,6 +29,7 @@
import android.service.notification.NotificationListenerService.RankingMap;
import android.service.notification.StatusBarNotification;
import android.util.ArrayMap;
+import android.util.ArraySet;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -56,9 +57,9 @@
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -105,6 +106,10 @@
*/
public static final int UNDEFINED_DISMISS_REASON = 0;
+ private final Set<NotificationEntry> mAllNotifications = new ArraySet<>();
+ private final Set<NotificationEntry> mReadOnlyAllNotifications =
+ Collections.unmodifiableSet(mAllNotifications);
+
/** Pending notifications are ones awaiting inflation */
@VisibleForTesting
protected final HashMap<String, NotificationEntry> mPendingNotifications = new HashMap<>();
@@ -468,6 +473,8 @@
entry.removeRow();
}
+ mAllNotifications.remove(entry);
+
// Let's remove the children if this was a summary
handleGroupSummaryRemoved(key);
removeVisibleNotification(key);
@@ -548,6 +555,7 @@
notification,
ranking,
mFgsFeatureController.isForegroundServiceDismissalEnabled());
+ mAllNotifications.add(entry);
mLeakDetector.trackInstance(entry);
@@ -709,15 +717,6 @@
}
/**
- * @return all notifications we're currently aware of (both pending and active notifications)
- */
- public Set<NotificationEntry> getPendingAndActiveNotifications() {
- Set<NotificationEntry> allNotifs = new HashSet<>(mPendingNotifications.values());
- allNotifs.addAll(mSortedAndFiltered);
- return allNotifs;
- }
-
- /**
* Use this method to retrieve a notification entry that has been prepared for presentation.
* Note that the notification may be filtered out and never shown to the user.
*
@@ -842,7 +841,7 @@
private void dumpEntry(PrintWriter pw, String indent, int i, NotificationEntry e) {
pw.print(indent);
- pw.println(" [" + i + "] key=" + e.getKey() + " icon=" + e.icon);
+ pw.println(" [" + i + "] key=" + e.getKey() + " icon=" + e.getIcons().getStatusBarIcon());
StatusBarNotification n = e.getSbn();
pw.print(indent);
pw.println(" pkg=" + n.getPackageName() + " id=" + n.getId() + " importance="
@@ -861,6 +860,15 @@
return mReadOnlyNotifications;
}
+ /**
+ * Returns a collections containing ALL notifications we know about, including ones that are
+ * hidden or for other users. See {@link CommonNotifCollection#getAllNotifs()}.
+ */
+ @Override
+ public Collection<NotificationEntry> getAllNotifs() {
+ return mReadOnlyAllNotifications;
+ }
+
/** @return A count of the active notifications */
public int getActiveNotificationsCount() {
return mReadOnlyNotifications.size();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
index 8a23e37..2747696 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
@@ -17,7 +17,6 @@
package com.android.systemui.statusbar.notification
import android.animation.ObjectAnimator
-import android.content.Context
import android.util.FloatProperty
import com.android.systemui.Interpolators
import com.android.systemui.plugins.statusbar.StatusBarStateController
@@ -26,10 +25,10 @@
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout
import com.android.systemui.statusbar.notification.stack.StackStateAnimator
import com.android.systemui.statusbar.phone.DozeParameters
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone
import com.android.systemui.statusbar.phone.KeyguardBypassController
import com.android.systemui.statusbar.phone.NotificationIconAreaController
import com.android.systemui.statusbar.phone.PanelExpansionListener
+import com.android.systemui.statusbar.policy.HeadsUpManager
import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener
import javax.inject.Inject
@@ -37,15 +36,14 @@
@Singleton
class NotificationWakeUpCoordinator @Inject constructor(
- private val mHeadsUpManagerPhone: HeadsUpManagerPhone,
- private val statusBarStateController: StatusBarStateController,
- private val bypassController: KeyguardBypassController,
- private val dozeParameters: DozeParameters)
- : OnHeadsUpChangedListener, StatusBarStateController.StateListener,
- PanelExpansionListener {
+ private val mHeadsUpManager: HeadsUpManager,
+ private val statusBarStateController: StatusBarStateController,
+ private val bypassController: KeyguardBypassController,
+ private val dozeParameters: DozeParameters
+) : OnHeadsUpChangedListener, StatusBarStateController.StateListener, PanelExpansionListener {
- private val mNotificationVisibility
- = object : FloatProperty<NotificationWakeUpCoordinator>("notificationVisibility") {
+ private val mNotificationVisibility = object : FloatProperty<NotificationWakeUpCoordinator>(
+ "notificationVisibility") {
override fun setValue(coordinator: NotificationWakeUpCoordinator, value: Float) {
coordinator.setVisibilityAmount(value)
@@ -78,10 +76,10 @@
field = value
willWakeUp = false
if (value) {
- if (mNotificationsVisible && !mNotificationsVisibleForExpansion
- && !bypassController.bypassEnabled) {
+ if (mNotificationsVisible && !mNotificationsVisibleForExpansion &&
+ !bypassController.bypassEnabled) {
// We're waking up while pulsing, let's make sure the animation looks nice
- mStackScroller.wakeUpFromPulse();
+ mStackScroller.wakeUpFromPulse()
}
if (bypassController.bypassEnabled && !mNotificationsVisible) {
// Let's make sure our huns become visible once we are waking up in case
@@ -100,7 +98,7 @@
}
private var collapsedEnoughToHide: Boolean = false
- lateinit var iconAreaController : NotificationIconAreaController
+ lateinit var iconAreaController: NotificationIconAreaController
var pulsing: Boolean = false
set(value) {
@@ -132,8 +130,8 @@
var canShow = pulsing
if (bypassController.bypassEnabled) {
// We also allow pulsing on the lock screen!
- canShow = canShow || (wakingUp || willWakeUp || fullyAwake)
- && statusBarStateController.state == StatusBarState.KEYGUARD
+ canShow = canShow || (wakingUp || willWakeUp || fullyAwake) &&
+ statusBarStateController.state == StatusBarState.KEYGUARD
// We want to hide the notifications when collapsed too much
if (collapsedEnoughToHide) {
canShow = false
@@ -143,7 +141,7 @@
}
init {
- mHeadsUpManagerPhone.addListener(this)
+ mHeadsUpManager.addListener(this)
statusBarStateController.addCallback(this)
addListener(object : WakeUpListener {
override fun onFullyHiddenChanged(isFullyHidden: Boolean) {
@@ -155,7 +153,7 @@
increaseSpeed = false)
}
}
- });
+ })
}
fun setStackScroller(stackScroller: NotificationStackScrollLayout) {
@@ -178,46 +176,55 @@
* @param animate should this change be animated
* @param increaseSpeed should the speed be increased of the animation
*/
- fun setNotificationsVisibleForExpansion(visible: Boolean, animate: Boolean,
- increaseSpeed: Boolean) {
+ fun setNotificationsVisibleForExpansion(
+ visible: Boolean,
+ animate: Boolean,
+ increaseSpeed: Boolean
+ ) {
mNotificationsVisibleForExpansion = visible
updateNotificationVisibility(animate, increaseSpeed)
if (!visible && mNotificationsVisible) {
// If we stopped expanding and we're still visible because we had a pulse that hasn't
// times out, let's release them all to make sure were not stuck in a state where
// notifications are visible
- mHeadsUpManagerPhone.releaseAllImmediately()
+ mHeadsUpManager.releaseAllImmediately()
}
}
fun addListener(listener: WakeUpListener) {
- wakeUpListeners.add(listener);
+ wakeUpListeners.add(listener)
}
fun removeListener(listener: WakeUpListener) {
- wakeUpListeners.remove(listener);
+ wakeUpListeners.remove(listener)
}
- private fun updateNotificationVisibility(animate: Boolean, increaseSpeed: Boolean) {
+ private fun updateNotificationVisibility(
+ animate: Boolean,
+ increaseSpeed: Boolean
+ ) {
// TODO: handle Lockscreen wakeup for bypass when we're not pulsing anymore
- var visible = mNotificationsVisibleForExpansion || mHeadsUpManagerPhone.hasNotifications()
+ var visible = mNotificationsVisibleForExpansion || mHeadsUpManager.hasNotifications()
visible = visible && canShowPulsingHuns
if (!visible && mNotificationsVisible && (wakingUp || willWakeUp) && mDozeAmount != 0.0f) {
// let's not make notifications invisible while waking up, otherwise the animation
// is strange
- return;
+ return
}
setNotificationsVisible(visible, animate, increaseSpeed)
}
- private fun setNotificationsVisible(visible: Boolean, animate: Boolean,
- increaseSpeed: Boolean) {
+ private fun setNotificationsVisible(
+ visible: Boolean,
+ animate: Boolean,
+ increaseSpeed: Boolean
+ ) {
if (mNotificationsVisible == visible) {
return
}
mNotificationsVisible = visible
- mVisibilityAnimator?.cancel();
+ mVisibilityAnimator?.cancel()
if (animate) {
notifyAnimationStart(visible)
startVisibilityAnimation(increaseSpeed)
@@ -230,8 +237,8 @@
if (updateDozeAmountIfBypass()) {
return
}
- if (linear != 1.0f && linear != 0.0f
- && (mLinearDozeAmount == 0.0f || mLinearDozeAmount == 1.0f)) {
+ if (linear != 1.0f && linear != 0.0f &&
+ (mLinearDozeAmount == 0.0f || mLinearDozeAmount == 1.0f)) {
// Let's notify the scroller that an animation started
notifyAnimationStart(mLinearDozeAmount == 1.0f)
}
@@ -245,17 +252,17 @@
mStackScroller.setDozeAmount(mDozeAmount)
updateHideAmount()
if (changed && linear == 0.0f) {
- setNotificationsVisible(visible = false, animate = false, increaseSpeed = false);
+ setNotificationsVisible(visible = false, animate = false, increaseSpeed = false)
setNotificationsVisibleForExpansion(visible = false, animate = false,
increaseSpeed = false)
}
}
override fun onStateChanged(newState: Int) {
- updateDozeAmountIfBypass();
+ updateDozeAmountIfBypass()
if (bypassController.bypassEnabled &&
- newState == StatusBarState.KEYGUARD && state == StatusBarState.SHADE_LOCKED
- && (!statusBarStateController.isDozing || shouldAnimateVisibility())) {
+ newState == StatusBarState.KEYGUARD && state == StatusBarState.SHADE_LOCKED &&
+ (!statusBarStateController.isDozing || shouldAnimateVisibility())) {
// We're leaving shade locked. Let's animate the notifications away
setNotificationsVisible(visible = true, increaseSpeed = false, animate = false)
setNotificationsVisible(visible = false, increaseSpeed = false, animate = true)
@@ -266,23 +273,23 @@
override fun onPanelExpansionChanged(expansion: Float, tracking: Boolean) {
val collapsedEnough = expansion <= 0.9f
if (collapsedEnough != this.collapsedEnoughToHide) {
- val couldShowPulsingHuns = canShowPulsingHuns;
+ val couldShowPulsingHuns = canShowPulsingHuns
this.collapsedEnoughToHide = collapsedEnough
if (couldShowPulsingHuns && !canShowPulsingHuns) {
updateNotificationVisibility(animate = true, increaseSpeed = true)
- mHeadsUpManagerPhone.releaseAllImmediately()
+ mHeadsUpManager.releaseAllImmediately()
}
}
}
private fun updateDozeAmountIfBypass(): Boolean {
if (bypassController.bypassEnabled) {
- var amount = 1.0f;
- if (statusBarStateController.state == StatusBarState.SHADE
- || statusBarStateController.state == StatusBarState.SHADE_LOCKED) {
- amount = 0.0f;
+ var amount = 1.0f
+ if (statusBarStateController.state == StatusBarState.SHADE ||
+ statusBarStateController.state == StatusBarState.SHADE_LOCKED) {
+ amount = 0.0f
}
- setDozeAmount(amount, amount)
+ setDozeAmount(amount, amount)
return true
}
return false
@@ -300,7 +307,7 @@
visibilityAnimator.setInterpolator(Interpolators.LINEAR)
var duration = StackStateAnimator.ANIMATION_DURATION_WAKEUP.toLong()
if (increaseSpeed) {
- duration = (duration.toFloat() / 1.5F).toLong();
+ duration = (duration.toFloat() / 1.5F).toLong()
}
visibilityAnimator.setDuration(duration)
visibilityAnimator.start()
@@ -311,7 +318,7 @@
mLinearVisibilityAmount = visibilityAmount
mVisibilityAmount = mVisibilityInterpolator.getInterpolation(
visibilityAmount)
- handleAnimationFinished();
+ handleAnimationFinished()
updateHideAmount()
}
@@ -322,7 +329,7 @@
}
}
- fun getWakeUpHeight() : Float {
+ fun getWakeUpHeight(): Float {
return mStackScroller.wakeUpHeight
}
@@ -330,7 +337,7 @@
val linearAmount = Math.min(1.0f - mLinearVisibilityAmount, mLinearDozeAmount)
val amount = Math.min(1.0f - mVisibilityAmount, mDozeAmount)
mStackScroller.setHideAmount(linearAmount, amount)
- notificationsFullyHidden = linearAmount == 1.0f;
+ notificationsFullyHidden = linearAmount == 1.0f
}
private fun notifyAnimationStart(awake: Boolean) {
@@ -361,7 +368,7 @@
// if we animate, we see the shelf briefly visible. Instead we fully animate
// the notification and its background out
animate = false
- } else if (!wakingUp && !willWakeUp){
+ } else if (!wakingUp && !willWakeUp) {
// TODO: look that this is done properly and not by anyone else
entry.setHeadsUpAnimatingAway(true)
mEntrySetToClearWhenFinished.add(entry)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
index 749e5e2..b90cfa8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifCollection.java
@@ -64,24 +64,34 @@
import com.android.systemui.statusbar.notification.collection.coalescer.CoalescedEvent;
import com.android.systemui.statusbar.notification.collection.coalescer.GroupCoalescer;
import com.android.systemui.statusbar.notification.collection.coalescer.GroupCoalescer.BatchableNotificationHandler;
+import com.android.systemui.statusbar.notification.collection.notifcollection.CleanUpEntryEvent;
import com.android.systemui.statusbar.notification.collection.notifcollection.CollectionReadyForBuildListener;
import com.android.systemui.statusbar.notification.collection.notifcollection.DismissedByUserStats;
+import com.android.systemui.statusbar.notification.collection.notifcollection.EntryAddedEvent;
+import com.android.systemui.statusbar.notification.collection.notifcollection.EntryRemovedEvent;
+import com.android.systemui.statusbar.notification.collection.notifcollection.EntryUpdatedEvent;
+import com.android.systemui.statusbar.notification.collection.notifcollection.InitEntryEvent;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionLogger;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifDismissInterceptor;
+import com.android.systemui.statusbar.notification.collection.notifcollection.NotifEvent;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender;
+import com.android.systemui.statusbar.notification.collection.notifcollection.RankingAppliedEvent;
+import com.android.systemui.statusbar.notification.collection.notifcollection.RankingUpdatedEvent;
import com.android.systemui.util.Assert;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Queue;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -124,6 +134,8 @@
private final List<NotifLifetimeExtender> mLifetimeExtenders = new ArrayList<>();
private final List<NotifDismissInterceptor> mDismissInterceptors = new ArrayList<>();
+ private Queue<NotifEvent> mEventQueue = new ArrayDeque<>();
+
private boolean mAttached = false;
private boolean mAmDispatchingToOtherCode;
@@ -160,8 +172,8 @@
mBuildListener = buildListener;
}
- /** @see NotifPipeline#getActiveNotifs() */
- Collection<NotificationEntry> getActiveNotifs() {
+ /** @see NotifPipeline#getAllNotifs() */
+ Collection<NotificationEntry> getAllNotifs() {
Assert.isMainThread();
return mReadOnlyNotificationSet;
}
@@ -242,7 +254,7 @@
}
locallyDismissNotifications(entriesToLocallyDismiss);
- rebuildList();
+ dispatchEventsAndRebuildList();
}
/**
@@ -251,8 +263,7 @@
public void dismissNotification(
NotificationEntry entry,
@NonNull DismissedByUserStats stats) {
- dismissNotifications(List.of(
- new Pair<NotificationEntry, DismissedByUserStats>(entry, stats)));
+ dismissNotifications(List.of(new Pair<>(entry, stats)));
}
/**
@@ -268,7 +279,7 @@
// system process is dead if we're here.
}
- final List<NotificationEntry> entries = new ArrayList(getActiveNotifs());
+ final List<NotificationEntry> entries = new ArrayList<>(getAllNotifs());
for (int i = entries.size() - 1; i >= 0; i--) {
NotificationEntry entry = entries.get(i);
if (!shouldDismissOnClearAll(entry, userId)) {
@@ -283,7 +294,7 @@
}
locallyDismissNotifications(entries);
- rebuildList();
+ dispatchEventsAndRebuildList();
}
/**
@@ -326,8 +337,9 @@
private void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
Assert.isMainThread();
- postNotification(sbn, requireRanking(rankingMap, sbn.getKey()), rankingMap);
- rebuildList();
+ postNotification(sbn, requireRanking(rankingMap, sbn.getKey()));
+ applyRanking(rankingMap);
+ dispatchEventsAndRebuildList();
}
private void onNotificationGroupPosted(List<CoalescedEvent> batch) {
@@ -336,9 +348,9 @@
mLogger.logNotifGroupPosted(batch.get(0).getSbn().getGroupKey(), batch.size());
for (CoalescedEvent event : batch) {
- postNotification(event.getSbn(), event.getRanking(), null);
+ postNotification(event.getSbn(), event.getRanking());
}
- rebuildList();
+ dispatchEventsAndRebuildList();
}
private void onNotificationRemoved(
@@ -354,55 +366,49 @@
throw new IllegalStateException("No notification to remove with key " + sbn.getKey());
}
entry.mCancellationReason = reason;
- applyRanking(rankingMap);
tryRemoveNotification(entry);
- rebuildList();
+ applyRanking(rankingMap);
+ dispatchEventsAndRebuildList();
}
private void onNotificationRankingUpdate(RankingMap rankingMap) {
Assert.isMainThread();
+ mEventQueue.add(new RankingUpdatedEvent(rankingMap));
applyRanking(rankingMap);
- dispatchNotificationRankingUpdate(rankingMap);
- rebuildList();
+ dispatchEventsAndRebuildList();
}
private void postNotification(
StatusBarNotification sbn,
- Ranking ranking,
- @Nullable RankingMap rankingMap) {
+ Ranking ranking) {
NotificationEntry entry = mNotificationSet.get(sbn.getKey());
if (entry == null) {
// A new notification!
- mLogger.logNotifPosted(sbn.getKey());
-
entry = new NotificationEntry(sbn, ranking);
mNotificationSet.put(sbn.getKey(), entry);
- dispatchOnEntryInit(entry);
- if (rankingMap != null) {
- applyRanking(rankingMap);
- }
-
- dispatchOnEntryAdded(entry);
+ mLogger.logNotifPosted(sbn.getKey());
+ mEventQueue.add(new InitEntryEvent(entry));
+ mEventQueue.add(new EntryAddedEvent(entry));
} else {
// Update to an existing entry
- mLogger.logNotifUpdated(sbn.getKey());
// Notification is updated so it is essentially re-added and thus alive again, so we
// can reset its state.
+ // TODO: If a coalesced event ever gets here, it's possible to lose track of children,
+ // since their rankings might have been updated earlier (and thus we may no longer
+ // think a child is associated with this locally-dismissed entry).
cancelLocalDismissal(entry);
cancelLifetimeExtension(entry);
cancelDismissInterception(entry);
entry.mCancellationReason = REASON_NOT_CANCELED;
entry.setSbn(sbn);
- if (rankingMap != null) {
- applyRanking(rankingMap);
- }
- dispatchOnEntryUpdated(entry);
+ mLogger.logNotifUpdated(sbn.getKey());
+ mEventQueue.add(new EntryUpdatedEvent(entry));
}
}
@@ -432,8 +438,8 @@
if (!isLifetimeExtended(entry)) {
mNotificationSet.remove(entry.getKey());
cancelDismissInterception(entry);
- dispatchOnEntryRemoved(entry, entry.mCancellationReason);
- dispatchOnEntryCleanUp(entry);
+ mEventQueue.add(new EntryRemovedEvent(entry, entry.mCancellationReason));
+ mEventQueue.add(new CleanUpEntryEvent(entry));
return true;
} else {
return false;
@@ -466,9 +472,16 @@
}
}
}
+ mEventQueue.add(new RankingAppliedEvent());
}
- private void rebuildList() {
+ private void dispatchEventsAndRebuildList() {
+ mAmDispatchingToOtherCode = true;
+ while (!mEventQueue.isEmpty()) {
+ mEventQueue.remove().dispatchTo(mNotifCollectionListeners);
+ }
+ mAmDispatchingToOtherCode = false;
+
if (mBuildListener != null) {
mBuildListener.onBuildList(mReadOnlyNotificationSet);
}
@@ -491,7 +504,7 @@
if (!isLifetimeExtended(entry)) {
if (tryRemoveNotification(entry)) {
- rebuildList();
+ dispatchEventsAndRebuildList();
}
}
}
@@ -660,57 +673,9 @@
|| entry.getSbn().getUser().getIdentifier() == userId;
}
- private void dispatchOnEntryInit(NotificationEntry entry) {
- mAmDispatchingToOtherCode = true;
- for (NotifCollectionListener listener : mNotifCollectionListeners) {
- listener.onEntryInit(entry);
- }
- mAmDispatchingToOtherCode = false;
- }
-
- private void dispatchOnEntryAdded(NotificationEntry entry) {
- mAmDispatchingToOtherCode = true;
- for (NotifCollectionListener listener : mNotifCollectionListeners) {
- listener.onEntryAdded(entry);
- }
- mAmDispatchingToOtherCode = false;
- }
-
- private void dispatchOnEntryUpdated(NotificationEntry entry) {
- mAmDispatchingToOtherCode = true;
- for (NotifCollectionListener listener : mNotifCollectionListeners) {
- listener.onEntryUpdated(entry);
- }
- mAmDispatchingToOtherCode = false;
- }
-
- private void dispatchNotificationRankingUpdate(RankingMap map) {
- mAmDispatchingToOtherCode = true;
- for (NotifCollectionListener listener : mNotifCollectionListeners) {
- listener.onRankingUpdate(map);
- }
- mAmDispatchingToOtherCode = false;
- }
-
- private void dispatchOnEntryRemoved(NotificationEntry entry, @CancellationReason int reason) {
- mAmDispatchingToOtherCode = true;
- for (NotifCollectionListener listener : mNotifCollectionListeners) {
- listener.onEntryRemoved(entry, reason);
- }
- mAmDispatchingToOtherCode = false;
- }
-
- private void dispatchOnEntryCleanUp(NotificationEntry entry) {
- mAmDispatchingToOtherCode = true;
- for (NotifCollectionListener listener : mNotifCollectionListeners) {
- listener.onEntryCleanUp(entry);
- }
- mAmDispatchingToOtherCode = false;
- }
-
@Override
public void dump(@NonNull FileDescriptor fd, PrintWriter pw, @NonNull String[] args) {
- final List<NotificationEntry> entries = new ArrayList<>(getActiveNotifs());
+ final List<NotificationEntry> entries = new ArrayList<>(getAllNotifs());
pw.println("\t" + TAG + " unsorted/unfiltered notifications:");
if (entries.size() == 0) {
@@ -754,6 +719,7 @@
private static final String TAG = "NotifCollection";
@IntDef(prefix = { "REASON_" }, value = {
+ REASON_NOT_CANCELED,
REASON_UNKNOWN,
REASON_CLICK,
REASON_CANCEL_ALL,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipeline.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipeline.java
index 14903cd..17899e9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipeline.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipeline.java
@@ -82,14 +82,14 @@
}
/**
- * Returns the list of "active" notifications, i.e. the notifications that are currently posted
+ * Returns the list of all known notifications, i.e. the notifications that are currently posted
* to the phone. In general, this tracks closely to the list maintained by NotificationManager,
* but it can diverge slightly due to lifetime extenders.
*
* The returned collection is read-only, unsorted, unfiltered, and ungrouped.
*/
- public Collection<NotificationEntry> getActiveNotifs() {
- return mNotifCollection.getActiveNotifs();
+ public Collection<NotificationEntry> getAllNotifs() {
+ return mNotifCollection.getAllNotifs();
}
@Override
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 3e9d8a4..7019b5b 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
@@ -29,8 +29,6 @@
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_STATUS_BAR;
-import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC;
-import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED;
import static com.android.systemui.statusbar.notification.collection.NotifCollection.REASON_NOT_CANCELED;
import static com.android.systemui.statusbar.notification.stack.NotificationSectionsManager.BUCKET_ALERTING;
@@ -44,10 +42,7 @@
import android.app.Person;
import android.app.RemoteInputHistoryItem;
import android.content.Context;
-import android.content.pm.LauncherApps;
-import android.content.pm.LauncherApps.ShortcutQuery;
import android.content.pm.ShortcutInfo;
-import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
@@ -55,25 +50,20 @@
import android.service.notification.SnoozeCriterion;
import android.service.notification.StatusBarNotification;
import android.util.ArraySet;
-import android.util.Log;
-import android.view.View;
-import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.statusbar.StatusBarIcon;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.ContrastColorUtil;
import com.android.systemui.statusbar.InflationTask;
-import com.android.systemui.statusbar.StatusBarIconView;
-import com.android.systemui.statusbar.notification.InflationException;
import com.android.systemui.statusbar.notification.collection.NotifCollection.CancellationReason;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifFilter;
import com.android.systemui.statusbar.notification.collection.listbuilder.pluggable.NotifPromoter;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifDismissInterceptor;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifLifetimeExtender;
+import com.android.systemui.statusbar.notification.icon.IconPack;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRowController;
import com.android.systemui.statusbar.notification.row.NotificationGuts;
@@ -81,8 +71,6 @@
import com.android.systemui.statusbar.notification.stack.NotificationSectionsManager;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.Objects;
@@ -102,15 +90,11 @@
* clean this up in the future.
*/
public final class NotificationEntry extends ListEntry {
- private static final String TAG = "NotificationEntry";
private final String mKey;
private StatusBarNotification mSbn;
private Ranking mRanking;
- private StatusBarIcon mSmallIcon;
- private StatusBarIcon mPeopleAvatar;
-
/*
* Bookkeeping members
*/
@@ -142,10 +126,7 @@
* TODO: Remove every member beneath this line if possible
*/
- public StatusBarIconView icon;
- public StatusBarIconView expandedIcon;
- public StatusBarIconView centeredIcon;
- public StatusBarIconView aodIcon;
+ private IconPack mIcons = IconPack.buildEmptyPack(null);
private boolean interruption;
public int targetSdk;
private long lastFullScreenIntentLaunchTime = NOT_LAUNCHED_YET;
@@ -191,7 +172,8 @@
private boolean hasSentReply;
private boolean mSensitive = true;
- private Runnable mOnSensitiveChangedListener;
+ private List<OnSensitivityChangedListener> mOnSensitivityChangedListeners = new ArrayList<>();
+
private boolean mAutoHeadsUp;
private boolean mPulseSupressed;
private boolean mAllowFgsDismissal;
@@ -347,6 +329,15 @@
* TODO: Remove as many of these as possible
*/
+ @NonNull
+ public IconPack getIcons() {
+ return mIcons;
+ }
+
+ public void setIcons(@NonNull IconPack icons) {
+ mIcons = icons;
+ }
+
public void setInterruption() {
interruption = true;
}
@@ -464,239 +455,6 @@
|| SystemClock.elapsedRealtime() > initializationTime + INITIALIZATION_DELAY;
}
- /**
- * Create the icons for a notification
- * @param context the context to create the icons with
- * @param sbn the notification
- * @throws InflationException Exception if required icons are not valid or specified
- */
- public void createIcons(Context context, StatusBarNotification sbn)
- throws InflationException {
- StatusBarIcon ic = getIcon(context, sbn, false /* redact */);
-
- // Construct the icon.
- icon = new StatusBarIconView(context,
- sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId()), sbn);
- icon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
-
- // Construct the expanded icon.
- expandedIcon = new StatusBarIconView(context,
- sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId()), sbn);
- expandedIcon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
-
- // Construct the expanded icon.
- aodIcon = new StatusBarIconView(context,
- sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId()), sbn);
- aodIcon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
- aodIcon.setIncreasedSize(true);
-
- try {
- setIcons(ic, Collections.singletonList(icon));
- if (isSensitive()) {
- ic = getIcon(context, sbn, true /* redact */);
- }
- setIcons(ic, Arrays.asList(expandedIcon, aodIcon));
- } catch (InflationException e) {
- icon = null;
- expandedIcon = null;
- centeredIcon = null;
- aodIcon = null;
- throw e;
- }
-
- expandedIcon.setVisibility(View.INVISIBLE);
- expandedIcon.setOnVisibilityChangedListener(
- newVisibility -> {
- if (row != null) {
- row.setIconsVisible(newVisibility != View.VISIBLE);
- }
- });
-
- // Construct the centered icon
- if (mSbn.getNotification().isMediaNotification()) {
- centeredIcon = new StatusBarIconView(context,
- sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId()), sbn);
- centeredIcon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
- try {
- setIcons(ic, Collections.singletonList(centeredIcon));
- } catch (InflationException e) {
- centeredIcon = null;
- throw e;
- }
- }
- }
-
- /**
- * Determines if this icon should be tinted based on the sensitivity of the icon, its context
- * and the user's indicated sensitivity preference.
- *
- * @param ic The icon that should/should not be tinted.
- * @return
- */
- private boolean shouldTintIcon(StatusBarIconView ic) {
- boolean usedInSensitiveContext = (ic == expandedIcon || ic == aodIcon);
- return !isImportantConversation() || (usedInSensitiveContext && isSensitive());
- }
-
-
- private void setIcons(StatusBarIcon ic, List<StatusBarIconView> icons)
- throws InflationException {
- for (StatusBarIconView icon: icons) {
- if (icon == null) {
- continue;
- }
- icon.setTintIcons(shouldTintIcon(icon));
- if (!icon.set(ic)) {
- throw new InflationException("Couldn't create icon" + ic);
- }
- }
- }
-
- private StatusBarIcon getIcon(Context context, StatusBarNotification sbn, boolean redact)
- throws InflationException {
- Notification n = sbn.getNotification();
- final boolean showPeopleAvatar = isImportantConversation() && !redact;
-
- // If cached, return corresponding cached values
- if (showPeopleAvatar && mPeopleAvatar != null) {
- return mPeopleAvatar;
- } else if (!showPeopleAvatar && mSmallIcon != null) {
- return mSmallIcon;
- }
-
- Icon icon = showPeopleAvatar ? createPeopleAvatar(context) : n.getSmallIcon();
- if (icon == null) {
- throw new InflationException("No icon in notification from " + sbn.getPackageName());
- }
-
- StatusBarIcon ic = new StatusBarIcon(
- sbn.getUser(),
- sbn.getPackageName(),
- icon,
- n.iconLevel,
- n.number,
- StatusBarIconView.contentDescForNotification(context, n));
-
- // Cache if important conversation.
- if (isImportantConversation()) {
- if (showPeopleAvatar) {
- mPeopleAvatar = ic;
- } else {
- mSmallIcon = ic;
- }
- }
- return ic;
- }
-
- private Icon createPeopleAvatar(Context context) throws InflationException {
- // Attempt to extract form shortcut.
- String conversationId = getChannel().getConversationId();
- ShortcutQuery query = new ShortcutQuery()
- .setPackage(mSbn.getPackageName())
- .setQueryFlags(FLAG_MATCH_DYNAMIC | FLAG_MATCH_PINNED)
- .setShortcutIds(Collections.singletonList(conversationId));
- List<ShortcutInfo> shortcuts = context.getSystemService(LauncherApps.class)
- .getShortcuts(query, mSbn.getUser());
- Icon ic = null;
- if (shortcuts != null && !shortcuts.isEmpty()) {
- ic = shortcuts.get(0).getIcon();
- }
-
- // Fall back to notification large icon if available
- if (ic == null) {
- ic = mSbn.getNotification().getLargeIcon();
- }
-
- // Fall back to extract from message
- if (ic == null) {
- Bundle extras = mSbn.getNotification().extras;
- List<Message> messages = Message.getMessagesFromBundleArray(
- extras.getParcelableArray(Notification.EXTRA_MESSAGES));
- Person user = extras.getParcelable(Notification.EXTRA_MESSAGING_PERSON);
-
- for (int i = messages.size() - 1; i >= 0; i--) {
- Message message = messages.get(i);
- Person sender = message.getSenderPerson();
- if (sender != null && sender != user) {
- ic = message.getSenderPerson().getIcon();
- break;
- }
- }
- }
-
- // Revert to small icon if still not available
- if (ic == null) {
- ic = mSbn.getNotification().getSmallIcon();
- }
- if (ic == null) {
- throw new InflationException("No icon in notification from " + mSbn.getPackageName());
- }
- return ic;
- }
-
- private void updateSensitiveIconState() {
- try {
- StatusBarIcon ic = getIcon(getRow().getContext(), mSbn, isSensitive());
- setIcons(ic, Arrays.asList(expandedIcon, aodIcon));
- } catch (InflationException e) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Unable to update icon", e);
- }
- }
- }
-
- public void setIconTag(int key, Object tag) {
- if (icon != null) {
- icon.setTag(key, tag);
- expandedIcon.setTag(key, tag);
- }
-
- if (centeredIcon != null) {
- centeredIcon.setTag(key, tag);
- }
-
- if (aodIcon != null) {
- aodIcon.setTag(key, tag);
- }
- }
-
- /**
- * Update the notification icons.
- *
- * @param context the context to create the icons with.
- * @param sbn the notification to read the icon from.
- * @throws InflationException Exception if required icons are not valid or specified
- */
- public void updateIcons(Context context, StatusBarNotification sbn)
- throws InflationException {
- if (icon != null) {
- // Update the icon
- mSmallIcon = null;
- mPeopleAvatar = null;
-
- StatusBarIcon ic = getIcon(context, sbn, false /* redact */);
-
- icon.setNotification(sbn);
- expandedIcon.setNotification(sbn);
- aodIcon.setNotification(sbn);
- setIcons(ic, Arrays.asList(icon, expandedIcon));
-
- if (isSensitive()) {
- ic = getIcon(context, sbn, true /* redact */);
- }
- setIcons(ic, Collections.singletonList(aodIcon));
-
- if (centeredIcon != null) {
- centeredIcon.setNotification(sbn);
- setIcons(ic, Collections.singletonList(centeredIcon));
- }
- }
- }
-
- private boolean isImportantConversation() {
- return getChannel() != null && getChannel().isImportantConversation();
- }
-
public int getContrastedColor(Context context, boolean isLowPriority,
int backgroundColor) {
int rawColor = isLowPriority ? Notification.COLOR_DEFAULT :
@@ -1125,9 +883,8 @@
getRow().setSensitive(sensitive, deviceSensitive);
if (sensitive != mSensitive) {
mSensitive = sensitive;
- updateSensitiveIconState();
- if (mOnSensitiveChangedListener != null) {
- mOnSensitiveChangedListener.run();
+ for (int i = 0; i < mOnSensitivityChangedListeners.size(); i++) {
+ mOnSensitivityChangedListeners.get(i).onSensitivityChanged(this);
}
}
}
@@ -1136,8 +893,14 @@
return mSensitive;
}
- public void setOnSensitiveChangedListener(Runnable listener) {
- mOnSensitiveChangedListener = listener;
+ /** Add a listener to be notified when the entry's sensitivity changes. */
+ public void addOnSensitivityChangedListener(OnSensitivityChangedListener listener) {
+ mOnSensitivityChangedListeners.add(listener);
+ }
+
+ /** Remove a listener that was registered above. */
+ public void removeOnSensitivityChangedListener(OnSensitivityChangedListener listener) {
+ mOnSensitivityChangedListeners.remove(listener);
}
public boolean isPulseSuppressed() {
@@ -1167,6 +930,12 @@
}
}
+ /** Listener interface for {@link #addOnSensitivityChangedListener} */
+ public interface OnSensitivityChangedListener {
+ /** Called when the sensitivity changes */
+ void onSensitivityChanged(@NonNull NotificationEntry entry);
+ }
+
/** @see #getDismissState() */
public enum DismissState {
/** User has not dismissed this notif or its parent */
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescer.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescer.java
index 98c45ff..596235c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescer.java
@@ -260,11 +260,14 @@
private void applyRanking(RankingMap rankingMap) {
for (CoalescedEvent event : mCoalescedEvents.values()) {
Ranking ranking = new Ranking();
- if (!rankingMap.getRanking(event.getKey(), ranking)) {
- throw new IllegalStateException(
- "Ranking map doesn't contain key: " + event.getKey());
+ if (rankingMap.getRanking(event.getKey(), ranking)) {
+ event.setRanking(ranking);
+ } else {
+ // TODO: (b/148791039) We should crash if we are ever handed a ranking with
+ // incomplete entries. Right now, there's a race condition in NotificationListener
+ // that means this might occur when SystemUI is starting up.
+ mLogger.logMissingRanking(event.getKey());
}
- event.setRanking(ranking);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescerLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescerLogger.kt
index 6e8788d..d4d5b64 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescerLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coalescer/GroupCoalescerLogger.kt
@@ -57,6 +57,14 @@
"Modification of notif $str1 triggered TIMEOUT emit of batched group $str2"
})
}
+
+ fun logMissingRanking(forKey: String) {
+ buffer.log(TAG, LogLevel.WARNING, {
+ str1 = forKey
+ }, {
+ "RankingMap is missing an entry for coalesced notification $str1"
+ })
+ }
}
private const val TAG = "GroupCoalescer"
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/BubbleCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/BubbleCoordinator.java
index 370de83..92426e5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/BubbleCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/BubbleCoordinator.java
@@ -126,7 +126,7 @@
mInterceptedDismissalEntries.remove(entry.getKey());
mOnEndDismissInterception.onEndDismissInterception(mDismissInterceptor, entry,
createDismissedByUserStats(entry));
- } else if (mNotifPipeline.getActiveNotifs().contains(entry)) {
+ } else if (mNotifPipeline.getAllNotifs().contains(entry)) {
// Bubbles are hiding the notifications from the shade, but the bubble was
// deleted; therefore, the notification should be cancelled as if it were a user
// dismissal (this won't re-enter handleInterceptDimissal because Bubbles
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java
index 854444f..b5b756d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinator.java
@@ -240,7 +240,7 @@
}
private NotificationEntry findNotificationEntryWithKey(String key) {
- for (NotificationEntry entry : mNotifPipeline.getActiveNotifs()) {
+ for (NotificationEntry entry : mNotifPipeline.getAllNotifs()) {
if (entry.getKey().equals(key)) {
return entry;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
index e8a62e4..7237284 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
@@ -16,7 +16,6 @@
package com.android.systemui.statusbar.notification.collection.inflation;
-import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME;
import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_HEADS_UP;
import android.annotation.Nullable;
@@ -29,34 +28,29 @@
import android.view.ViewGroup;
import com.android.internal.util.NotificationMessagingUtil;
-import com.android.systemui.R;
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.NotificationPresenter;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
import com.android.systemui.statusbar.NotificationUiAdjustment;
import com.android.systemui.statusbar.notification.InflationException;
import com.android.systemui.statusbar.notification.NotificationClicker;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.icon.IconManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRowController;
import com.android.systemui.statusbar.notification.row.NotifBindPipeline;
-import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.notification.row.NotificationRowContentBinder;
import com.android.systemui.statusbar.notification.row.RowContentBindParams;
import com.android.systemui.statusbar.notification.row.RowContentBindStage;
import com.android.systemui.statusbar.notification.row.RowInflaterTask;
import com.android.systemui.statusbar.notification.row.dagger.ExpandableNotificationRowComponent;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
-import com.android.systemui.statusbar.phone.KeyguardBypassController;
-import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.StatusBar;
import java.util.Objects;
import javax.inject.Inject;
-import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
@@ -66,23 +60,23 @@
private static final String TAG = "NotificationViewManager";
- private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
-
private final Context mContext;
- private final NotifBindPipeline mNotifBindPipeline;
- private final RowContentBindStage mRowContentBindStage;
private final NotificationMessagingUtil mMessagingUtil;
private final NotificationRemoteInputManager mNotificationRemoteInputManager;
private final NotificationLockscreenUserManager mNotificationLockscreenUserManager;
+ private final NotifBindPipeline mNotifBindPipeline;
+ private final RowContentBindStage mRowContentBindStage;
+ private final NotificationInterruptStateProvider mNotificationInterruptStateProvider;
+ private final Provider<RowInflaterTask> mRowInflaterTaskProvider;
+ private final ExpandableNotificationRowComponent.Builder
+ mExpandableNotificationRowComponentBuilder;
+ private final IconManager mIconManager;
private NotificationPresenter mPresenter;
private NotificationListContainer mListContainer;
private NotificationRowContentBinder.InflationCallback mInflationCallback;
private BindRowCallback mBindRowCallback;
private NotificationClicker mNotificationClicker;
- private final Provider<RowInflaterTask> mRowInflaterTaskProvider;
- private final ExpandableNotificationRowComponent.Builder
- mExpandableNotificationRowComponentBuilder;
@Inject
public NotificationRowBinderImpl(
@@ -92,23 +86,20 @@
NotificationLockscreenUserManager notificationLockscreenUserManager,
NotifBindPipeline notifBindPipeline,
RowContentBindStage rowContentBindStage,
- @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowLongPress,
- KeyguardBypassController keyguardBypassController,
- StatusBarStateController statusBarStateController,
- NotificationGroupManager notificationGroupManager,
- NotificationGutsManager notificationGutsManager,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptionStateProvider,
Provider<RowInflaterTask> rowInflaterTaskProvider,
- ExpandableNotificationRowComponent.Builder expandableNotificationRowComponentBuilder) {
+ ExpandableNotificationRowComponent.Builder expandableNotificationRowComponentBuilder,
+ IconManager iconManager) {
mContext = context;
mNotifBindPipeline = notifBindPipeline;
mRowContentBindStage = rowContentBindStage;
mMessagingUtil = notificationMessagingUtil;
mNotificationRemoteInputManager = notificationRemoteInputManager;
mNotificationLockscreenUserManager = notificationLockscreenUserManager;
- mNotificationInterruptionStateProvider = notificationInterruptionStateProvider;
+ mNotificationInterruptStateProvider = notificationInterruptionStateProvider;
mRowInflaterTaskProvider = rowInflaterTaskProvider;
mExpandableNotificationRowComponentBuilder = expandableNotificationRowComponentBuilder;
+ mIconManager = iconManager;
}
/**
@@ -120,6 +111,8 @@
mPresenter = presenter;
mListContainer = listContainer;
mBindRowCallback = bindRowCallback;
+
+ mIconManager.attach();
}
public void setInflationCallback(NotificationRowContentBinder.InflationCallback callback) {
@@ -142,12 +135,12 @@
final StatusBarNotification sbn = entry.getSbn();
if (entry.rowExists()) {
- entry.updateIcons(mContext, sbn);
+ mIconManager.updateIcons(entry);
entry.reset();
updateNotification(entry, pmUser, sbn, entry.getRow());
entry.getRowController().setOnDismissRunnable(onDismissRunnable);
} else {
- entry.createIcons(mContext, sbn);
+ mIconManager.createIcons(entry);
mRowInflaterTaskProvider.get().inflate(mContext, parent, entry,
row -> {
// Setup the controller for the view.
@@ -227,8 +220,8 @@
row.setLegacy(entry.targetSdk >= Build.VERSION_CODES.GINGERBREAD
&& entry.targetSdk < Build.VERSION_CODES.LOLLIPOP);
- // TODO: should updates to the entry be happening somewhere else?
- entry.setIconTag(R.id.icon_is_pre_L, entry.targetSdk < Build.VERSION_CODES.LOLLIPOP);
+ // TODO: should this be happening somewhere else?
+ mIconManager.updateIconTags(entry, entry.targetSdk);
row.setOnActivatedListener(mPresenter);
@@ -243,7 +236,7 @@
params.setUseIncreasedHeadsUpHeight(useIncreasedHeadsUp);
params.setUseLowPriority(entry.isAmbient());
- if (mNotificationInterruptionStateProvider.shouldHeadsUp(entry)) {
+ if (mNotificationInterruptStateProvider.shouldHeadsUp(entry)) {
params.requireContentViews(FLAG_CONTENT_VIEW_HEADS_UP);
}
//TODO: Replace this API with RowContentBindParams directly
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/CommonNotifCollection.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/CommonNotifCollection.java
index 171816f..b4c2bb8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/CommonNotifCollection.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/CommonNotifCollection.java
@@ -20,6 +20,8 @@
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import java.util.Collection;
+
/**
* A notification collection that manages the list of {@link NotificationEntry}s that will be
* rendered.
@@ -34,4 +36,13 @@
* or deleted.
*/
void addCollectionListener(NotifCollectionListener listener);
+
+ /**
+ * Returns the list of all known notifications, i.e. the notifications that are currently posted
+ * to the phone. In general, this tracks closely to the list maintained by NotificationManager,
+ * but it can diverge slightly due to lifetime extenders.
+ *
+ * The returned collection is read-only, unsorted, unfiltered, and ungrouped.
+ */
+ Collection<NotificationEntry> getAllNotifs();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionListener.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionListener.java
index b2c53da..0c0cded 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionListener.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifCollectionListener.java
@@ -70,8 +70,24 @@
}
/**
- * Called whenever the RankingMap is updated by system server. By the time this listener is
- * called, the Rankings of all entries will have been updated.
+ * Called whenever a ranking update is applied. During a ranking update, all active,
+ * non-lifetime-extended notification entries will have their ranking object updated.
+ *
+ * Ranking updates occur whenever a notification is added, updated, or removed, or when a
+ * standalone ranking is sent from the server.
+ */
+ default void onRankingApplied() {
+ }
+
+ /**
+ * Called whenever system server sends a standalone ranking update (i.e. one that isn't
+ * associated with a notification being added or removed).
+ *
+ * In general it is unsafe to depend on this method as rankings can change for other reasons.
+ * Instead, listen for {@link #onRankingApplied()}, which is called whenever ANY ranking update
+ * is applied, regardless of source.
+ *
+ * @deprecated Use {@link #onRankingApplied()} instead.
*/
default void onRankingUpdate(NotificationListenerService.RankingMap rankingMap) {
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt
new file mode 100644
index 0000000..2ef0368
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/notifcollection/NotifEvent.kt
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.collection.notifcollection
+
+import android.service.notification.NotificationListenerService.RankingMap
+import com.android.systemui.statusbar.notification.collection.NotifCollection
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+
+/**
+ * Set of classes that represent the various events that [NotifCollection] can dispatch to
+ * [NotifCollectionListener]s.
+ *
+ * These events build up in a queue and are periodically emitted in chunks by the collection.
+ */
+
+sealed class NotifEvent {
+ fun dispatchTo(listeners: List<NotifCollectionListener>) {
+ for (i in listeners.indices) {
+ dispatchToListener(listeners[i])
+ }
+ }
+
+ abstract fun dispatchToListener(listener: NotifCollectionListener)
+}
+
+data class InitEntryEvent(
+ val entry: NotificationEntry
+) : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onEntryInit(entry)
+ }
+}
+
+data class EntryAddedEvent(
+ val entry: NotificationEntry
+) : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onEntryAdded(entry)
+ }
+}
+
+data class EntryUpdatedEvent(
+ val entry: NotificationEntry
+) : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onEntryUpdated(entry)
+ }
+}
+
+data class EntryRemovedEvent(
+ val entry: NotificationEntry,
+ val reason: Int
+) : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onEntryRemoved(entry, reason)
+ }
+}
+
+data class CleanUpEntryEvent(
+ val entry: NotificationEntry
+) : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onEntryCleanUp(entry)
+ }
+}
+
+data class RankingUpdatedEvent(
+ val rankingMap: RankingMap
+) : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onRankingUpdate(rankingMap)
+ }
+}
+
+class RankingAppliedEvent() : NotifEvent() {
+ override fun dispatchToListener(listener: NotifCollectionListener) {
+ listener.onRankingApplied()
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java
index d0b553d..1d8e979 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationsModule.java
@@ -21,6 +21,8 @@
import android.view.accessibility.AccessibilityManager;
import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.UiEventLogger;
+import com.android.internal.logging.UiEventLoggerImpl;
import com.android.systemui.R;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.dagger.qualifiers.UiBackground;
@@ -29,10 +31,8 @@
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
import com.android.systemui.statusbar.notification.ForegroundServiceDismissalFeatureController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationEntryManagerLogger;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationRankingManager;
@@ -42,7 +42,12 @@
import com.android.systemui.statusbar.notification.init.NotificationsController;
import com.android.systemui.statusbar.notification.init.NotificationsControllerImpl;
import com.android.systemui.statusbar.notification.init.NotificationsControllerStub;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProviderImpl;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
+import com.android.systemui.statusbar.notification.logging.NotificationPanelLogger;
+import com.android.systemui.statusbar.notification.logging.NotificationPanelLoggerImpl;
import com.android.systemui.statusbar.notification.row.NotificationBlockingHelperManager;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
@@ -54,6 +59,7 @@
import javax.inject.Singleton;
+import dagger.Binds;
import dagger.Lazy;
import dagger.Module;
import dagger.Provides;
@@ -123,7 +129,7 @@
NotificationRemoteInputManager remoteInputManager,
VisualStabilityManager visualStabilityManager,
StatusBarStateController statusBarStateController,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptStateProvider,
NotificationListener notificationListener,
HeadsUpManager headsUpManager) {
return new NotificationAlertingManager(
@@ -131,7 +137,7 @@
remoteInputManager,
visualStabilityManager,
statusBarStateController,
- notificationInterruptionStateProvider,
+ notificationInterruptStateProvider,
notificationListener,
headsUpManager);
}
@@ -144,13 +150,29 @@
@UiBackground Executor uiBgExecutor,
NotificationEntryManager entryManager,
StatusBarStateController statusBarStateController,
- NotificationLogger.ExpansionStateLogger expansionStateLogger) {
+ NotificationLogger.ExpansionStateLogger expansionStateLogger,
+ NotificationPanelLogger notificationPanelLogger) {
return new NotificationLogger(
notificationListener,
uiBgExecutor,
entryManager,
statusBarStateController,
- expansionStateLogger);
+ expansionStateLogger,
+ notificationPanelLogger);
+ }
+
+ /** Provides an instance of {@link NotificationPanelLogger} */
+ @Singleton
+ @Provides
+ static NotificationPanelLogger provideNotificationPanelLogger() {
+ return new NotificationPanelLoggerImpl();
+ }
+
+ /** Provides an instance of {@link com.android.internal.logging.UiEventLogger} */
+ @Singleton
+ @Provides
+ static UiEventLogger provideUiEventLogger() {
+ return new UiEventLoggerImpl();
}
/** Provides an instance of {@link NotificationBlockingHelperManager} */
@@ -190,4 +212,9 @@
NotificationEntryManager entryManager) {
return featureFlags.isNewNotifPipelineRenderingEnabled() ? pipeline.get() : entryManager;
}
+
+ /** */
+ @Binds
+ NotificationInterruptStateProvider bindNotificationInterruptStateProvider(
+ NotificationInterruptStateProviderImpl notificationInterruptStateProviderImpl);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconBuilder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconBuilder.kt
new file mode 100644
index 0000000..afc123f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconBuilder.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.icon
+
+import android.app.Notification
+import android.content.Context
+import com.android.systemui.statusbar.StatusBarIconView
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import javax.inject.Inject
+
+/**
+ * Testable wrapper around Context.
+ */
+class IconBuilder @Inject constructor(
+ private val context: Context
+) {
+ fun createIconView(entry: NotificationEntry): StatusBarIconView {
+ return StatusBarIconView(
+ context,
+ "${entry.sbn.packageName}/0x${Integer.toHexString(entry.sbn.id)}",
+ entry.sbn)
+ }
+
+ fun getIconContentDescription(n: Notification): CharSequence {
+ return StatusBarIconView.contentDescForNotification(context, n)
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
new file mode 100644
index 0000000..bb0fcaf
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconManager.kt
@@ -0,0 +1,338 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.icon
+
+import android.app.Notification
+import android.app.Person
+import android.content.pm.LauncherApps
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.util.Log
+import android.view.View
+import android.widget.ImageView
+import com.android.internal.statusbar.StatusBarIcon
+import com.android.systemui.R
+import com.android.systemui.statusbar.StatusBarIconView
+import com.android.systemui.statusbar.notification.InflationException
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection
+import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener
+import javax.inject.Inject
+
+/**
+ * Inflates and updates icons associated with notifications
+ *
+ * Notifications are represented by icons in a few different places -- in the status bar, in the
+ * notification shelf, in AOD, etc. This class is in charge of inflating the views that hold these
+ * icons and keeping the icon assets themselves up to date as notifications change.
+ *
+ * TODO: Much of this code was copied whole-sale in order to get it out of NotificationEntry.
+ * Long-term, it should probably live somewhere in the content inflation pipeline.
+ */
+class IconManager @Inject constructor(
+ private val notifCollection: CommonNotifCollection,
+ private val launcherApps: LauncherApps,
+ private val iconBuilder: IconBuilder
+) {
+ fun attach() {
+ notifCollection.addCollectionListener(entryListener)
+ }
+
+ private val entryListener = object : NotifCollectionListener {
+ override fun onEntryInit(entry: NotificationEntry) {
+ entry.addOnSensitivityChangedListener(sensitivityListener)
+ }
+
+ override fun onEntryCleanUp(entry: NotificationEntry) {
+ entry.removeOnSensitivityChangedListener(sensitivityListener)
+ }
+
+ override fun onRankingApplied() {
+ // When the sensitivity changes OR when the isImportantConversation status changes,
+ // we need to update the icons
+ for (entry in notifCollection.allNotifs) {
+ val isImportant = isImportantConversation(entry)
+ if (entry.icons.areIconsAvailable &&
+ isImportant != entry.icons.isImportantConversation) {
+ updateIconsSafe(entry)
+ }
+ entry.icons.isImportantConversation = isImportant
+ }
+ }
+ }
+
+ private val sensitivityListener = NotificationEntry.OnSensitivityChangedListener {
+ entry -> updateIconsSafe(entry)
+ }
+
+ /**
+ * Inflate icon views for each icon variant and assign appropriate icons to them. Stores the
+ * result in [NotificationEntry.getIcons].
+ *
+ * @throws InflationException Exception if required icons are not valid or specified
+ */
+ @Throws(InflationException::class)
+ fun createIcons(entry: NotificationEntry) {
+ // Construct the status bar icon view.
+ val sbIcon = iconBuilder.createIconView(entry)
+ sbIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
+
+ // Construct the shelf icon view.
+ val shelfIcon = iconBuilder.createIconView(entry)
+ shelfIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
+
+ shelfIcon.visibility = View.INVISIBLE
+ // TODO: This doesn't belong here
+ shelfIcon.setOnVisibilityChangedListener { newVisibility: Int ->
+ if (entry.row != null) {
+ entry.row.setIconsVisible(newVisibility != View.VISIBLE)
+ }
+ }
+
+ // Construct the aod icon view.
+ val aodIcon = iconBuilder.createIconView(entry)
+ aodIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
+ aodIcon.setIncreasedSize(true)
+
+ // Construct the centered icon view.
+ val centeredIcon = if (entry.sbn.notification.isMediaNotification) {
+ iconBuilder.createIconView(entry).apply {
+ scaleType = ImageView.ScaleType.CENTER_INSIDE
+ }
+ } else {
+ null
+ }
+
+ // Set the icon views' icons
+ val (normalIconDescriptor, sensitiveIconDescriptor) = getIconDescriptors(entry)
+
+ try {
+ setIcon(entry, normalIconDescriptor, sbIcon)
+ setIcon(entry, sensitiveIconDescriptor, shelfIcon)
+ setIcon(entry, sensitiveIconDescriptor, aodIcon)
+ if (centeredIcon != null) {
+ setIcon(entry, normalIconDescriptor, centeredIcon)
+ }
+ entry.icons = IconPack.buildPack(sbIcon, shelfIcon, aodIcon, centeredIcon, entry.icons)
+ } catch (e: InflationException) {
+ entry.icons = IconPack.buildEmptyPack(entry.icons)
+ throw e
+ }
+ }
+
+ /**
+ * Update the notification icons.
+ *
+ * @param entry the notification to read the icon from.
+ * @throws InflationException Exception if required icons are not valid or specified
+ */
+ @Throws(InflationException::class)
+ fun updateIcons(entry: NotificationEntry) {
+ if (!entry.icons.areIconsAvailable) {
+ return
+ }
+ entry.icons.smallIconDescriptor = null
+ entry.icons.peopleAvatarDescriptor = null
+
+ val (normalIconDescriptor, sensitiveIconDescriptor) = getIconDescriptors(entry)
+
+ entry.icons.statusBarIcon?.let {
+ it.notification = entry.sbn
+ setIcon(entry, normalIconDescriptor, it)
+ }
+
+ entry.icons.shelfIcon?.let {
+ it.notification = entry.sbn
+ setIcon(entry, normalIconDescriptor, it)
+ }
+
+ entry.icons.aodIcon?.let {
+ it.notification = entry.sbn
+ setIcon(entry, sensitiveIconDescriptor, it)
+ }
+
+ entry.icons.centeredIcon?.let {
+ it.notification = entry.sbn
+ setIcon(entry, sensitiveIconDescriptor, it)
+ }
+ }
+
+ /**
+ * Updates tags on the icon views to match the posting app's target SDK level
+ *
+ * Note that this method MUST be called after both [createIcons] and [updateIcons].
+ */
+ fun updateIconTags(entry: NotificationEntry, targetSdk: Int) {
+ setTagOnIconViews(
+ entry.icons,
+ R.id.icon_is_pre_L,
+ targetSdk < Build.VERSION_CODES.LOLLIPOP)
+ }
+
+ private fun updateIconsSafe(entry: NotificationEntry) {
+ try {
+ updateIcons(entry)
+ } catch (e: InflationException) {
+ // TODO This should mark the entire row as involved in an inflation error
+ Log.e(TAG, "Unable to update icon", e)
+ }
+ }
+
+ @Throws(InflationException::class)
+ private fun getIconDescriptors(
+ entry: NotificationEntry
+ ): Pair<StatusBarIcon, StatusBarIcon> {
+ val iconDescriptor = getIconDescriptor(entry, false /* redact */)
+ val sensitiveDescriptor = if (entry.isSensitive) {
+ getIconDescriptor(entry, true /* redact */)
+ } else {
+ iconDescriptor
+ }
+ return Pair(iconDescriptor, sensitiveDescriptor)
+ }
+
+ @Throws(InflationException::class)
+ private fun getIconDescriptor(
+ entry: NotificationEntry,
+ redact: Boolean
+ ): StatusBarIcon {
+ val n = entry.sbn.notification
+ val showPeopleAvatar = isImportantConversation(entry) && !redact
+
+ val peopleAvatarDescriptor = entry.icons.peopleAvatarDescriptor
+ val smallIconDescriptor = entry.icons.smallIconDescriptor
+
+ // If cached, return corresponding cached values
+ if (showPeopleAvatar && peopleAvatarDescriptor != null) {
+ return peopleAvatarDescriptor
+ } else if (!showPeopleAvatar && smallIconDescriptor != null) {
+ return smallIconDescriptor
+ }
+
+ val icon =
+ (if (showPeopleAvatar) {
+ createPeopleAvatar(entry)
+ } else {
+ n.smallIcon
+ }) ?: throw InflationException(
+ "No icon in notification from " + entry.sbn.packageName)
+
+ val ic = StatusBarIcon(
+ entry.sbn.user,
+ entry.sbn.packageName,
+ icon,
+ n.iconLevel,
+ n.number,
+ iconBuilder.getIconContentDescription(n))
+
+ // Cache if important conversation.
+ if (isImportantConversation(entry)) {
+ if (showPeopleAvatar) {
+ entry.icons.peopleAvatarDescriptor = ic
+ } else {
+ entry.icons.smallIconDescriptor = ic
+ }
+ }
+
+ return ic
+ }
+
+ @Throws(InflationException::class)
+ private fun setIcon(
+ entry: NotificationEntry,
+ iconDescriptor: StatusBarIcon,
+ iconView: StatusBarIconView
+ ) {
+ iconView.setTintIcons(shouldTintIconView(entry, iconView))
+ if (!iconView.set(iconDescriptor)) {
+ throw InflationException("Couldn't create icon $iconDescriptor")
+ }
+ }
+
+ @Throws(InflationException::class)
+ private fun createPeopleAvatar(entry: NotificationEntry): Icon? {
+ // Attempt to extract form shortcut.
+ val conversationId = entry.ranking.channel.conversationId
+ val query = LauncherApps.ShortcutQuery()
+ .setPackage(entry.sbn.packageName)
+ .setQueryFlags(
+ LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
+ or LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
+ .setShortcutIds(listOf(conversationId))
+ val shortcuts = launcherApps.getShortcuts(query, entry.sbn.user)
+ var ic: Icon? = null
+ if (shortcuts != null && shortcuts.isNotEmpty()) {
+ ic = shortcuts[0].icon
+ }
+
+ // Fall back to notification large icon if available
+ if (ic == null) {
+ ic = entry.sbn.notification.getLargeIcon()
+ }
+
+ // Fall back to extract from message
+ if (ic == null) {
+ val extras: Bundle = entry.sbn.notification.extras
+ val messages = Notification.MessagingStyle.Message.getMessagesFromBundleArray(
+ extras.getParcelableArray(Notification.EXTRA_MESSAGES))
+ val user = extras.getParcelable<Person>(Notification.EXTRA_MESSAGING_PERSON)
+ for (i in messages.indices.reversed()) {
+ val message = messages[i]
+ val sender = message.senderPerson
+ if (sender != null && sender !== user) {
+ ic = message.senderPerson!!.icon
+ break
+ }
+ }
+ }
+
+ // Revert to small icon if still not available
+ if (ic == null) {
+ ic = entry.sbn.notification.smallIcon
+ }
+ if (ic == null) {
+ throw InflationException("No icon in notification from " + entry.sbn.packageName)
+ }
+ return ic
+ }
+
+ /**
+ * Determines if this icon should be tinted based on the sensitivity of the icon, its context
+ * and the user's indicated sensitivity preference.
+ *
+ * @param iconView The icon that should/should not be tinted.
+ */
+ private fun shouldTintIconView(entry: NotificationEntry, iconView: StatusBarIconView): Boolean {
+ val usedInSensitiveContext =
+ iconView === entry.icons.shelfIcon || iconView === entry.icons.aodIcon
+ return !isImportantConversation(entry) || usedInSensitiveContext && entry.isSensitive
+ }
+
+ private fun isImportantConversation(entry: NotificationEntry): Boolean {
+ return entry.ranking.channel != null && entry.ranking.channel.isImportantConversation
+ }
+
+ private fun setTagOnIconViews(icons: IconPack, key: Int, tag: Any) {
+ icons.statusBarIcon?.setTag(key, tag)
+ icons.shelfIcon?.setTag(key, tag)
+ icons.aodIcon?.setTag(key, tag)
+ icons.centeredIcon?.setTag(key, tag)
+ }
+}
+
+private const val TAG = "IconManager"
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconPack.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconPack.java
new file mode 100644
index 0000000..054e381
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/icon/IconPack.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.icon;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import com.android.internal.statusbar.StatusBarIcon;
+import com.android.systemui.statusbar.StatusBarIconView;
+
+/**
+ * Data class for storing icons associated with a notification
+ */
+public final class IconPack {
+
+ private final boolean mAreIconsAvailable;
+ @Nullable private final StatusBarIconView mStatusBarIcon;
+ @Nullable private final StatusBarIconView mShelfIcon;
+ @Nullable private final StatusBarIconView mAodIcon;
+ @Nullable private final StatusBarIconView mCenteredIcon;
+
+ @Nullable private StatusBarIcon mSmallIconDescriptor;
+ @Nullable private StatusBarIcon mPeopleAvatarDescriptor;
+
+ private boolean mIsImportantConversation;
+
+ /**
+ * Builds an empty instance of IconPack that doesn't have any icons (because either they
+ * haven't been inflated yet or there was an error while inflating them).
+ */
+ public static IconPack buildEmptyPack(@Nullable IconPack fromSource) {
+ return new IconPack(false, null, null, null, null, fromSource);
+ }
+
+ /**
+ * Builds an instance of an IconPack that contains successfully-inflated icons
+ */
+ public static IconPack buildPack(
+ @NonNull StatusBarIconView statusBarIcon,
+ @NonNull StatusBarIconView shelfIcon,
+ @NonNull StatusBarIconView aodIcon,
+ @Nullable StatusBarIconView centeredIcon,
+ @Nullable IconPack source) {
+ return new IconPack(true, statusBarIcon, shelfIcon, aodIcon, centeredIcon, source);
+ }
+
+ private IconPack(
+ boolean areIconsAvailable,
+ @Nullable StatusBarIconView statusBarIcon,
+ @Nullable StatusBarIconView shelfIcon,
+ @Nullable StatusBarIconView aodIcon,
+ @Nullable StatusBarIconView centeredIcon,
+ @Nullable IconPack source) {
+ mAreIconsAvailable = areIconsAvailable;
+ mStatusBarIcon = statusBarIcon;
+ mShelfIcon = shelfIcon;
+ mCenteredIcon = centeredIcon;
+ mAodIcon = aodIcon;
+ if (source != null) {
+ mIsImportantConversation = source.mIsImportantConversation;
+ }
+ }
+
+ /** The version of the notification icon that appears in the status bar. */
+ @Nullable
+ public StatusBarIconView getStatusBarIcon() {
+ return mStatusBarIcon;
+ }
+
+ /**
+ * The version of the icon that appears in the "shelf" at the bottom of the notification shade.
+ * In general, this icon also appears somewhere on the notification and is "sucked" into the
+ * shelf as the scrolls beyond it.
+ */
+ @Nullable
+ public StatusBarIconView getShelfIcon() {
+ return mShelfIcon;
+ }
+
+ @Nullable
+ public StatusBarIconView getCenteredIcon() {
+ return mCenteredIcon;
+ }
+
+ /** The version of the icon that's shown when pulsing (in AOD). */
+ @Nullable
+ public StatusBarIconView getAodIcon() {
+ return mAodIcon;
+ }
+
+ @Nullable
+ StatusBarIcon getSmallIconDescriptor() {
+ return mSmallIconDescriptor;
+ }
+
+ void setSmallIconDescriptor(@Nullable StatusBarIcon smallIconDescriptor) {
+ mSmallIconDescriptor = smallIconDescriptor;
+ }
+
+ @Nullable
+ StatusBarIcon getPeopleAvatarDescriptor() {
+ return mPeopleAvatarDescriptor;
+ }
+
+ void setPeopleAvatarDescriptor(@Nullable StatusBarIcon peopleAvatarDescriptor) {
+ mPeopleAvatarDescriptor = peopleAvatarDescriptor;
+ }
+
+ boolean isImportantConversation() {
+ return mIsImportantConversation;
+ }
+
+ void setImportantConversation(boolean importantConversation) {
+ mIsImportantConversation = importantConversation;
+ }
+
+ public boolean getAreIconsAvailable() {
+ return mAreIconsAvailable;
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/BypassHeadsUpNotifier.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/BypassHeadsUpNotifier.kt
similarity index 96%
rename from packages/SystemUI/src/com/android/systemui/statusbar/notification/BypassHeadsUpNotifier.kt
rename to packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/BypassHeadsUpNotifier.kt
index 269a7a5..88888d1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/BypassHeadsUpNotifier.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/BypassHeadsUpNotifier.kt
@@ -14,7 +14,7 @@
* limitations under the License
*/
-package com.android.systemui.statusbar.notification
+package com.android.systemui.statusbar.notification.interruption
import android.content.Context
import android.media.MediaMetadata
@@ -24,6 +24,7 @@
import com.android.systemui.statusbar.NotificationLockscreenUserManager
import com.android.systemui.statusbar.NotificationMediaManager
import com.android.systemui.statusbar.StatusBarState
+import com.android.systemui.statusbar.notification.NotificationEntryManager
import com.android.systemui.statusbar.notification.collection.NotificationEntry
import com.android.systemui.statusbar.phone.HeadsUpManagerPhone
import com.android.systemui.statusbar.phone.KeyguardBypassController
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationAlertingManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationAlertingManager.java
similarity index 90%
rename from packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationAlertingManager.java
rename to packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationAlertingManager.java
index df21f0b..b572502 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationAlertingManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationAlertingManager.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.systemui.statusbar.notification;
+package com.android.systemui.statusbar.notification.interruption;
import static com.android.systemui.statusbar.NotificationRemoteInputManager.FORCE_REMOTE_INPUT_HISTORY;
import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_HEADS_UP;
@@ -27,6 +27,9 @@
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.NotificationListener;
import com.android.systemui.statusbar.NotificationRemoteInputManager;
+import com.android.systemui.statusbar.notification.NotificationEntryListener;
+import com.android.systemui.statusbar.notification.NotificationEntryManager;
+import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.dagger.NotificationsModule;
import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -39,7 +42,7 @@
private final NotificationRemoteInputManager mRemoteInputManager;
private final VisualStabilityManager mVisualStabilityManager;
private final StatusBarStateController mStatusBarStateController;
- private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+ private final NotificationInterruptStateProvider mNotificationInterruptStateProvider;
private final NotificationListener mNotificationListener;
private HeadsUpManager mHeadsUpManager;
@@ -52,13 +55,13 @@
NotificationRemoteInputManager remoteInputManager,
VisualStabilityManager visualStabilityManager,
StatusBarStateController statusBarStateController,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptionStateProvider,
NotificationListener notificationListener,
HeadsUpManager headsUpManager) {
mRemoteInputManager = remoteInputManager;
mVisualStabilityManager = visualStabilityManager;
mStatusBarStateController = statusBarStateController;
- mNotificationInterruptionStateProvider = notificationInterruptionStateProvider;
+ mNotificationInterruptStateProvider = notificationInterruptionStateProvider;
mNotificationListener = notificationListener;
mHeadsUpManager = headsUpManager;
@@ -94,7 +97,7 @@
if (entry.getRow().getPrivateLayout().getHeadsUpChild() != null) {
// Possible for shouldHeadsUp to change between the inflation starting and ending.
// If it does and we no longer need to heads up, we should free the view.
- if (mNotificationInterruptionStateProvider.shouldHeadsUp(entry)) {
+ if (mNotificationInterruptStateProvider.shouldHeadsUp(entry)) {
mHeadsUpManager.showNotification(entry);
if (!mStatusBarStateController.isDozing()) {
// Mark as seen immediately
@@ -109,7 +112,7 @@
private void updateAlertState(NotificationEntry entry) {
boolean alertAgain = alertAgain(entry, entry.getSbn().getNotification());
// includes check for whether this notification should be filtered:
- boolean shouldAlert = mNotificationInterruptionStateProvider.shouldHeadsUp(entry);
+ boolean shouldAlert = mNotificationInterruptStateProvider.shouldHeadsUp(entry);
final boolean wasAlerting = mHeadsUpManager.isAlerting(entry.getKey());
if (wasAlerting) {
if (shouldAlert) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProvider.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProvider.java
new file mode 100644
index 0000000..3292a8f
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProvider.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.interruption;
+
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+
+/**
+ * Provides bubble-up and heads-up state for notification entries.
+ *
+ * When a notification is heads-up when dozing, this is also called "pulsing."
+ */
+public interface NotificationInterruptStateProvider {
+ /**
+ * If the device is awake (not dozing):
+ * Whether the notification should peek in from the top and alert the user.
+ *
+ * If the device is dozing:
+ * Whether the notification should show the ambient view of the notification ("pulse").
+ *
+ * @param entry the entry to check
+ * @return true if the entry should heads up, false otherwise
+ */
+ boolean shouldHeadsUp(NotificationEntry entry);
+
+ /**
+ * Whether the notification should appear as a bubble with a fly-out on top of the screen.
+ *
+ * @param entry the entry to check
+ * @return true if the entry should bubble up, false otherwise
+ */
+ boolean shouldBubbleUp(NotificationEntry entry);
+
+ /**
+ * Whether to launch the entry's full screen intent when the entry is added.
+ *
+ * @param entry the entry that was added
+ * @return {@code true} if we should launch the full screen intent
+ */
+ boolean shouldLaunchFullScreenIntentWhenAdded(NotificationEntry entry);
+
+ /**
+ * Add a component that can suppress visual interruptions.
+ */
+ void addSuppressor(NotificationInterruptSuppressor suppressor);
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProviderImpl.java
similarity index 63%
rename from packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java
rename to packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProviderImpl.java
index bbf2dde..46d5044 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationInterruptionStateProvider.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProviderImpl.java
@@ -14,33 +14,35 @@
* limitations under the License.
*/
-package com.android.systemui.statusbar.notification;
+package com.android.systemui.statusbar.notification.interruption;
import static com.android.systemui.statusbar.StatusBarState.SHADE;
import android.app.NotificationManager;
-import android.content.Context;
+import android.content.ContentResolver;
import android.database.ContentObserver;
import android.hardware.display.AmbientDisplayConfiguration;
+import android.os.Handler;
import android.os.PowerManager;
import android.os.RemoteException;
-import android.os.ServiceManager;
import android.os.UserHandle;
import android.provider.Settings;
-import android.service.dreams.DreamService;
import android.service.dreams.IDreamManager;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.systemui.Dependency;
+import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.NotificationPresenter;
import com.android.systemui.statusbar.StatusBarState;
+import com.android.systemui.statusbar.notification.NotificationFilter;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
+import java.util.ArrayList;
+import java.util.List;
+
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -48,120 +50,84 @@
* Provides heads-up and pulsing state for notification entries.
*/
@Singleton
-public class NotificationInterruptionStateProvider {
-
+public class NotificationInterruptStateProviderImpl implements NotificationInterruptStateProvider {
private static final String TAG = "InterruptionStateProvider";
- private static final boolean DEBUG = false;
+ private static final boolean DEBUG = true; //false;
private static final boolean DEBUG_HEADS_UP = true;
private static final boolean ENABLE_HEADS_UP = true;
private static final String SETTING_HEADS_UP_TICKER = "ticker_gets_heads_up";
+ private final List<NotificationInterruptSuppressor> mSuppressors = new ArrayList<>();
private final StatusBarStateController mStatusBarStateController;
private final NotificationFilter mNotificationFilter;
- private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
-
- private final Context mContext;
+ private final ContentResolver mContentResolver;
private final PowerManager mPowerManager;
private final IDreamManager mDreamManager;
+ private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
private final BatteryController mBatteryController;
-
- private NotificationPresenter mPresenter;
+ private final ContentObserver mHeadsUpObserver;
private HeadsUpManager mHeadsUpManager;
- private HeadsUpSuppressor mHeadsUpSuppressor;
- private ContentObserver mHeadsUpObserver;
@VisibleForTesting
protected boolean mUseHeadsUp = false;
- private boolean mDisableNotificationAlerts;
@Inject
- public NotificationInterruptionStateProvider(Context context, NotificationFilter filter,
- StatusBarStateController stateController, BatteryController batteryController) {
- this(context,
- (PowerManager) context.getSystemService(Context.POWER_SERVICE),
- IDreamManager.Stub.asInterface(
- ServiceManager.checkService(DreamService.DREAM_SERVICE)),
- new AmbientDisplayConfiguration(context),
- filter,
- batteryController,
- stateController);
- }
-
- @VisibleForTesting
- protected NotificationInterruptionStateProvider(
- Context context,
+ public NotificationInterruptStateProviderImpl(
+ ContentResolver contentResolver,
PowerManager powerManager,
IDreamManager dreamManager,
AmbientDisplayConfiguration ambientDisplayConfiguration,
NotificationFilter notificationFilter,
BatteryController batteryController,
- StatusBarStateController statusBarStateController) {
- mContext = context;
+ StatusBarStateController statusBarStateController,
+ HeadsUpManager headsUpManager,
+ @Main Handler mainHandler) {
+ mContentResolver = contentResolver;
mPowerManager = powerManager;
mDreamManager = dreamManager;
mBatteryController = batteryController;
mAmbientDisplayConfiguration = ambientDisplayConfiguration;
mNotificationFilter = notificationFilter;
mStatusBarStateController = statusBarStateController;
- }
-
- /** Sets up late-binding dependencies for this component. */
- public void setUpWithPresenter(
- NotificationPresenter notificationPresenter,
- HeadsUpManager headsUpManager,
- HeadsUpSuppressor headsUpSuppressor) {
- setUpWithPresenter(notificationPresenter, headsUpManager, headsUpSuppressor,
- new ContentObserver(Dependency.get(Dependency.MAIN_HANDLER)) {
- @Override
- public void onChange(boolean selfChange) {
- boolean wasUsing = mUseHeadsUp;
- mUseHeadsUp = ENABLE_HEADS_UP && !mDisableNotificationAlerts
- && Settings.Global.HEADS_UP_OFF != Settings.Global.getInt(
- mContext.getContentResolver(),
- Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED,
- Settings.Global.HEADS_UP_OFF);
- Log.d(TAG, "heads up is " + (mUseHeadsUp ? "enabled" : "disabled"));
- if (wasUsing != mUseHeadsUp) {
- if (!mUseHeadsUp) {
- Log.d(TAG,
- "dismissing any existing heads up notification on disable"
- + " event");
- mHeadsUpManager.releaseAllImmediately();
- }
- }
- }
- });
- }
-
- /** Sets up late-binding dependencies for this component. */
- public void setUpWithPresenter(
- NotificationPresenter notificationPresenter,
- HeadsUpManager headsUpManager,
- HeadsUpSuppressor headsUpSuppressor,
- ContentObserver observer) {
- mPresenter = notificationPresenter;
mHeadsUpManager = headsUpManager;
- mHeadsUpSuppressor = headsUpSuppressor;
- mHeadsUpObserver = observer;
+ mHeadsUpObserver = new ContentObserver(mainHandler) {
+ @Override
+ public void onChange(boolean selfChange) {
+ boolean wasUsing = mUseHeadsUp;
+ mUseHeadsUp = ENABLE_HEADS_UP
+ && Settings.Global.HEADS_UP_OFF != Settings.Global.getInt(
+ mContentResolver,
+ Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED,
+ Settings.Global.HEADS_UP_OFF);
+ Log.d(TAG, "heads up is " + (mUseHeadsUp ? "enabled" : "disabled"));
+ if (wasUsing != mUseHeadsUp) {
+ if (!mUseHeadsUp) {
+ Log.d(TAG, "dismissing any existing heads up notification on "
+ + "disable event");
+ mHeadsUpManager.releaseAllImmediately();
+ }
+ }
+ }
+ };
if (ENABLE_HEADS_UP) {
- mContext.getContentResolver().registerContentObserver(
+ mContentResolver.registerContentObserver(
Settings.Global.getUriFor(Settings.Global.HEADS_UP_NOTIFICATIONS_ENABLED),
true,
mHeadsUpObserver);
- mContext.getContentResolver().registerContentObserver(
+ mContentResolver.registerContentObserver(
Settings.Global.getUriFor(SETTING_HEADS_UP_TICKER), true,
mHeadsUpObserver);
}
mHeadsUpObserver.onChange(true); // set up
}
- /**
- * Whether the notification should appear as a bubble with a fly-out on top of the screen.
- *
- * @param entry the entry to check
- * @return true if the entry should bubble up, false otherwise
- */
+ @Override
+ public void addSuppressor(NotificationInterruptSuppressor suppressor) {
+ mSuppressors.add(suppressor);
+ }
+
+ @Override
public boolean shouldBubbleUp(NotificationEntry entry) {
final StatusBarNotification sbn = entry.getSbn();
@@ -201,12 +167,8 @@
return true;
}
- /**
- * Whether the notification should peek in from the top and alert the user.
- *
- * @param entry the entry to check
- * @return true if the entry should heads up, false otherwise
- */
+
+ @Override
public boolean shouldHeadsUp(NotificationEntry entry) {
if (mStatusBarStateController.isDozing()) {
return shouldHeadsUpWhenDozing(entry);
@@ -215,6 +177,17 @@
}
}
+ /**
+ * When an entry was added, should we launch its fullscreen intent? Examples are Alarms or
+ * incoming calls.
+ */
+ @Override
+ public boolean shouldLaunchFullScreenIntentWhenAdded(NotificationEntry entry) {
+ return entry.getSbn().getNotification().fullScreenIntent != null
+ && (!shouldHeadsUp(entry)
+ || mStatusBarStateController.getState() == StatusBarState.KEYGUARD);
+ }
+
private boolean shouldHeadsUpWhenAwake(NotificationEntry entry) {
StatusBarNotification sbn = entry.getSbn();
@@ -271,13 +244,15 @@
return false;
}
- if (!mHeadsUpSuppressor.canHeadsUp(entry, sbn)) {
- if (DEBUG_HEADS_UP) {
- Log.d(TAG, "No heads up: aborted by suppressor: " + sbn.getKey());
+ for (int i = 0; i < mSuppressors.size(); i++) {
+ if (mSuppressors.get(i).suppressAwakeHeadsUp(entry)) {
+ if (DEBUG_HEADS_UP) {
+ Log.d(TAG, "No heads up: aborted by suppressor: "
+ + mSuppressors.get(i).getName() + " sbnKey=" + sbn.getKey());
+ }
+ return false;
}
- return false;
}
-
return true;
}
@@ -325,7 +300,7 @@
}
return false;
}
- return true;
+ return true;
}
/**
@@ -334,8 +309,7 @@
* @param entry the entry to check
* @return true if these checks pass, false if the notification should not alert
*/
- @VisibleForTesting
- public boolean canAlertCommon(NotificationEntry entry) {
+ private boolean canAlertCommon(NotificationEntry entry) {
StatusBarNotification sbn = entry.getSbn();
if (mNotificationFilter.shouldFilterOut(entry)) {
@@ -352,6 +326,16 @@
}
return false;
}
+
+ for (int i = 0; i < mSuppressors.size(); i++) {
+ if (mSuppressors.get(i).suppressInterruptions(entry)) {
+ if (DEBUG_HEADS_UP) {
+ Log.d(TAG, "No alerting: aborted by suppressor: "
+ + mSuppressors.get(i).getName() + " sbnKey=" + sbn.getKey());
+ }
+ return false;
+ }
+ }
return true;
}
@@ -361,15 +345,17 @@
* @param entry the entry to check
* @return true if these checks pass, false if the notification should not alert
*/
- @VisibleForTesting
- public boolean canAlertAwakeCommon(NotificationEntry entry) {
+ private boolean canAlertAwakeCommon(NotificationEntry entry) {
StatusBarNotification sbn = entry.getSbn();
- if (mPresenter.isDeviceInVrMode()) {
- if (DEBUG_HEADS_UP) {
- Log.d(TAG, "No alerting: no huns or vr mode");
+ for (int i = 0; i < mSuppressors.size(); i++) {
+ if (mSuppressors.get(i).suppressAwakeInterruptions(entry)) {
+ if (DEBUG_HEADS_UP) {
+ Log.d(TAG, "No alerting: aborted by suppressor: "
+ + mSuppressors.get(i).getName() + " sbnKey=" + sbn.getKey());
+ }
+ return false;
}
- return false;
}
if (isSnoozedPackage(sbn)) {
@@ -392,54 +378,4 @@
private boolean isSnoozedPackage(StatusBarNotification sbn) {
return mHeadsUpManager.isSnoozed(sbn.getPackageName());
}
-
- /** Sets whether to disable all alerts. */
- public void setDisableNotificationAlerts(boolean disableNotificationAlerts) {
- mDisableNotificationAlerts = disableNotificationAlerts;
- mHeadsUpObserver.onChange(true);
- }
-
- /** Whether all alerts are disabled. */
- @VisibleForTesting
- public boolean areNotificationAlertsDisabled() {
- return mDisableNotificationAlerts;
- }
-
- /** Whether HUNs should be used. */
- @VisibleForTesting
- public boolean getUseHeadsUp() {
- return mUseHeadsUp;
- }
-
- protected NotificationPresenter getPresenter() {
- return mPresenter;
- }
-
- /**
- * When an entry was added, should we launch its fullscreen intent? Examples are Alarms or
- * incoming calls.
- *
- * @param entry the entry that was added
- * @return {@code true} if we should launch the full screen intent
- */
- public boolean shouldLaunchFullScreenIntentWhenAdded(NotificationEntry entry) {
- return entry.getSbn().getNotification().fullScreenIntent != null
- && (!shouldHeadsUp(entry)
- || mStatusBarStateController.getState() == StatusBarState.KEYGUARD);
- }
-
- /** A component which can suppress heads-up notifications due to the overall state of the UI. */
- public interface HeadsUpSuppressor {
- /**
- * Returns false if the provided notification is ineligible for heads-up according to this
- * component.
- *
- * @param entry entry of the notification that might be heads upped
- * @param sbn notification that might be heads upped
- * @return false if the notification can not be heads upped
- */
- boolean canHeadsUp(NotificationEntry entry, StatusBarNotification sbn);
-
- }
-
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptSuppressor.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptSuppressor.java
new file mode 100644
index 0000000..c19f8bd
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptSuppressor.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.interruption;
+
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+
+/** A component which can suppress visual interruptions of notifications such as heads-up and
+ * bubble-up.
+ */
+public interface NotificationInterruptSuppressor {
+ /**
+ * A unique name to identify this suppressor.
+ */
+ default String getName() {
+ return this.getClass().getName();
+ }
+
+ /**
+ * Returns true if the provided notification is, when the device is awake, ineligible for
+ * heads-up according to this component.
+ *
+ * @param entry entry of the notification that might heads-up
+ * @return true if the heads up interruption should be suppressed when the device is awake
+ */
+ default boolean suppressAwakeHeadsUp(NotificationEntry entry) {
+ return false;
+ }
+
+ /**
+ * Returns true if the provided notification is, when the device is awake, ineligible for
+ * heads-up or bubble-up according to this component.
+ *
+ * @param entry entry of the notification that might heads-up or bubble-up
+ * @return true if interruptions should be suppressed when the device is awake
+ */
+ default boolean suppressAwakeInterruptions(NotificationEntry entry) {
+ return false;
+ }
+
+ /**
+ * Returns true if the provided notification is, regardless of awake/dozing state,
+ * ineligible for heads-up or bubble-up according to this component.
+ *
+ * @param entry entry of the notification that might heads-up or bubble-up
+ * @return true if interruptions should be suppressed
+ */
+ default boolean suppressInterruptions(NotificationEntry entry) {
+ return false;
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java
index 6e161c9..ad04788 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java
@@ -70,6 +70,7 @@
private final NotificationListenerService mNotificationListener;
private final Executor mUiBgExecutor;
private final NotificationEntryManager mEntryManager;
+ private final NotificationPanelLogger mNotificationPanelLogger;
private HeadsUpManager mHeadsUpManager;
private final ExpansionStateLogger mExpansionStateLogger;
@@ -198,13 +199,15 @@
@UiBackground Executor uiBgExecutor,
NotificationEntryManager entryManager,
StatusBarStateController statusBarStateController,
- ExpansionStateLogger expansionStateLogger) {
+ ExpansionStateLogger expansionStateLogger,
+ NotificationPanelLogger notificationPanelLogger) {
mNotificationListener = notificationListener;
mUiBgExecutor = uiBgExecutor;
mEntryManager = entryManager;
mBarService = IStatusBarService.Stub.asInterface(
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
mExpansionStateLogger = expansionStateLogger;
+ mNotificationPanelLogger = notificationPanelLogger;
// Not expected to be destroyed, don't need to unsubscribe
statusBarStateController.addCallback(this);
@@ -264,6 +267,8 @@
// (Note that in cases where the scroller does emit events, this
// additional event doesn't break anything.)
mNotificationLocationsChangedListener.onChildLocationsChanged();
+ mNotificationPanelLogger.logPanelShown(mListContainer.hasPulsingNotifications(),
+ mEntryManager.getVisibleNotifications());
}
private void setDozing(boolean dozing) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLogger.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLogger.java
new file mode 100644
index 0000000..9a25c48
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLogger.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.logging;
+
+import android.annotation.Nullable;
+import android.service.notification.StatusBarNotification;
+
+import com.android.internal.logging.UiEvent;
+import com.android.internal.logging.UiEventLogger;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.logging.nano.Notifications;
+
+import java.util.List;
+/**
+ * Statsd logging for notification panel.
+ */
+public interface NotificationPanelLogger {
+
+ /**
+ * Log a NOTIFICATION_PANEL_REPORTED statsd event.
+ * @param visibleNotifications as provided by NotificationEntryManager.getVisibleNotifications()
+ */
+ void logPanelShown(boolean isLockscreen,
+ @Nullable List<NotificationEntry> visibleNotifications);
+
+ enum NotificationPanelEvent implements UiEventLogger.UiEventEnum {
+ @UiEvent(doc = "Notification panel shown from status bar.")
+ NOTIFICATION_PANEL_OPEN_STATUS_BAR(200),
+ @UiEvent(doc = "Notification panel shown from lockscreen.")
+ NOTIFICATION_PANEL_OPEN_LOCKSCREEN(201);
+
+ private final int mId;
+ NotificationPanelEvent(int id) {
+ mId = id;
+ }
+ @Override public int getId() {
+ return mId;
+ }
+
+ public static NotificationPanelEvent fromLockscreen(boolean isLockscreen) {
+ return isLockscreen ? NOTIFICATION_PANEL_OPEN_LOCKSCREEN :
+ NOTIFICATION_PANEL_OPEN_STATUS_BAR;
+ }
+ }
+
+ /**
+ * Composes a NotificationsList proto from the list of visible notifications.
+ * @param visibleNotifications as provided by NotificationEntryManager.getVisibleNotifications()
+ * @return NotificationList proto suitable for SysUiStatsLog.write(NOTIFICATION_PANEL_REPORTED)
+ */
+ static Notifications.NotificationList toNotificationProto(
+ @Nullable List<NotificationEntry> visibleNotifications) {
+ Notifications.NotificationList notificationList = new Notifications.NotificationList();
+ if (visibleNotifications == null) {
+ return notificationList;
+ }
+ final Notifications.Notification[] proto_array =
+ new Notifications.Notification[visibleNotifications.size()];
+ int i = 0;
+ for (NotificationEntry ne : visibleNotifications) {
+ final StatusBarNotification n = ne.getSbn();
+ if (n != null) {
+ final Notifications.Notification proto = new Notifications.Notification();
+ proto.uid = n.getUid();
+ proto.packageName = n.getPackageName();
+ if (n.getInstanceId() != null) {
+ proto.instanceId = n.getInstanceId().getId();
+ }
+ // TODO set np.groupInstanceId
+ if (n.getNotification() != null) {
+ proto.isGroupSummary = n.getNotification().isGroupSummary();
+ }
+ proto.section = 1 + ne.getBucket(); // We want 0 to mean not set / unknown
+ proto_array[i] = proto;
+ }
+ ++i;
+ }
+ notificationList.notifications = proto_array;
+ return notificationList;
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLoggerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLoggerImpl.java
new file mode 100644
index 0000000..75a6019
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLoggerImpl.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.logging;
+
+import com.android.systemui.shared.system.SysUiStatsLog;
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.logging.nano.Notifications;
+
+import com.google.protobuf.nano.MessageNano;
+
+import java.util.List;
+
+/**
+ * Normal implementation of NotificationPanelLogger.
+ */
+public class NotificationPanelLoggerImpl implements NotificationPanelLogger {
+ @Override
+ public void logPanelShown(boolean isLockscreen,
+ List<NotificationEntry> visibleNotifications) {
+ final Notifications.NotificationList proto = NotificationPanelLogger.toNotificationProto(
+ visibleNotifications);
+ SysUiStatsLog.write(SysUiStatsLog.NOTIFICATION_PANEL_REPORTED,
+ /* int event_id */ NotificationPanelEvent.fromLockscreen(isLockscreen).getId(),
+ /* int num_notifications*/ proto.notifications.length,
+ /* byte[] notifications*/ MessageNano.toByteArray(proto));
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/Notifications.proto b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/Notifications.proto
new file mode 100644
index 0000000..552a5fb
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/Notifications.proto
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.logging;
+
+/**
+ * NotificationList proto from atoms.proto, duplicated here so that it's accessible in the build.
+ * Must be kept in sync with the version in atoms.proto.
+ */
+
+message Notification {
+ // The notifying app's uid and package.
+ optional int32 uid = 1;
+ optional string package_name = 2;
+ // A small system-assigned identifier for the notification.
+ optional int32 instance_id = 3;
+
+ // Grouping information.
+ optional int32 group_instance_id = 4;
+ optional bool is_group_summary = 5;
+
+ // The section of the shade that the notification is in.
+ // See NotificationSectionsManager.PriorityBucket.
+ enum NotificationSection {
+ SECTION_UNKNOWN = 0;
+ SECTION_HEADS_UP = 1;
+ SECTION_PEOPLE = 2;
+ SECTION_ALERTING = 3;
+ SECTION_SILENT = 4;
+ }
+ optional NotificationSection section = 6;
+}
+
+message NotificationList {
+ repeated Notification notifications = 1; // An ordered sequence of notifications.
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt
index 62d3612..7f42fe0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleHubViewController.kt
@@ -164,8 +164,8 @@
// Immediately report current value of setting
updateListener(listener)
val observer = object : ContentObserver(handler) {
- override fun onChange(selfChange: Boolean, uri: Uri?, userId: Int) {
- super.onChange(selfChange, uri, userId)
+ override fun onChange(selfChange: Boolean, uri: Uri?, flags: Int) {
+ super.onChange(selfChange, uri, flags)
updateListener(listener)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleNotificationIdentifier.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleNotificationIdentifier.kt
index 597bdb9..be3873a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleNotificationIdentifier.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/people/PeopleNotificationIdentifier.kt
@@ -83,7 +83,7 @@
private val Ranking.personTypeInfo
get() = when {
- channel.isImportantConversation -> TYPE_IMPORTANT_PERSON
+ channel?.isImportantConversation == true -> TYPE_IMPORTANT_PERSON
isConversation -> TYPE_PERSON
else -> TYPE_NON_PERSON
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/DungeonRow.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/DungeonRow.kt
index 373457d..dbfa27f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/DungeonRow.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/DungeonRow.kt
@@ -37,7 +37,7 @@
}
(findViewById(R.id.icon) as StatusBarIconView).apply {
- set(entry?.icon?.statusBarIcon)
+ set(entry?.icons?.statusBarIcon?.statusBarIcon)
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index 9a4e789..b1db5b5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -31,7 +31,6 @@
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.app.Notification;
import android.app.NotificationChannel;
import android.content.Context;
import android.content.pm.PackageInfo;
@@ -151,7 +150,6 @@
private int mNotificationMinHeight;
private int mNotificationMinHeightLarge;
private int mNotificationMinHeightMedia;
- private int mNotificationMinHeightMessaging;
private int mNotificationMaxHeight;
private int mIncreasedPaddingBetweenElements;
private int mNotificationLaunchHeight;
@@ -581,7 +579,7 @@
@VisibleForTesting
void updateShelfIconColor() {
- StatusBarIconView expandedIcon = mEntry.expandedIcon;
+ StatusBarIconView expandedIcon = mEntry.getIcons().getShelfIcon();
boolean isPreL = Boolean.TRUE.equals(expandedIcon.getTag(R.id.icon_is_pre_L));
boolean colorize = !isPreL || NotificationUtils.isGrayscale(expandedIcon,
ContrastColorUtil.getInstance(mContext));
@@ -640,16 +638,10 @@
&& expandedView.findViewById(com.android.internal.R.id.media_actions) != null;
boolean showCompactMediaSeekbar = mMediaManager.getShowCompactMediaSeekbar();
- Class<? extends Notification.Style> style =
- mEntry.getSbn().getNotification().getNotificationStyle();
- boolean isMessagingLayout = Notification.MessagingStyle.class.equals(style);
-
if (customView && beforeP && !mIsSummaryWithChildren) {
minHeight = beforeN ? mNotificationMinHeightBeforeN : mNotificationMinHeightBeforeP;
} else if (isMediaLayout && showCompactMediaSeekbar) {
minHeight = mNotificationMinHeightMedia;
- } else if (isMessagingLayout) {
- minHeight = mNotificationMinHeightMessaging;
} else if (mUseIncreasedCollapsedHeight && layout == mPrivateLayout) {
minHeight = mNotificationMinHeightLarge;
} else {
@@ -1057,19 +1049,6 @@
return getShowingLayout().getVisibleNotificationHeader();
}
-
- /**
- * @return the contracted notification header. This can be different from
- * {@link #getNotificationHeader()} and also {@link #getVisibleNotificationHeader()} and only
- * returns the contracted version.
- */
- public NotificationHeaderView getContractedNotificationHeader() {
- if (mIsSummaryWithChildren) {
- return mChildrenContainer.getHeaderView();
- }
- return mPrivateLayout.getContractedNotificationHeader();
- }
-
public void setLongPressListener(LongPressListener longPressListener) {
mLongPressListener = longPressListener;
}
@@ -1311,7 +1290,7 @@
setLongPressListener(null);
mGroupParentWhenDismissed = mNotificationParent;
mChildAfterViewWhenDismissed = null;
- mEntry.icon.setDismissed();
+ mEntry.getIcons().getStatusBarIcon().setDismissed();
if (isChildInGroup()) {
List<ExpandableNotificationRow> notificationChildren =
mNotificationParent.getNotificationChildren();
@@ -1654,8 +1633,6 @@
R.dimen.notification_min_height_increased);
mNotificationMinHeightMedia = NotificationUtils.getFontScaledHeight(mContext,
R.dimen.notification_min_height_media);
- mNotificationMinHeightMessaging = NotificationUtils.getFontScaledHeight(mContext,
- R.dimen.notification_min_height_messaging);
mNotificationMaxHeight = NotificationUtils.getFontScaledHeight(mContext,
R.dimen.notification_max_height);
mMaxHeadsUpHeightBeforeN = NotificationUtils.getFontScaledHeight(mContext,
@@ -1855,7 +1832,7 @@
mTranslateableViews.get(i).setTranslationX(0);
}
invalidateOutline();
- getEntry().expandedIcon.setScrollX(0);
+ getEntry().getIcons().getShelfIcon().setScrollX(0);
}
if (mMenuRow != null) {
@@ -1935,7 +1912,7 @@
// In order to keep the shelf in sync with this swiping, we're simply translating
// it's icon by the same amount. The translation is already being used for the normal
// positioning, so we can use the scrollX instead.
- getEntry().expandedIcon.setScrollX((int) -translationX);
+ getEntry().getIcons().getShelfIcon().setScrollX((int) -translationX);
}
if (mMenuRow != null && mMenuRow.getMenuView() != null) {
@@ -2134,7 +2111,7 @@
@Override
public StatusBarIconView getShelfIcon() {
- return getEntry().expandedIcon;
+ return getEntry().getIcons().getShelfIcon();
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java
index 6dd4ff9..91cf285 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentInflater.java
@@ -25,6 +25,8 @@
import android.annotation.Nullable;
import android.app.Notification;
import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.pm.ApplicationInfo;
import android.os.AsyncTask;
import android.os.CancellationSignal;
import android.service.notification.StatusBarNotification;
@@ -716,6 +718,10 @@
sbn.getNotification());
Context packageContext = sbn.getPackageContext(mContext);
+ if (recoveredBuilder.usesTemplate()) {
+ // For all of our templates, we want it to be RTL
+ packageContext = new RtlEnabledContext(packageContext);
+ }
Notification notification = sbn.getNotification();
if (notification.isMediaNotification()) {
MediaNotificationProcessor processor = new MediaNotificationProcessor(mContext,
@@ -782,6 +788,19 @@
// try to purge unnecessary cached entries.
mRow.getImageResolver().purgeCache();
}
+
+ private class RtlEnabledContext extends ContextWrapper {
+ private RtlEnabledContext(Context packageContext) {
+ super(packageContext);
+ }
+
+ @Override
+ public ApplicationInfo getApplicationInfo() {
+ ApplicationInfo applicationInfo = super.getApplicationInfo();
+ applicationInfo.flags |= ApplicationInfo.FLAG_SUPPORTS_RTL;
+ return applicationInfo;
+ }
+ }
}
@VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 27fd1b2..8b8a901 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -1492,13 +1492,6 @@
}
}
- public NotificationHeaderView getContractedNotificationHeader() {
- if (mContractedChild != null) {
- return mContractedWrapper.getNotificationHeader();
- }
- return null;
- }
-
public NotificationHeaderView getVisibleNotificationHeader() {
NotificationViewWrapper wrapper = getVisibleWrapper(mVisibleType);
return wrapper == null ? null : wrapper.getNotificationHeader();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
index d746822..bd4984e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
@@ -315,7 +315,6 @@
mNotificationActivityStarter.startNotificationGutsIntent(intent, sbn.getUid(),
row);
};
- boolean isForBlockingHelper = row.isBlockingHelperShowing();
if (!userHandle.equals(UserHandle.ALL)
|| mLockscreenUserManager.getCurrentUserId() == UserHandle.USER_SYSTEM) {
@@ -335,13 +334,10 @@
row.getEntry().getChannel(),
row.getUniqueChannels(),
row.getEntry(),
- mCheckSaveListener,
onSettingsClick,
onAppSettingsClick,
mDeviceProvisionedController.isDeviceProvisioned(),
row.getIsNonblockable(),
- isForBlockingHelper,
- row.getEntry().getImportance(),
mHighPriorityProvider.isHighPriority(row.getEntry()));
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java
index 6b4511d..12aa4df 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationInfo.java
@@ -24,10 +24,6 @@
import static java.lang.annotation.RetentionPolicy.SOURCE;
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
import android.annotation.IntDef;
import android.annotation.Nullable;
import android.app.INotificationManager;
@@ -53,7 +49,6 @@
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
-import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
@@ -63,42 +58,33 @@
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.systemui.Dependency;
-import com.android.systemui.Interpolators;
import com.android.systemui.R;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
-import com.android.systemui.statusbar.notification.logging.NotificationCounters;
import java.lang.annotation.Retention;
import java.util.List;
import java.util.Set;
/**
- * The guts of a notification revealed when performing a long press. This also houses the blocking
- * helper affordance that allows a user to keep/stop notifications after swiping one away.
+ * The guts of a notification revealed when performing a long press.
*/
public class NotificationInfo extends LinearLayout implements NotificationGuts.GutsContent {
private static final String TAG = "InfoGuts";
@IntDef(prefix = { "ACTION_" }, value = {
ACTION_NONE,
- ACTION_UNDO,
+ ACTION_TOGGLE_ALERT,
ACTION_TOGGLE_SILENT,
- ACTION_BLOCK,
})
public @interface NotificationInfoAction {
}
public static final int ACTION_NONE = 0;
- static final int ACTION_UNDO = 1;
// standard controls
static final int ACTION_TOGGLE_SILENT = 2;
- // unused
- static final int ACTION_BLOCK = 3;
- // blocking helper
- static final int ACTION_DELIVER_SILENTLY = 4;
// standard controls
- private static final int ACTION_ALERT = 5;
+ private static final int ACTION_TOGGLE_ALERT = 5;
private TextView mPriorityDescriptionView;
private TextView mSilentDescriptionView;
@@ -128,101 +114,35 @@
@Nullable private Integer mChosenImportance;
private boolean mIsSingleDefaultChannel;
private boolean mIsNonblockable;
- private NotificationEntry mEntry;
private StatusBarNotification mSbn;
- private AnimatorSet mExpandAnimation;
private boolean mIsDeviceProvisioned;
- private CheckSaveListener mCheckSaveListener;
private OnSettingsClickListener mOnSettingsClickListener;
private OnAppSettingsClickListener mAppSettingsClickListener;
private NotificationGuts mGutsContainer;
private Drawable mPkgIcon;
- /** Whether this view is being shown as part of the blocking helper. */
- private boolean mIsForBlockingHelper;
-
@VisibleForTesting
boolean mSkipPost = false;
- /**
- * String that describes how the user exit or quit out of this view, also used as a counter tag.
- */
- private String mExitReason = NotificationCounters.BLOCKING_HELPER_DISMISSED;
-
-
// used by standard ui
private OnClickListener mOnAlert = v -> {
- mExitReason = NotificationCounters.BLOCKING_HELPER_KEEP_SHOWING;
mChosenImportance = IMPORTANCE_DEFAULT;
applyAlertingBehavior(BEHAVIOR_ALERTING, true /* userTriggered */);
};
// used by standard ui
private OnClickListener mOnSilent = v -> {
- mExitReason = NotificationCounters.BLOCKING_HELPER_DELIVER_SILENTLY;
mChosenImportance = IMPORTANCE_LOW;
applyAlertingBehavior(BEHAVIOR_SILENT, true /* userTriggered */);
};
-
// used by standard ui
private OnClickListener mOnDismissSettings = v -> {
mPressedApply = true;
closeControls(v, true);
};
- // used by blocking helper
- private OnClickListener mOnKeepShowing = v -> {
- mExitReason = NotificationCounters.BLOCKING_HELPER_KEEP_SHOWING;
- closeControls(v, true);
- mMetricsLogger.write(getLogMaker().setCategory(
- MetricsEvent.NOTIFICATION_BLOCKING_HELPER)
- .setType(MetricsEvent.TYPE_ACTION)
- .setSubtype(MetricsEvent.BLOCKING_HELPER_CLICK_STAY_SILENT));
- };
-
- // used by blocking helper
- private OnClickListener mOnDeliverSilently = v -> {
- handleSaveImportance(
- ACTION_DELIVER_SILENTLY, MetricsEvent.BLOCKING_HELPER_CLICK_STAY_SILENT);
- };
-
- private void handleSaveImportance(int action, int metricsSubtype) {
- Runnable saveImportance = () -> {
- saveImportanceAndExitReason(action);
- if (mIsForBlockingHelper) {
- swapContent(action, true /* animate */);
- mMetricsLogger.write(getLogMaker()
- .setCategory(MetricsEvent.NOTIFICATION_BLOCKING_HELPER)
- .setType(MetricsEvent.TYPE_ACTION)
- .setSubtype(metricsSubtype));
- }
- };
- if (mCheckSaveListener != null) {
- mCheckSaveListener.checkSave(saveImportance, mSbn);
- } else {
- saveImportance.run();
- }
- }
-
- private OnClickListener mOnUndo = v -> {
- // Reset exit counter that we'll log and record an undo event separately (not an exit event)
- mExitReason = NotificationCounters.BLOCKING_HELPER_DISMISSED;
- if (mIsForBlockingHelper) {
- logBlockingHelperCounter(NotificationCounters.BLOCKING_HELPER_UNDO);
- mMetricsLogger.write(getLogMaker().setCategory(
- MetricsEvent.NOTIFICATION_BLOCKING_HELPER)
- .setType(MetricsEvent.TYPE_DISMISS)
- .setSubtype(MetricsEvent.BLOCKING_HELPER_CLICK_UNDO));
- } else {
- // TODO: this can't happen?
- mMetricsLogger.write(importanceChangeLogMaker().setType(MetricsEvent.TYPE_DISMISS));
- }
- saveImportanceAndExitReason(ACTION_UNDO);
- swapContent(ACTION_UNDO, true /* animate */);
- };
-
public NotificationInfo(Context context, AttributeSet attrs) {
super(context, attrs);
}
@@ -250,30 +170,6 @@
void onClick(View v, Intent intent);
}
- @VisibleForTesting
- void bindNotification(
- final PackageManager pm,
- final INotificationManager iNotificationManager,
- final VisualStabilityManager visualStabilityManager,
- final String pkg,
- final NotificationChannel notificationChannel,
- final Set<NotificationChannel> uniqueChannelsInRow,
- final NotificationEntry entry,
- final CheckSaveListener checkSaveListener,
- final OnSettingsClickListener onSettingsClick,
- final OnAppSettingsClickListener onAppSettingsClick,
- boolean isDeviceProvisioned,
- boolean isNonblockable,
- int importance,
- boolean wasShownHighPriority)
- throws RemoteException {
- bindNotification(pm, iNotificationManager, visualStabilityManager, pkg, notificationChannel,
- uniqueChannelsInRow, entry, checkSaveListener, onSettingsClick,
- onAppSettingsClick, isDeviceProvisioned, isNonblockable,
- false /* isBlockingHelper */,
- importance, wasShownHighPriority);
- }
-
public void bindNotification(
PackageManager pm,
INotificationManager iNotificationManager,
@@ -282,13 +178,10 @@
NotificationChannel notificationChannel,
Set<NotificationChannel> uniqueChannelsInRow,
NotificationEntry entry,
- CheckSaveListener checkSaveListener,
OnSettingsClickListener onSettingsClick,
OnAppSettingsClickListener onAppSettingsClick,
boolean isDeviceProvisioned,
boolean isNonblockable,
- boolean isForBlockingHelper,
- int importance,
boolean wasShownHighPriority)
throws RemoteException {
mINotificationManager = iNotificationManager;
@@ -298,18 +191,15 @@
mPackageName = pkg;
mUniqueChannelsInRow = uniqueChannelsInRow;
mNumUniqueChannelsInRow = uniqueChannelsInRow.size();
- mEntry = entry;
mSbn = entry.getSbn();
mPm = pm;
mAppSettingsClickListener = onAppSettingsClick;
mAppName = mPackageName;
- mCheckSaveListener = checkSaveListener;
mOnSettingsClickListener = onSettingsClick;
mSingleNotificationChannel = notificationChannel;
mStartingChannelImportance = mSingleNotificationChannel.getImportance();
mWasShownHighPriority = wasShownHighPriority;
mIsNonblockable = isNonblockable;
- mIsForBlockingHelper = isForBlockingHelper;
mAppUid = mSbn.getUid();
mDelegatePkg = mSbn.getOpPkg();
mIsDeviceProvisioned = isDeviceProvisioned;
@@ -329,36 +219,12 @@
bindHeader();
bindChannelDetails();
- if (mIsForBlockingHelper) {
- bindBlockingHelper();
- } else {
- bindInlineControls();
- }
+ bindInlineControls();
mMetricsLogger.write(notificationControlsLogMaker());
}
- private void bindBlockingHelper() {
- findViewById(R.id.inline_controls).setVisibility(GONE);
- findViewById(R.id.blocking_helper).setVisibility(VISIBLE);
-
- findViewById(R.id.undo).setOnClickListener(mOnUndo);
-
- View turnOffButton = findViewById(R.id.blocking_helper_turn_off_notifications);
- turnOffButton.setOnClickListener(getSettingsOnClickListener());
- turnOffButton.setVisibility(turnOffButton.hasOnClickListeners() ? VISIBLE : GONE);
-
- TextView keepShowing = findViewById(R.id.keep_showing);
- keepShowing.setOnClickListener(mOnKeepShowing);
-
- View deliverSilently = findViewById(R.id.deliver_silently);
- deliverSilently.setOnClickListener(mOnDeliverSilently);
- }
-
private void bindInlineControls() {
- findViewById(R.id.inline_controls).setVisibility(VISIBLE);
- findViewById(R.id.blocking_helper).setVisibility(GONE);
-
if (mIsNonblockable) {
findViewById(R.id.non_configurable_text).setVisibility(VISIBLE);
findViewById(R.id.non_configurable_multichannel_text).setVisibility(GONE);
@@ -414,8 +280,8 @@
// app is gone, just show package name and generic icon
mPkgIcon = mPm.getDefaultActivityIcon();
}
- ((ImageView) findViewById(R.id.pkgicon)).setImageDrawable(mPkgIcon);
- ((TextView) findViewById(R.id.pkgname)).setText(mAppName);
+ ((ImageView) findViewById(R.id.pkg_icon)).setImageDrawable(mPkgIcon);
+ ((TextView) findViewById(R.id.pkg_name)).setText(mAppName);
// Delegate
bindDelegate();
@@ -445,8 +311,6 @@
if (mAppUid >= 0 && mOnSettingsClickListener != null && mIsDeviceProvisioned) {
final int appUidF = mAppUid;
return ((View view) -> {
- logBlockingHelperCounter(
- NotificationCounters.BLOCKING_HELPER_NOTIF_SETTINGS);
mOnSettingsClickListener.onClick(view,
mNumUniqueChannelsInRow > 1 ? null : mSingleNotificationChannel,
appUidF);
@@ -487,16 +351,13 @@
private void bindDelegate() {
TextView delegateView = findViewById(R.id.delegate_name);
- TextView dividerView = findViewById(R.id.pkg_divider);
CharSequence delegatePkg = null;
if (!TextUtils.equals(mPackageName, mDelegatePkg)) {
// this notification was posted by a delegate!
delegateView.setVisibility(View.VISIBLE);
- dividerView.setVisibility(View.VISIBLE);
} else {
delegateView.setVisibility(View.GONE);
- dividerView.setVisibility(View.GONE);
}
}
@@ -512,25 +373,19 @@
}
}
TextView groupNameView = findViewById(R.id.group_name);
+ View divider = findViewById(R.id.group_divider);
if (groupName != null) {
groupNameView.setText(groupName);
- groupNameView.setVisibility(View.VISIBLE);
+ groupNameView.setVisibility(VISIBLE);
+ divider.setVisibility(VISIBLE);
} else {
- groupNameView.setVisibility(View.GONE);
- }
- }
-
-
- @VisibleForTesting
- void logBlockingHelperCounter(String counterTag) {
- if (mIsForBlockingHelper) {
- mMetricsLogger.count(counterTag, 1);
+ groupNameView.setVisibility(GONE);
+ divider.setVisibility(GONE);
}
}
private void saveImportance() {
- if (!mIsNonblockable
- || mExitReason != NotificationCounters.BLOCKING_HELPER_STOP_NOTIFICATIONS) {
+ if (!mIsNonblockable) {
if (mChosenImportance == null) {
mChosenImportance = mStartingChannelImportance;
}
@@ -621,99 +476,13 @@
: R.string.inline_done_button);
}
- private void saveImportanceAndExitReason(@NotificationInfoAction int action) {
- switch (action) {
- case ACTION_UNDO:
- mChosenImportance = mStartingChannelImportance;
- break;
- case ACTION_DELIVER_SILENTLY:
- mExitReason = NotificationCounters.BLOCKING_HELPER_DELIVER_SILENTLY;
- mChosenImportance = mWasShownHighPriority
- ? IMPORTANCE_LOW : mStartingChannelImportance;
- break;
- default:
- throw new IllegalArgumentException();
- }
- }
-
- // only used for blocking helper
- private void swapContent(@NotificationInfoAction int action, boolean animate) {
- if (mExpandAnimation != null) {
- mExpandAnimation.cancel();
- }
-
- View blockingHelper = findViewById(R.id.blocking_helper);
- ViewGroup confirmation = findViewById(R.id.confirmation);
- TextView confirmationText = findViewById(R.id.confirmation_text);
-
- saveImportanceAndExitReason(action);
-
- switch (action) {
- case ACTION_UNDO:
- break;
- case ACTION_DELIVER_SILENTLY:
- confirmationText.setText(R.string.notification_channel_silenced);
- break;
- default:
- throw new IllegalArgumentException();
- }
-
- boolean isUndo = action == ACTION_UNDO;
-
- blockingHelper.setVisibility(isUndo ? VISIBLE : GONE);
- findViewById(R.id.channel_info).setVisibility(isUndo ? VISIBLE : GONE);
- findViewById(R.id.header).setVisibility(isUndo ? VISIBLE : GONE);
- confirmation.setVisibility(isUndo ? GONE : VISIBLE);
-
- if (animate) {
- ObjectAnimator promptAnim = ObjectAnimator.ofFloat(blockingHelper, View.ALPHA,
- blockingHelper.getAlpha(), isUndo ? 1f : 0f);
- promptAnim.setInterpolator(isUndo ? Interpolators.ALPHA_IN : Interpolators.ALPHA_OUT);
- ObjectAnimator confirmAnim = ObjectAnimator.ofFloat(confirmation, View.ALPHA,
- confirmation.getAlpha(), isUndo ? 0f : 1f);
- confirmAnim.setInterpolator(isUndo ? Interpolators.ALPHA_OUT : Interpolators.ALPHA_IN);
-
- mExpandAnimation = new AnimatorSet();
- mExpandAnimation.playTogether(promptAnim, confirmAnim);
- mExpandAnimation.setDuration(150);
- mExpandAnimation.addListener(new AnimatorListenerAdapter() {
- boolean mCancelled = false;
-
- @Override
- public void onAnimationCancel(Animator animation) {
- mCancelled = true;
- }
-
- @Override
- public void onAnimationEnd(Animator animation) {
- if (!mCancelled) {
- blockingHelper.setVisibility(isUndo ? VISIBLE : GONE);
- confirmation.setVisibility(isUndo ? GONE : VISIBLE);
- }
- }
- });
- mExpandAnimation.start();
- }
-
- // Since we're swapping/update the content, reset the timeout so the UI can't close
- // immediately after the update.
- if (mGutsContainer != null) {
- mGutsContainer.resetFalsingCheck();
- }
- }
-
@Override
public void onFinishedClosing() {
if (mChosenImportance != null) {
mStartingChannelImportance = mChosenImportance;
}
- mExitReason = NotificationCounters.BLOCKING_HELPER_DISMISSED;
- if (mIsForBlockingHelper) {
- bindBlockingHelper();
- } else {
- bindInlineControls();
- }
+ bindInlineControls();
mMetricsLogger.write(notificationControlsLogMaker().setType(MetricsEvent.TYPE_CLOSE));
}
@@ -756,13 +525,10 @@
}
/**
- * Closes the controls and commits the updated importance values (indirectly). If this view is
- * being used to show the blocking helper, this will immediately dismiss the blocking helper and
- * commit the updated importance.
+ * Closes the controls and commits the updated importance values (indirectly).
*
* <p><b>Note,</b> this will only get called once the view is dismissing. This means that the
- * user does not have the ability to undo the action anymore. See
- * {@link #swapContent(boolean, boolean)} for where undo is handled.
+ * user does not have the ability to undo the action anymore.
*/
@VisibleForTesting
void closeControls(View v, boolean save) {
@@ -811,7 +577,6 @@
if (save) {
saveImportance();
}
- logBlockingHelperCounter(mExitReason);
return false;
}
@@ -822,7 +587,7 @@
@VisibleForTesting
public boolean isAnimating() {
- return mExpandAnimation != null && mExpandAnimation.isRunning();
+ return false;
}
/**
@@ -901,8 +666,7 @@
private LogMaker notificationControlsLogMaker() {
return getLogMaker().setCategory(MetricsEvent.ACTION_NOTE_CONTROLS)
.setType(MetricsEvent.TYPE_OPEN)
- .setSubtype(mIsForBlockingHelper ? MetricsEvent.BLOCKING_HELPER_DISPLAY
- : MetricsEvent.BLOCKING_HELPER_UNKNOWN);
+ .setSubtype(MetricsEvent.BLOCKING_HELPER_UNKNOWN);
}
@Retention(SOURCE)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationUndoLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationUndoLayout.java
deleted file mode 100644
index 3ea8195..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationUndoLayout.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2018 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.statusbar.notification.row;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.FrameLayout;
-
-import com.android.systemui.R;
-
-/**
- * Custom view for the NotificationInfo confirmation views so that the confirmation text can
- * occupy the full width of the notification and push the undo button down to the next line if
- * necessary.
- *
- * @see NotificationInfo
- */
-public class NotificationUndoLayout extends FrameLayout {
- /**
- * View for the prompt/confirmation text to tell the user the previous action was successful.
- */
- private View mConfirmationTextView;
- /** Undo button (actionable text) view. */
- private View mUndoView;
-
- /**
- * Whether {@link #mConfirmationTextView} is multiline and will require the full width of the
- * parent (which causes the {@link #mUndoView} to push down).
- */
- private boolean mIsMultiline = false;
- private int mMultilineTopMargin;
-
- public NotificationUndoLayout(Context context) {
- this(context, null);
- }
-
- public NotificationUndoLayout(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- public NotificationUndoLayout(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- }
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
-
- mConfirmationTextView = findViewById(R.id.confirmation_text);
- mUndoView = findViewById(R.id.undo);
-
- mMultilineTopMargin = getResources().getDimensionPixelOffset(
- com.android.internal.R.dimen.notification_content_margin_start);
- }
-
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
-
- LayoutParams confirmationLayoutParams =
- (LayoutParams) mConfirmationTextView.getLayoutParams();
- LayoutParams undoLayoutParams =(LayoutParams) mUndoView.getLayoutParams();
-
- int measuredWidth = getMeasuredWidth();
- // Ignore the left margin on the undo button - no need for additional extra space between
- // the text and the button.
- int requiredWidth = mConfirmationTextView.getMeasuredWidth()
- + confirmationLayoutParams.rightMargin
- + confirmationLayoutParams.leftMargin
- + mUndoView.getMeasuredWidth()
- + undoLayoutParams.rightMargin;
- // If the measured width isn't enough to accommodate both the undo button and the text in
- // the same line, we'll need to adjust the view to be multi-line. Otherwise, we're done.
- if (requiredWidth > measuredWidth) {
- mIsMultiline = true;
-
- // Update height requirement to the text height and the button's height (along with
- // additional spacing for the top of the text).
- int updatedHeight = mMultilineTopMargin
- + mConfirmationTextView.getMeasuredHeight()
- + mUndoView.getMeasuredHeight()
- + undoLayoutParams.topMargin
- + undoLayoutParams.bottomMargin;
-
- setMeasuredDimension(measuredWidth, updatedHeight);
- } else {
- mIsMultiline = false;
- }
- }
-
- @Override
- protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
- // If the text view and undo view don't fit on the same line, we'll need to manually lay
- // out the content.
- if (mIsMultiline) {
- // Re-align parent right/bottom values. Left and top are considered to be 0.
- int parentBottom = getMeasuredHeight();
- int parentRight = getMeasuredWidth();
-
- LayoutParams confirmationLayoutParams =
- (LayoutParams) mConfirmationTextView.getLayoutParams();
- LayoutParams undoLayoutParams = (LayoutParams) mUndoView.getLayoutParams();
-
- // The confirmation text occupies the full width as computed earlier. Both side margins
- // are equivalent, so we only need to grab the left one here.
- mConfirmationTextView.layout(
- confirmationLayoutParams.leftMargin,
- mMultilineTopMargin,
- confirmationLayoutParams.leftMargin + mConfirmationTextView.getMeasuredWidth(),
- mMultilineTopMargin + mConfirmationTextView.getMeasuredHeight());
-
- // The undo button is aligned bottom|end with the parent in the case of multiline text.
- int undoViewLeft = getLayoutDirection() == View.LAYOUT_DIRECTION_RTL
- ? undoLayoutParams.rightMargin
- : parentRight - mUndoView.getMeasuredWidth() - undoLayoutParams.rightMargin;
- mUndoView.layout(
- undoViewLeft,
- parentBottom - mUndoView.getMeasuredHeight() - undoLayoutParams.bottomMargin,
- undoViewLeft + mUndoView.getMeasuredWidth(),
- parentBottom - undoLayoutParams.bottomMargin);
- } else {
- super.onLayout(changed, left, top, right, bottom);
- }
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationConversationTemplateViewWrapper.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationConversationTemplateViewWrapper.kt
new file mode 100644
index 0000000..1e2571b5
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationConversationTemplateViewWrapper.kt
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.row.wrapper
+
+import android.content.Context
+import android.view.View
+
+import com.android.internal.widget.ConversationLayout
+import com.android.internal.widget.MessagingLinearLayout
+import com.android.systemui.R
+import com.android.systemui.statusbar.notification.NotificationUtils
+import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow
+
+/**
+ * Wraps a notification containing a converation template
+ */
+class NotificationConversationTemplateViewWrapper constructor(
+ ctx: Context,
+ view: View,
+ row: ExpandableNotificationRow
+)
+ : NotificationTemplateViewWrapper(ctx, view, row) {
+
+ private val minHeightWithActions: Int
+ private val conversationLayout: ConversationLayout
+ private var conversationIcon: View? = null
+ private var conversationBadge: View? = null
+ private var expandButton: View? = null
+ private var messagingLinearLayout: MessagingLinearLayout? = null
+
+ init {
+ conversationLayout = view as ConversationLayout
+ minHeightWithActions = NotificationUtils.getFontScaledHeight(ctx,
+ R.dimen.notification_messaging_actions_min_height)
+ }
+
+ private fun resolveViews() {
+ messagingLinearLayout = conversationLayout.messagingLinearLayout
+ conversationIcon = conversationLayout.requireViewById(
+ com.android.internal.R.id.conversation_icon)
+ conversationBadge = conversationLayout.requireViewById(
+ com.android.internal.R.id.conversation_icon_badge)
+ expandButton = conversationLayout.requireViewById(
+ com.android.internal.R.id.expand_button)
+ }
+
+ override fun onContentUpdated(row: ExpandableNotificationRow) {
+ // Reinspect the notification. Before the super call, because the super call also updates
+ // the transformation types and we need to have our values set by then.
+ resolveViews()
+ super.onContentUpdated(row)
+ }
+
+ override fun updateTransformedTypes() {
+ // This also clears the existing types
+ super.updateTransformedTypes()
+ messagingLinearLayout?.let {
+ mTransformationHelper.addTransformedView(it.id, it)
+ }
+ conversationIcon?.let {
+ mTransformationHelper.addViewTransformingToSimilar(it.id, it)
+ }
+ conversationBadge?.let {
+ mTransformationHelper.addViewTransformingToSimilar(it.id, it)
+ }
+ expandButton?.let {
+ mTransformationHelper.addViewTransformingToSimilar(it.id, it)
+ }
+ }
+
+ override fun setRemoteInputVisible(visible: Boolean) {
+ conversationLayout.showHistoricMessages(visible)
+ }
+
+ override fun updateExpandability(expandable: Boolean, onClickListener: View.OnClickListener?) {
+ conversationLayout.updateExpandability(expandable, onClickListener)
+ }
+
+ override fun getMinLayoutHeight(): Int {
+ if (mActionsContainer != null && mActionsContainer.visibility != View.GONE) {
+ return minHeightWithActions
+ } else {
+ return super.getMinLayoutHeight()
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationHeaderViewWrapper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationHeaderViewWrapper.java
index 5e52c0a..1d06198 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationHeaderViewWrapper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationHeaderViewWrapper.java
@@ -53,12 +53,13 @@
protected final ViewTransformationHelper mTransformationHelper;
protected int mColor;
- private ImageView mIcon;
+ private ImageView mIcon;
private NotificationExpandButton mExpandButton;
protected NotificationHeaderView mNotificationHeader;
private TextView mHeaderText;
private ImageView mWorkProfileImage;
+
private boolean mIsLowPriority;
private boolean mTransformLowPriorityTitle;
private boolean mShowExpandButtonAtEnd;
@@ -105,12 +106,16 @@
mExpandButton = mView.findViewById(com.android.internal.R.id.expand_button);
mWorkProfileImage = mView.findViewById(com.android.internal.R.id.profile_badge);
mNotificationHeader = mView.findViewById(com.android.internal.R.id.notification_header);
- mNotificationHeader.setShowExpandButtonAtEnd(mShowExpandButtonAtEnd);
- mColor = mNotificationHeader.getOriginalIconColor();
+ if (mNotificationHeader != null) {
+ mNotificationHeader.setShowExpandButtonAtEnd(mShowExpandButtonAtEnd);
+ mColor = mNotificationHeader.getOriginalIconColor();
+ }
}
private void addAppOpsOnClickListener(ExpandableNotificationRow row) {
- mNotificationHeader.setAppOpsOnClickListener(row.getAppOpsOnClickListener());
+ if (mNotificationHeader != null) {
+ mNotificationHeader.setAppOpsOnClickListener(row.getAppOpsOnClickListener());
+ }
}
@Override
@@ -127,9 +132,11 @@
updateCropToPaddingForImageViews();
Notification notification = row.getEntry().getSbn().getNotification();
mIcon.setTag(ImageTransformState.ICON_TAG, notification.getSmallIcon());
- // The work profile image is always the same lets just set the icon tag for it not to
- // animate
- mWorkProfileImage.setTag(ImageTransformState.ICON_TAG, notification.getSmallIcon());
+ if (mWorkProfileImage != null) {
+ // The work profile image is always the same lets just set the icon tag for it not to
+ // animate
+ mWorkProfileImage.setTag(ImageTransformState.ICON_TAG, notification.getSmallIcon());
+ }
// We need to reset all views that are no longer transforming in case a view was previously
// transformed, but now we decided to transform its container instead.
@@ -174,8 +181,9 @@
protected void updateTransformedTypes() {
mTransformationHelper.reset();
- mTransformationHelper.addTransformedView(TransformableView.TRANSFORMING_VIEW_ICON, mIcon);
- if (mIsLowPriority) {
+ mTransformationHelper.addTransformedView(TransformableView.TRANSFORMING_VIEW_ICON,
+ mIcon);
+ if (mIsLowPriority && mHeaderText != null) {
mTransformationHelper.addTransformedView(TransformableView.TRANSFORMING_VIEW_TITLE,
mHeaderText);
}
@@ -184,7 +192,9 @@
@Override
public void updateExpandability(boolean expandable, View.OnClickListener onClickListener) {
mExpandButton.setVisibility(expandable ? View.VISIBLE : View.GONE);
- mNotificationHeader.setOnClickListener(expandable ? onClickListener : null);
+ if (mNotificationHeader != null) {
+ mNotificationHeader.setOnClickListener(expandable ? onClickListener : null);
+ }
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java
index 0a1a2fe..d41f5af 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java
@@ -353,8 +353,12 @@
@Override
public void setHeaderVisibleAmount(float headerVisibleAmount) {
super.setHeaderVisibleAmount(headerVisibleAmount);
- mNotificationHeader.setAlpha(headerVisibleAmount);
- mHeaderTranslation = (1.0f - headerVisibleAmount) * mFullHeaderTranslation;
+ float headerTranslation = 0f;
+ if (mNotificationHeader != null) {
+ mNotificationHeader.setAlpha(headerVisibleAmount);
+ headerTranslation = (1.0f - headerVisibleAmount) * mFullHeaderTranslation;
+ }
+ mHeaderTranslation = headerTranslation;
mView.setTranslationY(mHeaderTranslation);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapper.java
index c2eff8a..c834e4b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationViewWrapper.java
@@ -35,6 +35,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.graphics.ColorUtils;
import com.android.internal.util.ContrastColorUtil;
+import com.android.internal.widget.ConversationLayout;
import com.android.systemui.statusbar.CrossFadeHelper;
import com.android.systemui.statusbar.TransformableView;
import com.android.systemui.statusbar.notification.TransformState;
@@ -61,6 +62,9 @@
return new NotificationMediaTemplateViewWrapper(ctx, v, row);
} else if ("messaging".equals(v.getTag())) {
return new NotificationMessagingTemplateViewWrapper(ctx, v, row);
+ } else if ("conversation".equals(v.getTag())) {
+ return new NotificationConversationTemplateViewWrapper(ctx, (ConversationLayout) v,
+ row);
}
Class<? extends Notification.Style> style =
row.getEntry().getSbn().getNotification().getNotificationStyle();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
index 1bd9bbe..cfcbd88 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java
@@ -81,6 +81,8 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.graphics.ColorUtils;
import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.UiEvent;
+import com.android.internal.logging.UiEventLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.statusbar.IStatusBarService;
import com.android.internal.statusbar.NotificationVisibility;
@@ -502,6 +504,7 @@
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
@VisibleForTesting
protected final MetricsLogger mMetricsLogger = Dependency.get(MetricsLogger.class);
+ protected final UiEventLogger mUiEventLogger;
private final NotificationRemoteInputManager mRemoteInputManager =
Dependency.get(NotificationRemoteInputManager.class);
private final SysuiColorExtractor mColorExtractor = Dependency.get(SysuiColorExtractor.class);
@@ -547,7 +550,8 @@
FeatureFlags featureFlags,
NotifPipeline notifPipeline,
NotificationEntryManager entryManager,
- NotifCollection notifCollection
+ NotifCollection notifCollection,
+ UiEventLogger uiEventLogger
) {
super(context, attrs, 0, 0);
Resources res = getResources();
@@ -649,6 +653,7 @@
mDynamicPrivacyController = dynamicPrivacyController;
mStatusbarStateController = statusBarStateController;
initializeForegroundServiceSection(fgsFeatureController);
+ mUiEventLogger = uiEventLogger;
}
private void initializeForegroundServiceSection(
@@ -5524,7 +5529,8 @@
}
@ShadeViewRefactor(RefactorComponent.SHADE_VIEW)
- private void clearNotifications(
+ @VisibleForTesting
+ void clearNotifications(
@SelectedRows int selection,
boolean closeShade) {
// animate-swipe all dismissable notifications, then animate the shade closed
@@ -5567,6 +5573,9 @@
}
}
+ // Log dismiss event even if there's nothing to dismiss
+ mUiEventLogger.log(NotificationPanelEvent.fromSelection(selection));
+
if (viewsToRemove.isEmpty()) {
if (closeShade) {
Dependency.get(ShadeController.class).animateCollapsePanels(
@@ -6737,4 +6746,35 @@
public static final int ROWS_HIGH_PRIORITY = 1;
/** Only rows where entry.isHighPriority() is false. */
public static final int ROWS_GENTLE = 2;
+
+ /**
+ * Enum for UiEvent logged from this class
+ */
+ enum NotificationPanelEvent implements UiEventLogger.UiEventEnum {
+ INVALID(0),
+ @UiEvent(doc = "User dismissed all notifications from notification panel.")
+ DISMISS_ALL_NOTIFICATIONS_PANEL(312),
+ @UiEvent(doc = "User dismissed all silent notifications from notification panel.")
+ DISMISS_SILENT_NOTIFICATIONS_PANEL(314);
+ private final int mId;
+ NotificationPanelEvent(int id) {
+ mId = id;
+ }
+ @Override public int getId() {
+ return mId;
+ }
+
+ public static UiEventLogger.UiEventEnum fromSelection(@SelectedRows int selection) {
+ if (selection == ROWS_ALL) {
+ return DISMISS_ALL_NOTIFICATIONS_PANEL;
+ }
+ if (selection == ROWS_GENTLE) {
+ return DISMISS_SILENT_NOTIFICATIONS_PANEL;
+ }
+ if (NotificationStackScrollLayout.DEBUG) {
+ throw new IllegalArgumentException("Unexpected selection" + selection);
+ }
+ return INVALID;
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackStateAnimator.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackStateAnimator.java
index 0996ff2..14442e3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackStateAnimator.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackStateAnimator.java
@@ -453,9 +453,10 @@
needsAnimation = false;
}
NotificationEntry entry = row.getEntry();
- StatusBarIconView icon = entry.icon;
- if (entry.centeredIcon != null && entry.centeredIcon.getParent() != null) {
- icon = entry.centeredIcon;
+ StatusBarIconView icon = entry.getIcons().getStatusBarIcon();
+ final StatusBarIconView centeredIcon = entry.getIcons().getCenteredIcon();
+ if (centeredIcon != null && centeredIcon.getParent() != null) {
+ icon = centeredIcon;
}
if (icon.getParent() != null) {
icon.getLocationOnScreen(mTmpLocation);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java
index 745843d..adca10f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/EdgeBackGestureHandler.java
@@ -44,6 +44,7 @@
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
+import com.android.internal.policy.GestureNavigationSettingsObserver;
import com.android.systemui.Dependency;
import com.android.systemui.R;
import com.android.systemui.bubbles.BubbleController;
@@ -99,8 +100,10 @@
private final Region mExcludeRegion = new Region();
private final Region mUnrestrictedExcludeRegion = new Region();
- // The edge width where touch down is allowed
- private int mEdgeWidth;
+ // The left side edge width where touch down is allowed
+ private int mEdgeWidthLeft;
+ // The right side edge width where touch down is allowed
+ private int mEdgeWidthRight;
// The bottom gesture area height
private int mBottomGestureHeight;
// The slop to distinguish between horizontal and vertical motion
@@ -127,6 +130,8 @@
private int mRightInset;
private int mSysUiFlags;
+ private final GestureNavigationSettingsObserver mGestureNavigationSettingsObserver;
+
private final NavigationEdgeBackPlugin.BackCallback mBackCallback =
new NavigationEdgeBackPlugin.BackCallback() {
@Override
@@ -174,13 +179,17 @@
mLongPressTimeout = Math.min(MAX_LONG_PRESS_TIMEOUT,
ViewConfiguration.getLongPressTimeout());
+ mGestureNavigationSettingsObserver = new GestureNavigationSettingsObserver(
+ mContext.getMainThreadHandler(), mContext, () -> updateCurrentUserResources(res));
+
updateCurrentUserResources(res);
sysUiFlagContainer.addCallback(sysUiFlags -> mSysUiFlags = sysUiFlags);
}
public void updateCurrentUserResources(Resources res) {
- mEdgeWidth = res.getDimensionPixelSize(
- com.android.internal.R.dimen.config_backGestureInset);
+ mEdgeWidthLeft = mGestureNavigationSettingsObserver.getLeftSensitivity(res);
+ mEdgeWidthRight = mGestureNavigationSettingsObserver.getRightSensitivity(res);
+
mBottomGestureHeight = res.getDimensionPixelSize(
com.android.internal.R.dimen.navigation_bar_gesture_height);
}
@@ -236,6 +245,7 @@
}
if (!mIsEnabled) {
+ mGestureNavigationSettingsObserver.unregister();
mContext.getSystemService(DisplayManager.class).unregisterDisplayListener(this);
mPluginManager.removePluginListener(this);
@@ -248,6 +258,7 @@
}
} else {
+ mGestureNavigationSettingsObserver.register();
updateDisplaySize();
mContext.getSystemService(DisplayManager.class).registerDisplayListener(this,
mContext.getMainThreadHandler());
@@ -321,7 +332,8 @@
private boolean isWithinTouchRegion(int x, int y) {
// Disallow if too far from the edge
- if (x > mEdgeWidth + mLeftInset && x < (mDisplaySize.x - mEdgeWidth - mRightInset)) {
+ if (x > mEdgeWidthLeft + mLeftInset
+ && x < (mDisplaySize.x - mEdgeWidthRight - mRightInset)) {
return false;
}
@@ -364,7 +376,7 @@
if (action == MotionEvent.ACTION_DOWN) {
// Verify if this is in within the touch region and we aren't in immersive mode, and
// either the bouncer is showing or the notification panel is hidden
- mIsOnLeftEdge = ev.getX() <= mEdgeWidth + mLeftInset;
+ mIsOnLeftEdge = ev.getX() <= mEdgeWidthLeft + mLeftInset;
mInRejectedExclusion = false;
mAllowGesture = !QuickStepContract.isBackGestureDisabled(mSysUiFlags)
&& isWithinTouchRegion((int) ev.getX(), (int) ev.getY());
@@ -461,7 +473,8 @@
pw.println(" mExcludeRegion=" + mExcludeRegion);
pw.println(" mUnrestrictedExcludeRegion=" + mUnrestrictedExcludeRegion);
pw.println(" mIsAttached=" + mIsAttached);
- pw.println(" mEdgeWidth=" + mEdgeWidth);
+ pw.println(" mEdgeWidthLeft=" + mEdgeWidthLeft);
+ pw.println(" mEdgeWidthRight=" + mEdgeWidthRight);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
index c39ee3a..51c02c9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpAppearanceController.java
@@ -269,7 +269,7 @@
}
updateIsolatedIconLocation(false /* requireUpdate */);
mNotificationIconAreaController.showIconIsolated(newEntry == null ? null
- : newEntry.icon, animateIsolation);
+ : newEntry.getIcons().getStatusBarIcon(), animateIsolation);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
index ee31300..90bc075b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -492,7 +492,7 @@
try {
result = ActivityTaskManager.getService().startActivityAsUser(
null, getContext().getBasePackageName(),
- getContext().getFeatureId(), intent,
+ getContext().getAttributionTag(), intent,
intent.resolveTypeIfNeeded(getContext().getContentResolver()),
null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, o.toBundle(),
UserHandle.CURRENT.getIdentifier());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextView.java
index c5c3fff..c54fa29 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextView.java
@@ -27,6 +27,8 @@
*/
public class KeyguardIndicationTextView extends TextView {
+ private CharSequence mText = "";
+
public KeyguardIndicationTextView(Context context) {
super(context);
}
@@ -53,10 +55,12 @@
// TODO: Animation, make sure that we will show one indication long enough.
if (TextUtils.isEmpty(text)) {
+ mText = "";
setVisibility(View.INVISIBLE);
- } else {
+ } else if (!TextUtils.equals(text, mText)) {
+ mText = text;
setVisibility(View.VISIBLE);
- setText(text);
+ setText(mText);
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
index c29ec9e..cf9d43e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
@@ -26,7 +26,6 @@
import android.graphics.drawable.Animatable2;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.graphics.drawable.Drawable;
-import android.hardware.biometrics.BiometricSourceType;
import android.os.Trace;
import android.provider.Settings;
import android.text.TextUtils;
@@ -34,22 +33,17 @@
import android.view.ViewTreeObserver;
import android.view.accessibility.AccessibilityNodeInfo;
-import androidx.annotation.Nullable;
-
import com.android.internal.graphics.ColorUtils;
import com.android.keyguard.KeyguardUpdateMonitor;
-import com.android.keyguard.KeyguardUpdateMonitorCallback;
import com.android.systemui.Dependency;
import com.android.systemui.Interpolators;
import com.android.systemui.R;
-import com.android.systemui.dock.DockManager;
import com.android.systemui.statusbar.KeyguardAffordanceView;
import com.android.systemui.statusbar.StatusBarState;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.phone.ScrimController.ScrimVisibility;
import com.android.systemui.statusbar.policy.AccessibilityController;
import com.android.systemui.statusbar.policy.KeyguardStateController;
-import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -61,8 +55,7 @@
* Manages the different states and animations of the unlock icon.
*/
public class LockIcon extends KeyguardAffordanceView implements
- KeyguardStateController.Callback, NotificationWakeUpCoordinator.WakeUpListener,
- ViewTreeObserver.OnPreDrawListener, OnHeadsUpChangedListener {
+ ViewTreeObserver.OnPreDrawListener {
private static final int STATE_LOCKED = 0;
private static final int STATE_LOCK_OPEN = 1;
@@ -70,7 +63,6 @@
private static final int STATE_BIOMETRICS_ERROR = 3;
private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
private final AccessibilityController mAccessibilityController;
- private final DockManager mDockManager;
private final KeyguardStateController mKeyguardStateController;
private final KeyguardBypassController mBypassController;
private final NotificationWakeUpCoordinator mWakeUpCoordinator;
@@ -130,43 +122,6 @@
update();
}
};
- private final DockManager.DockEventListener mDockEventListener =
- new DockManager.DockEventListener() {
- @Override
- public void onEvent(int event) {
- boolean docked = event == DockManager.STATE_DOCKED
- || event == DockManager.STATE_DOCKED_HIDE;
- if (docked != mDocked) {
- mDocked = docked;
- update();
- }
- }
- };
-
- private final KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
- new KeyguardUpdateMonitorCallback() {
- @Override
- public void onSimStateChanged(int subId, int slotId, int simState) {
- mSimLocked = mKeyguardUpdateMonitor.isSimPinSecure();
- update();
- }
-
- @Override
- public void onKeyguardVisibilityChanged(boolean showing) {
- update();
- }
-
- @Override
- public void onBiometricRunningStateChanged(boolean running,
- BiometricSourceType biometricSourceType) {
- update();
- }
-
- @Override
- public void onStrongAuthStateChanged(int userId) {
- update();
- }
- };
@Inject
public LockIcon(@Named(VIEW_CONTEXT) Context context, AttributeSet attrs,
@@ -174,7 +129,6 @@
KeyguardBypassController bypassController,
NotificationWakeUpCoordinator wakeUpCoordinator,
KeyguardStateController keyguardStateController,
- @Nullable DockManager dockManager,
HeadsUpManagerPhone headsUpManager) {
super(context, attrs);
mContext = context;
@@ -183,7 +137,6 @@
mBypassController = bypassController;
mWakeUpCoordinator = wakeUpCoordinator;
mKeyguardStateController = keyguardStateController;
- mDockManager = dockManager;
mHeadsUpManager = headsUpManager;
}
@@ -191,24 +144,14 @@
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mKeyguardStateController.addCallback(mKeyguardMonitorCallback);
- mKeyguardUpdateMonitor.registerCallback(mUpdateMonitorCallback);
- mWakeUpCoordinator.addListener(this);
mSimLocked = mKeyguardUpdateMonitor.isSimPinSecure();
- if (mDockManager != null) {
- mDockManager.addListener(mDockEventListener);
- }
update();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
- mKeyguardUpdateMonitor.removeCallback(mUpdateMonitorCallback);
mKeyguardStateController.removeCallback(mKeyguardMonitorCallback);
- mWakeUpCoordinator.removeListener(this);
- if (mDockManager != null) {
- mDockManager.removeListener(mDockEventListener);
- }
}
/**
@@ -306,7 +249,7 @@
* Update the icon visibility
* @return true if the visibility changed
*/
- private boolean updateIconVisibility() {
+ boolean updateIconVisibility() {
boolean onAodNotPulsingOrDocked = mDozing && (!mPulsing || mDocked);
boolean invisible = onAodNotPulsingOrDocked || mWakeAndUnlockRunning
|| mShowingLaunchAffordance;
@@ -424,16 +367,6 @@
return -1;
}
- @Override
- public void onFullyHiddenChanged(boolean isFullyHidden) {
- if (mBypassController.getBypassEnabled()) {
- boolean changed = updateIconVisibility();
- if (changed) {
- update();
- }
- }
- }
-
public void setBouncerShowingScrimmed(boolean bouncerShowing) {
mBouncerShowingScrimmed = bouncerShowing;
if (mBypassController.getBypassEnabled()) {
@@ -454,6 +387,18 @@
updateDarkTint();
}
+ void setSimLocked(boolean simLocked) {
+ mSimLocked = simLocked;
+ }
+
+ /** Set if the device is docked. */
+ public void setDocked(boolean docked) {
+ if (mDocked != docked) {
+ mDocked = docked;
+ update();
+ }
+ }
+
@Retention(RetentionPolicy.SOURCE)
@IntDef({ERROR, UNLOCK, LOCK, SCANNING})
@interface LockAnimIndex {}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenLockIconController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenLockIconController.java
index 698a430..2b1a8a4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenLockIconController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockscreenLockIconController.java
@@ -18,20 +18,29 @@
import android.content.res.TypedArray;
import android.graphics.Color;
+import android.hardware.biometrics.BiometricSourceType;
import android.view.View;
import android.view.ViewGroup;
+import androidx.annotation.Nullable;
+
import com.android.internal.logging.nano.MetricsProto;
import com.android.internal.widget.LockPatternUtils;
import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.keyguard.KeyguardUpdateMonitorCallback;
import com.android.systemui.R;
+import com.android.systemui.dock.DockManager;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.KeyguardIndicationController;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator.WakeUpListener;
import com.android.systemui.statusbar.policy.AccessibilityController;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.statusbar.policy.ConfigurationController.ConfigurationListener;
+import java.util.Optional;
+
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -47,6 +56,9 @@
private final KeyguardIndicationController mKeyguardIndicationController;
private final StatusBarStateController mStatusBarStateController;
private final ConfigurationController mConfigurationController;
+ private final NotificationWakeUpCoordinator mNotificationWakeUpCoordinator;
+ private final KeyguardBypassController mKeyguardBypassController;
+ private final Optional<DockManager> mDockManager;
private LockIcon mLockIcon;
private View.OnAttachStateChangeListener mOnAttachStateChangeListener =
@@ -55,6 +67,10 @@
public void onViewAttachedToWindow(View v) {
mStatusBarStateController.addCallback(mSBStateListener);
mConfigurationController.addCallback(mConfigurationListener);
+ mNotificationWakeUpCoordinator.addListener(mWakeUpListener);
+ mKeyguardUpdateMonitor.registerCallback(mUpdateMonitorCallback);
+
+ mDockManager.ifPresent(dockManager -> dockManager.addListener(mDockEventListener));
mConfigurationListener.onThemeChanged();
}
@@ -63,6 +79,11 @@
public void onViewDetachedFromWindow(View v) {
mStatusBarStateController.removeCallback(mSBStateListener);
mConfigurationController.removeCallback(mConfigurationListener);
+ mNotificationWakeUpCoordinator.removeListener(mWakeUpListener);
+ mKeyguardUpdateMonitor.removeCallback(mUpdateMonitorCallback);
+
+
+ mDockManager.ifPresent(dockManager -> dockManager.removeListener(mDockEventListener));
}
};
@@ -115,6 +136,47 @@
}
};
+ private final WakeUpListener mWakeUpListener = new WakeUpListener() {
+ @Override
+ public void onFullyHiddenChanged(boolean isFullyHidden) {
+ if (mKeyguardBypassController.getBypassEnabled()) {
+ boolean changed = mLockIcon.updateIconVisibility();
+ if (changed) {
+ mLockIcon.update();
+ }
+ }
+ }
+ };
+
+ private final KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
+ new KeyguardUpdateMonitorCallback() {
+ @Override
+ public void onSimStateChanged(int subId, int slotId, int simState) {
+ mLockIcon.setSimLocked(mKeyguardUpdateMonitor.isSimPinSecure());
+ mLockIcon.update();
+ }
+
+ @Override
+ public void onKeyguardVisibilityChanged(boolean showing) {
+ mLockIcon.update();
+ }
+
+ @Override
+ public void onBiometricRunningStateChanged(boolean running,
+ BiometricSourceType biometricSourceType) {
+ mLockIcon.update();
+ }
+
+ @Override
+ public void onStrongAuthStateChanged(int userId) {
+ mLockIcon.update();
+ }
+ };
+
+ private final DockManager.DockEventListener mDockEventListener =
+ event -> mLockIcon.setDocked(event == DockManager.STATE_DOCKED
+ || event == DockManager.STATE_DOCKED_HIDE);
+
@Inject
public LockscreenLockIconController(LockscreenGestureLogger lockscreenGestureLogger,
KeyguardUpdateMonitor keyguardUpdateMonitor,
@@ -123,7 +185,10 @@
AccessibilityController accessibilityController,
KeyguardIndicationController keyguardIndicationController,
StatusBarStateController statusBarStateController,
- ConfigurationController configurationController) {
+ ConfigurationController configurationController,
+ NotificationWakeUpCoordinator notificationWakeUpCoordinator,
+ KeyguardBypassController keyguardBypassController,
+ @Nullable DockManager dockManager) {
mLockscreenGestureLogger = lockscreenGestureLogger;
mKeyguardUpdateMonitor = keyguardUpdateMonitor;
mLockPatternUtils = lockPatternUtils;
@@ -132,6 +197,9 @@
mKeyguardIndicationController = keyguardIndicationController;
mStatusBarStateController = statusBarStateController;
mConfigurationController = configurationController;
+ mNotificationWakeUpCoordinator = notificationWakeUpCoordinator;
+ mKeyguardBypassController = keyguardBypassController;
+ mDockManager = dockManager == null ? Optional.empty() : Optional.of(dockManager);
mKeyguardIndicationController.setLockIconController(this);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
index 02cf8cc..31266db 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarFragment.java
@@ -205,6 +205,28 @@
private final Handler mHandler;
+ private final AutoHideUiElement mAutoHideUiElement = new AutoHideUiElement() {
+ @Override
+ public void synchronizeState() {
+ checkNavBarModes();
+ }
+
+ @Override
+ public boolean shouldHideOnTouch() {
+ return !mNotificationRemoteInputManager.getController().isRemoteInputActive();
+ }
+
+ @Override
+ public boolean isVisible() {
+ return isTransientShown();
+ }
+
+ @Override
+ public void hide() {
+ clearTransient();
+ }
+ };
+
private final OverviewProxyListener mOverviewProxyListener = new OverviewProxyListener() {
@Override
public void onConnectionChanged(boolean isConnected) {
@@ -529,14 +551,15 @@
public void setWindowState(
int displayId, @WindowType int window, @WindowVisibleState int state) {
if (displayId == mDisplayId
- && mNavigationBarView != null
&& window == StatusBarManager.WINDOW_NAVIGATION_BAR
&& mNavigationBarWindowState != state) {
mNavigationBarWindowState = state;
+ updateSystemUiStateFlags(-1);
if (DEBUG_WINDOW_STATE) Log.d(TAG, "Navigation bar " + windowStateToString(state));
- updateSystemUiStateFlags(-1);
- mNavigationBarView.setWindowVisible(isNavBarWindowVisible());
+ if (mNavigationBarView != null) {
+ mNavigationBarView.setWindowVisible(isNavBarWindowVisible());
+ }
}
}
@@ -1052,28 +1075,13 @@
/** Sets {@link AutoHideController} to the navigation bar. */
public void setAutoHideController(AutoHideController autoHideController) {
+ if (mAutoHideController != null) {
+ mAutoHideController.removeAutoHideUiElement(mAutoHideUiElement);
+ }
mAutoHideController = autoHideController;
- mAutoHideController.addAutoHideUiElement(new AutoHideUiElement() {
- @Override
- public void synchronizeState() {
- checkNavBarModes();
- }
-
- @Override
- public boolean shouldHideOnTouch() {
- return !mNotificationRemoteInputManager.getController().isRemoteInputActive();
- }
-
- @Override
- public boolean isVisible() {
- return isTransientShown();
- }
-
- @Override
- public void hide() {
- clearTransient();
- }
- });
+ if (mAutoHideController != null) {
+ mAutoHideController.addAutoHideUiElement(mAutoHideUiElement);
+ }
}
private boolean isTransientShown() {
@@ -1212,6 +1220,7 @@
@Override
public void onViewDetachedFromWindow(View v) {
FragmentHostManager.removeAndDestroy(v);
+ navigationBarView.removeOnAttachStateChangeListener(this);
}
});
context.getSystemService(WindowManager.class).addView(navigationBarView, lp);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationModeController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationModeController.java
index 43ac4cf..d24ccf3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationModeController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationModeController.java
@@ -28,6 +28,7 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.content.om.IOverlayManager;
+import android.content.om.OverlayInfo;
import android.content.pm.PackageManager;
import android.content.res.ApkAssets;
import android.os.PatternMatcher;
@@ -172,6 +173,9 @@
public void updateCurrentInteractionMode(boolean notify) {
mCurrentUserContext = getCurrentUserContext();
int mode = getCurrentInteractionMode(mCurrentUserContext);
+ if (mode == NAV_BAR_MODE_GESTURAL) {
+ switchToDefaultGestureNavOverlayIfNecessary();
+ }
mUiBgExecutor.execute(() -> {
Settings.Secure.putString(mCurrentUserContext.getContentResolver(),
Secure.NAVIGATION_MODE, String.valueOf(mode));
@@ -277,6 +281,34 @@
}
}
+ private void switchToDefaultGestureNavOverlayIfNecessary() {
+ final int userId = mCurrentUserContext.getUserId();
+ try {
+ final IOverlayManager om = mOverlayManager;
+ final OverlayInfo info = om.getOverlayInfo(NAV_BAR_MODE_GESTURAL_OVERLAY, userId);
+ if (info != null && !info.isEnabled()) {
+ // Enable the default gesture nav overlay, and move the back gesture inset scale to
+ // Settings.Secure for left and right sensitivity.
+ final int curInset = mCurrentUserContext.getResources().getDimensionPixelSize(
+ com.android.internal.R.dimen.config_backGestureInset);
+ om.setEnabledExclusiveInCategory(NAV_BAR_MODE_GESTURAL_OVERLAY, userId);
+ final int defInset = mCurrentUserContext.getResources().getDimensionPixelSize(
+ com.android.internal.R.dimen.config_backGestureInset);
+
+ final float scale = defInset == 0 ? 1.0f : ((float) curInset) / defInset;
+ Settings.Secure.putFloat(mCurrentUserContext.getContentResolver(),
+ Secure.BACK_GESTURE_INSET_SCALE_LEFT, scale);
+ Settings.Secure.putFloat(mCurrentUserContext.getContentResolver(),
+ Secure.BACK_GESTURE_INSET_SCALE_RIGHT, scale);
+ if (DEBUG) {
+ Log.v(TAG, "Moved back sensitivity for user " + userId + " to scale " + scale);
+ }
+ }
+ } catch (SecurityException | IllegalStateException | RemoteException e) {
+ Log.e(TAG, "Failed to switch to default gesture nav overlay for user " + userId);
+ }
+ }
+
public void setModeOverlay(String overlayPkg, int userId) {
mUiBgExecutor.execute(() -> {
try {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java
deleted file mode 100644
index 5d8044f..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationPrototypeController.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2008 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.statusbar.phone;
-
-import static android.view.Display.DEFAULT_DISPLAY;
-
-import android.annotation.IntDef;
-import android.content.ComponentCallbacks;
-import android.content.Context;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.database.ContentObserver;
-import android.graphics.Point;
-import android.net.Uri;
-import android.os.Handler;
-import android.provider.Settings;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * Coordinates with the prototype settings plugin app that uses Settings.Global to allow different
- * prototypes to run in the system. The class will handle communication changes from the settings
- * app and call back to listeners.
- */
-public class NavigationPrototypeController extends ContentObserver implements ComponentCallbacks {
- private static final String HIDE_BACK_BUTTON_SETTING = "quickstepcontroller_hideback";
- private static final String HIDE_HOME_BUTTON_SETTING = "quickstepcontroller_hidehome";
- private static final String PROTOTYPE_ENABLED = "prototype_enabled";
-
- public static final String EDGE_SENSITIVITY_WIDTH_SETTING =
- "quickstepcontroller_edge_width_sensitivity";
- private final String GESTURE_MATCH_SETTING = "quickstepcontroller_gesture_match_map";
- public static final String NAV_COLOR_ADAPT_ENABLE_SETTING = "navbar_color_adapt_enable";
- public static final String SHOW_HOME_HANDLE_SETTING = "quickstepcontroller_showhandle";
- public static final String ENABLE_ASSISTANT_GESTURE = "ENABLE_ASSISTANT_GESTURE";
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef({ACTION_DEFAULT, ACTION_QUICKSTEP, ACTION_QUICKSCRUB, ACTION_BACK,
- ACTION_QUICKSWITCH, ACTION_NOTHING, ACTION_ASSISTANT})
- @interface GestureAction {}
- static final int ACTION_DEFAULT = 0;
- static final int ACTION_QUICKSTEP = 1;
- static final int ACTION_QUICKSCRUB = 2;
- static final int ACTION_BACK = 3;
- static final int ACTION_QUICKSWITCH = 4;
- static final int ACTION_NOTHING = 5;
- static final int ACTION_ASSISTANT = 6;
-
- private OnPrototypeChangedListener mListener;
-
- /**
- * Each index corresponds to a different action set in QuickStepController
- * {@see updateSwipeLTRBackSetting}
- */
- private int[] mActionMap = new int[6];
-
- private final Context mContext;
-
- public NavigationPrototypeController(Context context) {
- super(new Handler());
- mContext = context;
- updateSwipeLTRBackSetting();
- }
-
- public void setOnPrototypeChangedListener(OnPrototypeChangedListener listener) {
- mListener = listener;
- }
-
- /**
- * Observe all the settings to react to from prototype settings
- */
- public void register() {
- registerObserver(HIDE_BACK_BUTTON_SETTING);
- registerObserver(HIDE_HOME_BUTTON_SETTING);
- registerObserver(GESTURE_MATCH_SETTING);
- registerObserver(NAV_COLOR_ADAPT_ENABLE_SETTING);
- registerObserver(SHOW_HOME_HANDLE_SETTING);
- registerObserver(ENABLE_ASSISTANT_GESTURE);
- mContext.registerComponentCallbacks(this);
- }
-
- /**
- * Disable observing settings to react to from prototype settings
- */
- public void unregister() {
- mContext.getContentResolver().unregisterContentObserver(this);
- mContext.unregisterComponentCallbacks(this);
- }
-
- @Override
- public void onChange(boolean selfChange, Uri uri) {
- super.onChange(selfChange, uri);
- if (!selfChange && mListener != null) {
- final String path = uri.getPath();
- if (path.endsWith(GESTURE_MATCH_SETTING)) {
- // Get the settings gesture map corresponding to each action
- // {@see updateSwipeLTRBackSetting}
- updateSwipeLTRBackSetting();
- mListener.onGestureRemap(mActionMap);
- } else if (path.endsWith(HIDE_BACK_BUTTON_SETTING)) {
- mListener.onBackButtonVisibilityChanged(
- !getGlobalBool(HIDE_BACK_BUTTON_SETTING, false));
- } else if (path.endsWith(HIDE_HOME_BUTTON_SETTING)) {
- mListener.onHomeButtonVisibilityChanged(!hideHomeButton());
- } else if (path.endsWith(NAV_COLOR_ADAPT_ENABLE_SETTING)) {
- mListener.onColorAdaptChanged(mContext.getDisplayId() == DEFAULT_DISPLAY);
- } else if (path.endsWith(SHOW_HOME_HANDLE_SETTING)) {
- mListener.onHomeHandleVisiblilityChanged(showHomeHandle());
- } else if (path.endsWith(ENABLE_ASSISTANT_GESTURE)) {
- mListener.onAssistantGestureEnabled(isAssistantGestureEnabled());
- }
- }
- }
-
- /**
- * @return the width for edge swipe
- */
- public int getEdgeSensitivityWidth() {
- return mContext.getResources().getDimensionPixelSize(
- com.android.internal.R.dimen.config_backGestureInset);
- }
-
- /**
- * @return full screen height
- */
- public int getEdgeSensitivityHeight() {
- final Point size = new Point();
- mContext.getDisplay().getRealSize(size);
- return size.y;
- }
-
- public boolean isEnabled() {
- return getGlobalBool(PROTOTYPE_ENABLED, false);
- }
-
- /**
- * Retrieve the action map to apply to the quick step controller
- * @return an action map
- */
- int[] getGestureActionMap() {
- return mActionMap;
- }
-
- /**
- * @return if home button should be invisible
- */
- boolean hideHomeButton() {
- return getGlobalBool(HIDE_HOME_BUTTON_SETTING, false /* default */);
- }
-
- boolean showHomeHandle() {
- return getGlobalBool(SHOW_HOME_HANDLE_SETTING, false /* default */);
- }
-
- boolean isAssistantGestureEnabled() {
- return getGlobalBool(ENABLE_ASSISTANT_GESTURE, false /* default */);
- }
-
-
- /**
- * Since Settings.Global cannot pass arrays, use a string to represent each character as a
- * gesture map to actions corresponding to {@see GestureAction}. The number is represented as:
- * Number: [up] [down] [left] [right]
- */
- private void updateSwipeLTRBackSetting() {
- String value = Settings.Global.getString(mContext.getContentResolver(),
- GESTURE_MATCH_SETTING);
- if (value != null) {
- for (int i = 0; i < mActionMap.length; ++i) {
- mActionMap[i] = Character.getNumericValue(value.charAt(i));
- }
- }
- }
-
- private boolean getGlobalBool(String name, boolean defaultVal) {
- return Settings.Global.getInt(mContext.getContentResolver(), name, defaultVal ? 1 : 0) == 1;
- }
-
- private int getGlobalInt(String name, int defaultVal) {
- return Settings.Global.getInt(mContext.getContentResolver(), name, defaultVal);
- }
-
- private void registerObserver(String name) {
- mContext.getContentResolver()
- .registerContentObserver(Settings.Global.getUriFor(name), false, this);
- }
-
- private static int convertDpToPixel(float dp) {
- return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
- }
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- if (mListener != null) {
- mListener.onEdgeSensitivityChanged(getEdgeSensitivityWidth(),
- getEdgeSensitivityHeight());
- }
- }
-
- @Override
- public void onLowMemory() {
- }
-
- public interface OnPrototypeChangedListener {
- void onGestureRemap(@GestureAction int[] actions);
- void onBackButtonVisibilityChanged(boolean visible);
- void onHomeButtonVisibilityChanged(boolean visible);
- void onHomeHandleVisiblilityChanged(boolean visible);
- void onColorAdaptChanged(boolean enabled);
- void onEdgeSensitivityChanged(int width, int height);
- void onAssistantGestureEnabled(boolean enabled);
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
index b09ccff..f58cce5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
@@ -253,8 +253,8 @@
boolean hidePulsing, boolean onlyShowCenteredIcon) {
final boolean isCenteredNotificationIcon = mCenteredIconView != null
- && entry.centeredIcon != null
- && Objects.equals(entry.centeredIcon, mCenteredIconView);
+ && entry.getIcons().getCenteredIcon() != null
+ && Objects.equals(entry.getIcons().getCenteredIcon(), mCenteredIconView);
if (onlyShowCenteredIcon) {
return isCenteredNotificationIcon;
}
@@ -307,7 +307,7 @@
}
private void updateShelfIcons() {
- updateIconsForLayout(entry -> entry.expandedIcon, mShelfIcons,
+ updateIconsForLayout(entry -> entry.getIcons().getShelfIcon(), mShelfIcons,
true /* showAmbient */,
true /* showLowPriority */,
false /* hideDismissed */,
@@ -319,7 +319,7 @@
}
public void updateStatusBarIcons() {
- updateIconsForLayout(entry -> entry.icon, mNotificationIcons,
+ updateIconsForLayout(entry -> entry.getIcons().getStatusBarIcon(), mNotificationIcons,
false /* showAmbient */,
mShowLowPriority,
true /* hideDismissed */,
@@ -331,7 +331,7 @@
}
private void updateCenterIcon() {
- updateIconsForLayout(entry -> entry.centeredIcon, mCenteredIcon,
+ updateIconsForLayout(entry -> entry.getIcons().getCenteredIcon(), mCenteredIcon,
false /* showAmbient */,
true /* showLowPriority */,
false /* hideDismissed */,
@@ -343,7 +343,7 @@
}
public void updateAodNotificationIcons() {
- updateIconsForLayout(entry -> entry.aodIcon, mAodIcons,
+ updateIconsForLayout(entry -> entry.getIcons().getAodIcon(), mAodIcons,
false /* showAmbient */,
true /* showLowPriority */,
true /* hideDismissed */,
@@ -517,7 +517,7 @@
* Shows the icon view given in the center.
*/
public void showIconCentered(NotificationEntry entry) {
- StatusBarIconView icon = entry == null ? null : entry.centeredIcon;
+ StatusBarIconView icon = entry == null ? null : entry.getIcons().getCenteredIcon();
if (!Objects.equals(mCenteredIconView, icon)) {
mCenteredIconView = icon;
updateNotificationIcons();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowController.java
index 75f5023..e1e679f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowController.java
@@ -309,7 +309,8 @@
return !state.mForceCollapsed && (state.isKeyguardShowingAndNotOccluded()
|| state.mPanelVisible || state.mKeyguardFadingAway || state.mBouncerShowing
|| state.mHeadsUpShowing || state.mBubblesShowing
- || state.mScrimsVisibility != ScrimController.TRANSPARENT);
+ || state.mScrimsVisibility != ScrimController.TRANSPARENT)
+ || state.mBackgroundBlurRadius > 0;
}
private void applyFitsSystemWindows(State state) {
@@ -478,6 +479,19 @@
apply(mCurrentState);
}
+ /**
+ * Current blur level, controller by
+ * {@link com.android.systemui.statusbar.NotificationShadeDepthController}.
+ * @param backgroundBlurRadius Radius in pixels.
+ */
+ public void setBackgroundBlurRadius(int backgroundBlurRadius) {
+ if (mCurrentState.mBackgroundBlurRadius == backgroundBlurRadius) {
+ return;
+ }
+ mCurrentState.mBackgroundBlurRadius = backgroundBlurRadius;
+ apply(mCurrentState);
+ }
+
public void setHeadsUpShowing(boolean showing) {
mCurrentState.mHeadsUpShowing = showing;
apply(mCurrentState);
@@ -665,6 +679,7 @@
boolean mForcePluginOpen;
boolean mDozing;
int mScrimsVisibility;
+ int mBackgroundBlurRadius;
private boolean isKeyguardShowingAndNotOccluded() {
return mKeyguardShowing && !mKeyguardOccluded;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewController.java
index f38d416..596a607 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewController.java
@@ -18,7 +18,6 @@
import static android.app.StatusBarManager.WINDOW_STATE_SHOWING;
-import android.annotation.Nullable;
import android.app.StatusBarManager;
import android.graphics.RectF;
import android.hardware.display.AmbientDisplayConfiguration;
@@ -44,7 +43,7 @@
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.DragDownHelper;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
-import com.android.systemui.statusbar.NotificationShadeWindowBlurController;
+import com.android.systemui.statusbar.NotificationShadeDepthController;
import com.android.systemui.statusbar.PulseExpansionHandler;
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
@@ -82,7 +81,7 @@
private final CommandQueue mCommandQueue;
private final NotificationShadeWindowView mView;
private final ShadeController mShadeController;
- private final NotificationShadeWindowBlurController mBlurController;
+ private final NotificationShadeDepthController mDepthController;
private GestureDetector mGestureDetector;
private View mBrightnessMirror;
@@ -126,7 +125,7 @@
CommandQueue commandQueue,
ShadeController shadeController,
DockManager dockManager,
- @Nullable NotificationShadeWindowBlurController blurController,
+ NotificationShadeDepthController depthController,
NotificationShadeWindowView notificationShadeWindowView,
NotificationPanelViewController notificationPanelViewController,
SuperStatusBarViewFactory statusBarViewFactory) {
@@ -149,7 +148,7 @@
mShadeController = shadeController;
mDockManager = dockManager;
mNotificationPanelViewController = notificationPanelViewController;
- mBlurController = blurController;
+ mDepthController = depthController;
mStatusBarViewFactory = statusBarViewFactory;
// This view is not part of the newly inflated expanded status bar.
@@ -394,10 +393,8 @@
mView.getContext(), mView, expandHelperCallback,
dragDownCallback, mFalsingManager));
- if (mBlurController != null) {
- mBlurController.setRoot(mView);
- mNotificationPanelViewController.addExpansionListener(mBlurController);
- }
+ mDepthController.setRoot(mView);
+ mNotificationPanelViewController.addExpansionListener(mDepthController);
}
public NotificationShadeWindowView getView() {
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 1359f74..e25c14c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
@@ -40,6 +40,7 @@
import com.android.systemui.plugins.DarkIconDispatcher;
import com.android.systemui.plugins.DarkIconDispatcher.DarkReceiver;
import com.android.systemui.statusbar.CommandQueue;
+import com.android.systemui.util.leak.RotationUtils;
import java.util.Objects;
@@ -47,7 +48,6 @@
private static final String TAG = "PhoneStatusBarView";
private static final boolean DEBUG = StatusBar.DEBUG;
private static final boolean DEBUG_GESTURES = false;
- private static final int NO_VALUE = Integer.MIN_VALUE;
private final CommandQueue mCommandQueue;
StatusBar mBar;
@@ -64,13 +64,14 @@
}
};
private DarkReceiver mBattery;
- private int mLastOrientation;
+ private int mRotationOrientation;
@Nullable
private View mCenterIconSpace;
@Nullable
private View mCutoutSpace;
@Nullable
private DisplayCutout mDisplayCutout;
+ private int mStatusBarHeight;
/**
* Draw this many pixels into the left/right side of the cutout to optimally use the space
@@ -107,7 +108,7 @@
super.onAttachedToWindow();
// Always have Battery meters in the status bar observe the dark/light modes.
Dependency.get(DarkIconDispatcher.class).addDarkReceiver(mBattery);
- if (updateOrientationAndCutout(getResources().getConfiguration().orientation)) {
+ if (updateOrientationAndCutout()) {
updateLayoutForCutout();
}
}
@@ -124,7 +125,7 @@
super.onConfigurationChanged(newConfig);
// May trigger cutout space layout-ing
- if (updateOrientationAndCutout(newConfig.orientation)) {
+ if (updateOrientationAndCutout()) {
updateLayoutForCutout();
requestLayout();
}
@@ -132,7 +133,7 @@
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
- if (updateOrientationAndCutout(mLastOrientation)) {
+ if (updateOrientationAndCutout()) {
updateLayoutForCutout();
requestLayout();
}
@@ -140,17 +141,14 @@
}
/**
- *
- * @param newOrientation may pass NO_VALUE for no change
* @return boolean indicating if we need to update the cutout location / margins
*/
- private boolean updateOrientationAndCutout(int newOrientation) {
+ private boolean updateOrientationAndCutout() {
boolean changed = false;
- if (newOrientation != NO_VALUE) {
- if (mLastOrientation != newOrientation) {
- changed = true;
- mLastOrientation = newOrientation;
- }
+ int newRotation = RotationUtils.getExactRotation(mContext);
+ if (newRotation != mRotationOrientation) {
+ changed = true;
+ mRotationOrientation = newRotation;
}
if (!Objects.equals(getRootWindowInsets().getDisplayCutout(), mDisplayCutout)) {
@@ -293,17 +291,16 @@
final int waterfallTopInset =
mDisplayCutout == null ? 0 : mDisplayCutout.getWaterfallInsets().top;
ViewGroup.LayoutParams layoutParams = getLayoutParams();
- layoutParams.height =
- getResources().getDimensionPixelSize(R.dimen.status_bar_height) - waterfallTopInset;
+ mStatusBarHeight = getResources().getDimensionPixelSize(R.dimen.status_bar_height);
+ layoutParams.height = mStatusBarHeight - waterfallTopInset;
setLayoutParams(layoutParams);
}
private void updateLayoutForCutout() {
updateStatusBarHeight();
- Pair<Integer, Integer> cornerCutoutMargins =
- StatusBarWindowView.cornerCutoutMargins(mDisplayCutout, getDisplay());
- updateCutoutLocation(cornerCutoutMargins);
- updateSafeInsets(cornerCutoutMargins);
+ updateCutoutLocation(StatusBarWindowView.cornerCutoutMargins(mDisplayCutout, getDisplay()));
+ updateSafeInsets(StatusBarWindowView.statusBarCornerCutoutMargins(mDisplayCutout,
+ getDisplay(), mRotationOrientation, mStatusBarHeight));
}
private void updateCutoutLocation(Pair<Integer, Integer> cornerCutoutMargins) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
index 945a9db..c590139 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar.phone;
+import static java.lang.Float.isNaN;
+
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
@@ -45,6 +47,7 @@
import com.android.systemui.R;
import com.android.systemui.colorextraction.SysuiColorExtractor;
import com.android.systemui.dock.DockManager;
+import com.android.systemui.statusbar.BlurUtils;
import com.android.systemui.statusbar.ScrimView;
import com.android.systemui.statusbar.notification.stack.ViewState;
import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -105,21 +108,21 @@
/**
* Default alpha value for most scrims.
*/
- public static final float SCRIM_ALPHA = 0.2f;
+ protected static final float KEYGUARD_SCRIM_ALPHA = 0.2f;
/**
* Scrim opacity when the phone is about to wake-up.
*/
public static final float WAKE_SENSOR_SCRIM_ALPHA = 0.6f;
/**
- * A scrim varies its opacity based on a busyness factor, for example
- * how many notifications are currently visible.
+ * The default scrim under the shade and dialogs.
+ * This should not be lower than 0.54, otherwise we won't pass GAR.
*/
public static final float BUSY_SCRIM_ALPHA = 0.75f;
/**
- * The most common scrim, the one under the keyguard.
+ * Same as above, but when blur is supported.
*/
- protected static final float SCRIM_BEHIND_ALPHA_KEYGUARD = SCRIM_ALPHA;
+ public static final float BLUR_SCRIM_ALPHA = 0.54f;
static final int TAG_KEY_ANIM = R.id.scrim;
private static final int TAG_START_ALPHA = R.id.scrim_alpha_start;
@@ -144,7 +147,8 @@
private GradientColors mColors;
private boolean mNeedsDrawableColorUpdate;
- private float mScrimBehindAlphaKeyguard = SCRIM_BEHIND_ALPHA_KEYGUARD;
+ private float mScrimBehindAlphaKeyguard = KEYGUARD_SCRIM_ALPHA;
+ private final float mDefaultScrimAlpha;
// Assuming the shade is expanded during initialization
private float mExpansionFraction = 1f;
@@ -190,9 +194,11 @@
AlarmManager alarmManager, KeyguardStateController keyguardStateController,
DelayedWakeLock.Builder delayedWakeLockBuilder, Handler handler,
KeyguardUpdateMonitor keyguardUpdateMonitor, SysuiColorExtractor sysuiColorExtractor,
- DockManager dockManager) {
+ DockManager dockManager, BlurUtils blurUtils) {
mScrimStateListener = lightBarController::setScrimState;
+ mDefaultScrimAlpha = blurUtils.supportsBlursOnWindows()
+ ? BLUR_SCRIM_ALPHA : BUSY_SCRIM_ALPHA;
mKeyguardStateController = keyguardStateController;
mDarkenWhileDragging = !mKeyguardStateController.canDismissLockScreen();
@@ -234,6 +240,7 @@
states[i].init(mScrimInFront, mScrimBehind, mScrimForBubble, mDozeParameters,
mDockManager);
states[i].setScrimBehindAlphaKeyguard(mScrimBehindAlphaKeyguard);
+ states[i].setDefaultScrimAlpha(mDefaultScrimAlpha);
}
mScrimBehind.setDefaultFocusHighlightEnabled(false);
@@ -289,6 +296,10 @@
mInFrontAlpha = state.getFrontAlpha();
mBehindAlpha = state.getBehindAlpha();
mBubbleAlpha = state.getBubbleAlpha();
+ if (isNaN(mBehindAlpha) || isNaN(mInFrontAlpha)) {
+ throw new IllegalStateException("Scrim opacity is NaN for state: " + state + ", front: "
+ + mInFrontAlpha + ", back: " + mBehindAlpha);
+ }
applyExpansionToAlpha();
// Scrim might acquire focus when user is navigating with a D-pad or a keyboard.
@@ -416,6 +427,9 @@
* @param fraction From 0 to 1 where 0 means collapsed and 1 expanded.
*/
public void setPanelExpansion(float fraction) {
+ if (isNaN(fraction)) {
+ throw new IllegalArgumentException("Fraction should not be NaN");
+ }
if (mExpansionFraction != fraction) {
mExpansionFraction = fraction;
@@ -474,7 +488,7 @@
// Darken scrim as you pull down the shade when unlocked
float behindFraction = getInterpolatedFraction();
behindFraction = (float) Math.pow(behindFraction, 0.8f);
- mBehindAlpha = behindFraction * BUSY_SCRIM_ALPHA;
+ mBehindAlpha = behindFraction * mDefaultScrimAlpha;
mInFrontAlpha = 0;
} else if (mState == ScrimState.KEYGUARD || mState == ScrimState.PULSING) {
// Either darken of make the scrim transparent when you
@@ -482,7 +496,7 @@
float interpolatedFract = getInterpolatedFraction();
float alphaBehind = mState.getBehindAlpha();
if (mDarkenWhileDragging) {
- mBehindAlpha = MathUtils.lerp(BUSY_SCRIM_ALPHA, alphaBehind,
+ mBehindAlpha = MathUtils.lerp(mDefaultScrimAlpha, alphaBehind,
interpolatedFract);
mInFrontAlpha = mState.getFrontAlpha();
} else {
@@ -493,6 +507,10 @@
mBehindTint = ColorUtils.blendARGB(ScrimState.BOUNCER.getBehindTint(),
mState.getBehindTint(), interpolatedFract);
}
+ if (isNaN(mBehindAlpha) || isNaN(mInFrontAlpha)) {
+ throw new IllegalStateException("Scrim opacity is NaN for state: " + mState
+ + ", front: " + mInFrontAlpha + ", back: " + mBehindAlpha);
+ }
}
/**
@@ -548,6 +566,10 @@
float newBehindAlpha = mState.getBehindAlpha();
if (mBehindAlpha != newBehindAlpha) {
mBehindAlpha = newBehindAlpha;
+ if (isNaN(mBehindAlpha)) {
+ throw new IllegalStateException("Scrim opacity is NaN for state: " + mState
+ + ", back: " + mBehindAlpha);
+ }
updateScrims();
}
}
@@ -948,8 +970,12 @@
pw.print(" tint=0x");
pw.println(Integer.toHexString(mScrimForBubble.getTint()));
- pw.print(" mTracking=");
+ pw.print(" mTracking=");
pw.println(mTracking);
+ pw.print(" mDefaultScrimAlpha=");
+ pw.println(mDefaultScrimAlpha);
+ pw.print(" mExpansionFraction=");
+ pw.println(mExpansionFraction);
}
public void setWallpaperSupportsAmbientMode(boolean wallpaperSupportsAmbientMode) {
@@ -996,6 +1022,10 @@
// in this case, back-scrim needs to be re-evaluated
if (mState == ScrimState.AOD || mState == ScrimState.PULSING) {
float newBehindAlpha = mState.getBehindAlpha();
+ if (isNaN(newBehindAlpha)) {
+ throw new IllegalStateException("Scrim opacity is NaN for state: " + mState
+ + ", back: " + mBehindAlpha);
+ }
if (mBehindAlpha != newBehindAlpha) {
mBehindAlpha = newBehindAlpha;
updateScrims();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
index c23fd0a..ade642c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimState.java
@@ -92,7 +92,7 @@
BOUNCER {
@Override
public void prepare(ScrimState previousState) {
- mBehindAlpha = ScrimController.BUSY_SCRIM_ALPHA;
+ mBehindAlpha = mDefaultScrimAlpha;
mFrontAlpha = 0f;
mBubbleAlpha = 0f;
}
@@ -106,7 +106,7 @@
public void prepare(ScrimState previousState) {
mBehindAlpha = 0;
mBubbleAlpha = 0f;
- mFrontAlpha = ScrimController.BUSY_SCRIM_ALPHA;
+ mFrontAlpha = mDefaultScrimAlpha;
}
},
@@ -233,9 +233,9 @@
mBehindTint = Color.TRANSPARENT;
mBubbleTint = Color.TRANSPARENT;
- mFrontAlpha = ScrimController.TRANSPARENT;
- mBehindAlpha = ScrimController.BUSY_SCRIM_ALPHA;
- mBubbleAlpha = ScrimController.BUSY_SCRIM_ALPHA;
+ mFrontAlpha = 0f;
+ mBehindAlpha = mDefaultScrimAlpha;
+ mBubbleAlpha = mDefaultScrimAlpha;
mAnimationDuration = ScrimController.ANIMATION_DURATION;
mBlankScreen = false;
@@ -255,6 +255,7 @@
float mBubbleAlpha;
float mScrimBehindAlphaKeyguard;
+ float mDefaultScrimAlpha;
ScrimView mScrimInFront;
ScrimView mScrimBehind;
ScrimView mScrimForBubble;
@@ -341,6 +342,10 @@
mScrimBehindAlphaKeyguard = scrimBehindAlphaKeyguard;
}
+ public void setDefaultScrimAlpha(float defaultScrimAlpha) {
+ mDefaultScrimAlpha = defaultScrimAlpha;
+ }
+
public void setWallpaperSupportsAmbientMode(boolean wallpaperSupportsAmbientMode) {
mWallpaperSupportsAmbientMode = wallpaperSupportsAmbientMode;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 3e6e027..d343090 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -185,15 +185,15 @@
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.VibratorHelper;
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
-import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
import com.android.systemui.statusbar.notification.NotificationActivityStarter;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.init.NotificationsController;
+import com.android.systemui.statusbar.notification.interruption.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -404,10 +404,9 @@
private final NotificationGutsManager mGutsManager;
private final NotificationLogger mNotificationLogger;
- private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
private final NotificationViewHierarchyManager mViewHierarchyManager;
private final KeyguardViewMediator mKeyguardViewMediator;
- private final NotificationAlertingManager mNotificationAlertingManager;
+ protected final NotificationInterruptStateProvider mNotificationInterruptStateProvider;
// for disabling the status bar
private int mDisabled1 = 0;
@@ -621,10 +620,10 @@
RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler,
NotificationGutsManager notificationGutsManager,
NotificationLogger notificationLogger,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptStateProvider,
NotificationViewHierarchyManager notificationViewHierarchyManager,
KeyguardViewMediator keyguardViewMediator,
- NotificationAlertingManager notificationAlertingManager,
+ NotificationAlertingManager notificationAlertingManager, // need to inject for now
DisplayMetrics displayMetrics,
MetricsLogger metricsLogger,
@UiBackground Executor uiBgExecutor,
@@ -701,10 +700,9 @@
mRemoteInputQuickSettingsDisabler = remoteInputQuickSettingsDisabler;
mGutsManager = notificationGutsManager;
mNotificationLogger = notificationLogger;
- mNotificationInterruptionStateProvider = notificationInterruptionStateProvider;
+ mNotificationInterruptStateProvider = notificationInterruptStateProvider;
mViewHierarchyManager = notificationViewHierarchyManager;
mKeyguardViewMediator = keyguardViewMediator;
- mNotificationAlertingManager = notificationAlertingManager;
mDisplayMetrics = displayMetrics;
mMetricsLogger = metricsLogger;
mUiBgExecutor = uiBgExecutor;
@@ -1238,9 +1236,9 @@
mPresenter = new StatusBarNotificationPresenter(mContext, mNotificationPanelViewController,
mHeadsUpManager, mNotificationShadeWindowView, mStackScroller, mDozeScrimController,
mScrimController, mActivityLaunchAnimator, mDynamicPrivacyController,
- mNotificationAlertingManager, mKeyguardStateController,
- mKeyguardIndicationController,
- this /* statusBar */, mShadeController, mCommandQueue, mInitController);
+ mKeyguardStateController, mKeyguardIndicationController,
+ this /* statusBar */, mShadeController, mCommandQueue, mInitController,
+ mNotificationInterruptStateProvider);
mNotificationShelf.setOnActivatedListener(mPresenter);
mRemoteInputManager.getController().addCallback(mNotificationShadeWindowController);
@@ -1589,8 +1587,9 @@
}
if ((diff1 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
- mNotificationInterruptionStateProvider.setDisableNotificationAlerts(
- (state1 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0);
+ if (areNotificationAlertsDisabled()) {
+ mHeadsUpManager.releaseAllImmediately();
+ }
}
if ((diff2 & StatusBarManager.DISABLE2_QUICK_SETTINGS) != 0) {
@@ -1605,6 +1604,10 @@
}
}
+ boolean areNotificationAlertsDisabled() {
+ return (mDisabled1 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0;
+ }
+
protected H createHandler() {
return new StatusBar.H();
}
@@ -2332,7 +2335,7 @@
void checkBarModes() {
if (mDemoMode) return;
- if (mNotificationShadeWindowViewController != null) {
+ if (mNotificationShadeWindowViewController != null && getStatusBarTransitions() != null) {
checkBarMode(mStatusBarMode, mStatusBarWindowState, getStatusBarTransitions());
}
mNavigationBarController.checkNavBarModes(mDisplayId);
@@ -2599,7 +2602,7 @@
}
try {
result = ActivityTaskManager.getService().startActivityAsUser(
- null, mContext.getBasePackageName(), mContext.getFeatureId(),
+ null, mContext.getBasePackageName(), mContext.getAttributionTag(),
intent,
intent.resolveTypeIfNeeded(mContext.getContentResolver()),
null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index 0644a42..31db8eb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -42,6 +42,7 @@
import com.android.internal.widget.LockPatternUtils;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.keyguard.KeyguardUpdateMonitorCallback;
+import com.android.keyguard.KeyguardViewController;
import com.android.keyguard.ViewMediatorCallback;
import com.android.settingslib.animation.AppearAnimationUtils;
import com.android.systemui.DejankUtils;
@@ -77,7 +78,8 @@
@Singleton
public class StatusBarKeyguardViewManager implements RemoteInputController.Callback,
StatusBarStateController.StateListener, ConfigurationController.ConfigurationListener,
- PanelExpansionListener, NavigationModeController.ModeChangedListener {
+ PanelExpansionListener, NavigationModeController.ModeChangedListener,
+ KeyguardViewController {
// When hiding the Keyguard with timing supplied from WindowManager, better be early than late.
private static final long HIDE_TIMING_CORRECTION_MS = - 16 * 3;
@@ -221,6 +223,7 @@
mDockManager = dockManager;
}
+ @Override
public void registerStatusBar(StatusBar statusBar,
ViewGroup container,
NotificationPanelViewController notificationPanelViewController,
@@ -326,6 +329,7 @@
* Show the keyguard. Will handle creating and attaching to the view manager
* lazily.
*/
+ @Override
public void show(Bundle options) {
mShowing = true;
mNotificationShadeWindowController.setKeyguardShowing(true);
@@ -430,9 +434,7 @@
mAfterKeyguardGoneRunnables.add(runnable);
}
- /**
- * Reset the state of the view.
- */
+ @Override
public void reset(boolean hideBouncerWhenShowing) {
if (mShowing) {
if (mOccluded && !mDozing) {
@@ -452,23 +454,28 @@
return mGoingToSleepVisibleNotOccluded;
}
+ @Override
public void onStartedGoingToSleep() {
mGoingToSleepVisibleNotOccluded = isShowing() && !isOccluded();
}
+ @Override
public void onFinishedGoingToSleep() {
mGoingToSleepVisibleNotOccluded = false;
mBouncer.onScreenTurnedOff();
}
+ @Override
public void onStartedWakingUp() {
// TODO: remove
}
+ @Override
public void onScreenTurningOn() {
// TODO: remove
}
+ @Override
public void onScreenTurnedOn() {
// TODO: remove
}
@@ -503,14 +510,17 @@
}
}
+ @Override
public void setNeedsInput(boolean needsInput) {
mNotificationShadeWindowController.setKeyguardNeedsInput(needsInput);
}
+ @Override
public boolean isUnlockWithWallpaper() {
return mNotificationShadeWindowController.isShowingWallpaper();
}
+ @Override
public void setOccluded(boolean occluded, boolean animate) {
mStatusBar.setOccluded(occluded);
if (occluded && !mOccluded && mShowing) {
@@ -554,13 +564,7 @@
return mOccluded;
}
- /**
- * Starts the animation before we dismiss Keyguard, i.e. an disappearing animation on the
- * security view of the bouncer.
- *
- * @param finishRunnable the runnable to be run after the animation finished, or {@code null} if
- * no action should be run
- */
+ @Override
public void startPreHideAnimation(Runnable finishRunnable) {
if (mBouncer.isShowing()) {
mBouncer.startPreHideAnimation(finishRunnable);
@@ -572,9 +576,7 @@
updateLockIcon();
}
- /**
- * Hides the keyguard view
- */
+ @Override
public void hide(long startTime, long fadeoutDuration) {
mShowing = false;
mKeyguardStateController.notifyKeyguardState(mShowing,
@@ -728,9 +730,7 @@
mAfterKeyguardGoneRunnables.clear();
}
- /**
- * Dismisses the keyguard by going to the next screen or making it gone.
- */
+ @Override
public void dismissAndCollapse() {
mStatusBar.executeRunnableDismissingKeyguard(null, null, true, false, true);
}
@@ -742,9 +742,7 @@
return mBouncer.isSecure();
}
- /**
- * @return Whether the keyguard is showing
- */
+ @Override
public boolean isShowing() {
return mShowing;
}
@@ -921,18 +919,17 @@
mViewMediatorCallback.readyForKeyguardDone();
}
+ @Override
public boolean shouldDisableWindowAnimationsForUnlock() {
return mStatusBar.isInLaunchTransition();
}
-
- /**
- * @return Whether subtle animation should be used for unlocking the device.
- */
+ @Override
public boolean shouldSubtleWindowAnimationsForUnlock() {
return needsBypassFading();
}
+ @Override
public boolean isGoingToNotificationShade() {
return mStatusBarStateController.leaveOpenOnKeyguardHide();
}
@@ -941,13 +938,12 @@
return mBouncer.isSecure() || mLockPatternUtils.isSecure(userId);
}
+ @Override
public void keyguardGoingAway() {
mStatusBar.keyguardGoingAway();
}
- /**
- * Called when cancel button in bouncer is pressed.
- */
+ @Override
public void onCancelClicked() {
// No-op
}
@@ -964,6 +960,7 @@
mBouncer.showMessage(message, colorState);
}
+ @Override
public ViewRootImpl getViewRootImpl() {
return mStatusBar.getStatusBarView().getViewRootImpl();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
index e1a20b6..53fa263 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java
@@ -68,12 +68,12 @@
import com.android.systemui.statusbar.notification.NotificationActivityStarter;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.notifcollection.DismissedByUserStats;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.policy.HeadsUpUtil;
@@ -108,7 +108,7 @@
private final NotifCollection mNotifCollection;
private final FeatureFlags mFeatureFlags;
private final StatusBarStateController mStatusBarStateController;
- private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+ private final NotificationInterruptStateProvider mNotificationInterruptStateProvider;
private final MetricsLogger mMetricsLogger;
private final Context mContext;
private final NotificationPanelViewController mNotificationPanel;
@@ -142,7 +142,7 @@
NotificationLockscreenUserManager lockscreenUserManager,
ShadeController shadeController, StatusBar statusBar,
KeyguardStateController keyguardStateController,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptStateProvider,
MetricsLogger metricsLogger, LockPatternUtils lockPatternUtils,
Handler mainThreadHandler, Handler backgroundHandler, Executor uiBgExecutor,
ActivityIntentHelper activityIntentHelper, BubbleController bubbleController,
@@ -167,7 +167,7 @@
mActivityStarter = activityStarter;
mEntryManager = entryManager;
mStatusBarStateController = statusBarStateController;
- mNotificationInterruptionStateProvider = notificationInterruptionStateProvider;
+ mNotificationInterruptStateProvider = notificationInterruptStateProvider;
mMetricsLogger = metricsLogger;
mAssistManagerLazy = assistManagerLazy;
mGroupManager = groupManager;
@@ -436,7 +436,7 @@
}
private void handleFullScreenIntent(NotificationEntry entry) {
- if (mNotificationInterruptionStateProvider.shouldLaunchFullScreenIntentWhenAdded(entry)) {
+ if (mNotificationInterruptStateProvider.shouldLaunchFullScreenIntentWhenAdded(entry)) {
if (shouldSuppressFullScreenIntent(entry)) {
if (DEBUG) {
Log.d(TAG, "No Fullscreen intent: suppressed by DND: " + entry.getKey());
@@ -603,7 +603,7 @@
private final ActivityIntentHelper mActivityIntentHelper;
private final BubbleController mBubbleController;
private NotificationPanelViewController mNotificationPanelViewController;
- private NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+ private NotificationInterruptStateProvider mNotificationInterruptStateProvider;
private final ShadeController mShadeController;
private NotificationPresenter mNotificationPresenter;
private ActivityLaunchAnimator mActivityLaunchAnimator;
@@ -626,7 +626,7 @@
NotificationGroupManager groupManager,
NotificationLockscreenUserManager lockscreenUserManager,
KeyguardStateController keyguardStateController,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptStateProvider,
MetricsLogger metricsLogger,
LockPatternUtils lockPatternUtils,
@Main Handler mainThreadHandler,
@@ -654,7 +654,7 @@
mGroupManager = groupManager;
mLockscreenUserManager = lockscreenUserManager;
mKeyguardStateController = keyguardStateController;
- mNotificationInterruptionStateProvider = notificationInterruptionStateProvider;
+ mNotificationInterruptStateProvider = notificationInterruptStateProvider;
mMetricsLogger = metricsLogger;
mLockPatternUtils = lockPatternUtils;
mMainThreadHandler = mainThreadHandler;
@@ -712,7 +712,7 @@
mShadeController,
mStatusBar,
mKeyguardStateController,
- mNotificationInterruptionStateProvider,
+ mNotificationInterruptStateProvider,
mMetricsLogger,
mLockPatternUtils,
mMainThreadHandler,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
index 30d6b507..79cea91 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenter.java
@@ -60,13 +60,13 @@
import com.android.systemui.statusbar.notification.AboveShelfObserver;
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.inflation.NotificationRowBinderImpl;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptSuppressor;
import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
@@ -98,8 +98,6 @@
(SysuiStatusBarStateController) Dependency.get(StatusBarStateController.class);
private final NotificationEntryManager mEntryManager =
Dependency.get(NotificationEntryManager.class);
- private final NotificationInterruptionStateProvider mNotificationInterruptionStateProvider =
- Dependency.get(NotificationInterruptionStateProvider.class);
private final NotificationMediaManager mMediaManager =
Dependency.get(NotificationMediaManager.class);
private final VisualStabilityManager mVisualStabilityManager =
@@ -140,13 +138,13 @@
ScrimController scrimController,
ActivityLaunchAnimator activityLaunchAnimator,
DynamicPrivacyController dynamicPrivacyController,
- NotificationAlertingManager notificationAlertingManager,
KeyguardStateController keyguardStateController,
KeyguardIndicationController keyguardIndicationController,
StatusBar statusBar,
ShadeController shadeController,
CommandQueue commandQueue,
- InitController initController) {
+ InitController initController,
+ NotificationInterruptStateProvider notificationInterruptStateProvider) {
mContext = context;
mKeyguardStateController = keyguardStateController;
mNotificationPanel = panel;
@@ -216,8 +214,7 @@
mEntryManager.addNotificationLifetimeExtender(mGutsManager);
mEntryManager.addNotificationLifetimeExtenders(
remoteInputManager.getLifetimeExtenders());
- mNotificationInterruptionStateProvider.setUpWithPresenter(
- this, mHeadsUpManager, this::canHeadsUp);
+ notificationInterruptStateProvider.addSuppressor(mInterruptSuppressor);
mLockscreenUserManager.setUpWithPresenter(this);
mMediaManager.setUpWithPresenter(this);
mVisualStabilityManager.setUpWithPresenter(this);
@@ -336,39 +333,6 @@
return mEntryManager.hasActiveNotifications();
}
- public boolean canHeadsUp(NotificationEntry entry, StatusBarNotification sbn) {
- if (mStatusBar.isOccluded()) {
- boolean devicePublic = mLockscreenUserManager.
- isLockscreenPublicMode(mLockscreenUserManager.getCurrentUserId());
- boolean userPublic = devicePublic
- || mLockscreenUserManager.isLockscreenPublicMode(sbn.getUserId());
- boolean needsRedaction = mLockscreenUserManager.needsRedaction(entry);
- if (userPublic && needsRedaction) {
- // TODO(b/135046837): we can probably relax this with dynamic privacy
- return false;
- }
- }
-
- if (!mCommandQueue.panelsEnabled()) {
- if (DEBUG) {
- Log.d(TAG, "No heads up: disabled panel : " + sbn.getKey());
- }
- return false;
- }
-
- if (sbn.getNotification().fullScreenIntent != null) {
- if (mAccessibilityManager.isTouchExplorationEnabled()) {
- if (DEBUG) Log.d(TAG, "No heads up: accessible fullscreen: " + sbn.getKey());
- return false;
- } else {
- // we only allow head-up on the lockscreen if it doesn't have a fullscreen intent
- return !mKeyguardStateController.isShowing()
- || mStatusBar.isOccluded();
- }
- }
- return true;
- }
-
@Override
public void onUserSwitched(int newUserId) {
// Begin old BaseStatusBar.userSwitched
@@ -507,4 +471,66 @@
}
}
};
+
+ private final NotificationInterruptSuppressor mInterruptSuppressor =
+ new NotificationInterruptSuppressor() {
+ @Override
+ public String getName() {
+ return TAG;
+ }
+
+ @Override
+ public boolean suppressAwakeHeadsUp(NotificationEntry entry) {
+ final StatusBarNotification sbn = entry.getSbn();
+ if (mStatusBar.isOccluded()) {
+ boolean devicePublic = mLockscreenUserManager
+ .isLockscreenPublicMode(mLockscreenUserManager.getCurrentUserId());
+ boolean userPublic = devicePublic
+ || mLockscreenUserManager.isLockscreenPublicMode(sbn.getUserId());
+ boolean needsRedaction = mLockscreenUserManager.needsRedaction(entry);
+ if (userPublic && needsRedaction) {
+ // TODO(b/135046837): we can probably relax this with dynamic privacy
+ return true;
+ }
+ }
+
+ if (!mCommandQueue.panelsEnabled()) {
+ if (DEBUG) {
+ Log.d(TAG, "No heads up: disabled panel : " + sbn.getKey());
+ }
+ return true;
+ }
+
+ if (sbn.getNotification().fullScreenIntent != null) {
+ // we don't allow head-up on the lockscreen (unless there's a
+ // "showWhenLocked" activity currently showing) if
+ // the potential HUN has a fullscreen intent
+ if (mKeyguardStateController.isShowing() && !mStatusBar.isOccluded()) {
+ if (DEBUG) {
+ Log.d(TAG, "No heads up: entry has fullscreen intent on lockscreen "
+ + sbn.getKey());
+ }
+ return true;
+ }
+
+ if (mAccessibilityManager.isTouchExplorationEnabled()) {
+ if (DEBUG) {
+ Log.d(TAG, "No heads up: accessible fullscreen: " + sbn.getKey());
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public boolean suppressAwakeInterruptions(NotificationEntry entry) {
+ return isDeviceInVrMode();
+ }
+
+ @Override
+ public boolean suppressInterruptions(NotificationEntry entry) {
+ return mStatusBar.areNotificationAlertsDisabled();
+ }
+ };
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
index 22bf513..760a6d6 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowView.java
@@ -33,6 +33,8 @@
import android.view.WindowInsets;
import android.widget.FrameLayout;
+import com.android.systemui.util.leak.RotationUtils;
+
/**
* Status bar view.
*/
@@ -52,17 +54,13 @@
@Override
public WindowInsets onApplyWindowInsets(WindowInsets windowInsets) {
final Insets insets = windowInsets.getInsetsIgnoringVisibility(systemBars());
- mLeftInset = 0;
- mRightInset = 0;
+ mLeftInset = insets.left;
+ mRightInset = insets.right;
mTopInset = 0;
DisplayCutout displayCutout = getRootWindowInsets().getDisplayCutout();
if (displayCutout != null) {
mTopInset = displayCutout.getWaterfallInsets().top;
- mLeftInset = displayCutout.getSafeInsetLeft();
- mRightInset = displayCutout.getSafeInsetRight();
}
- mLeftInset = Math.max(insets.left, mLeftInset);
- mRightInset = Math.max(insets.right, mRightInset);
applyMargins();
return windowInsets;
}
@@ -100,44 +98,33 @@
return new Pair<>(roundedCornerContentPadding, roundedCornerContentPadding);
}
- // compute the padding needed for corner cutout.
- final int leftMargin = cutout.getSafeInsetLeft();
- final int rightMargin = cutout.getSafeInsetRight();
+ // padding needed for corner cutout.
int leftCornerCutoutPadding = 0;
int rightCornerCutoutPadding = 0;
if (cornerCutoutPadding != null) {
- if (cornerCutoutPadding.first > leftMargin) {
- leftCornerCutoutPadding = cornerCutoutPadding.first - leftMargin;
- }
- if (cornerCutoutPadding.second > rightMargin) {
- rightCornerCutoutPadding = cornerCutoutPadding.second - rightMargin;
- }
- }
-
- // compute the padding needed for rounded corner
- int leftRoundedCornerPadding = 0;
- int rightRoundedCornerPadding = 0;
- if (roundedCornerContentPadding > leftMargin) {
- leftRoundedCornerPadding = roundedCornerContentPadding - leftMargin;
- }
- if (roundedCornerContentPadding > rightMargin) {
- rightRoundedCornerPadding = roundedCornerContentPadding - rightMargin;
+ leftCornerCutoutPadding = cornerCutoutPadding.first;
+ rightCornerCutoutPadding = cornerCutoutPadding.second;
}
return new Pair<>(
- Math.max(leftCornerCutoutPadding, leftRoundedCornerPadding),
- Math.max(rightCornerCutoutPadding, rightRoundedCornerPadding));
+ Math.max(leftCornerCutoutPadding, roundedCornerContentPadding),
+ Math.max(rightCornerCutoutPadding, roundedCornerContentPadding));
}
+
/**
- * Compute the corner cutout margins
- *
- * @param cutout
- * @param display
- * @return
+ * Compute the corner cutout margins in portrait mode
*/
public static Pair<Integer, Integer> cornerCutoutMargins(DisplayCutout cutout,
Display display) {
+ return statusBarCornerCutoutMargins(cutout, display, RotationUtils.ROTATION_NONE, 0);
+ }
+
+ /**
+ * Compute the corner cutout margins in the given orientation (exactRotation)
+ */
+ public static Pair<Integer, Integer> statusBarCornerCutoutMargins(DisplayCutout cutout,
+ Display display, int exactRotation, int statusBarHeight) {
if (cutout == null) {
return null;
}
@@ -145,14 +132,33 @@
display.getRealSize(size);
Rect bounds = new Rect();
- boundsFromDirection(cutout, Gravity.TOP, bounds);
+ switch (exactRotation) {
+ case RotationUtils.ROTATION_LANDSCAPE:
+ boundsFromDirection(cutout, Gravity.LEFT, bounds);
+ break;
+ case RotationUtils.ROTATION_SEASCAPE:
+ boundsFromDirection(cutout, Gravity.RIGHT, bounds);
+ break;
+ case RotationUtils.ROTATION_NONE:
+ boundsFromDirection(cutout, Gravity.TOP, bounds);
+ break;
+ case RotationUtils.ROTATION_UPSIDE_DOWN:
+ // we assume the cutout is always on top in portrait mode
+ return null;
+ }
+
+ if (statusBarHeight >= 0 && bounds.top > statusBarHeight) {
+ return null;
+ }
if (bounds.left <= 0) {
return new Pair<>(bounds.right, 0);
}
+
if (bounds.right >= size.x) {
return new Pair<>(0, size.x - bounds.left);
}
+
return null;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarPhoneModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarPhoneModule.java
index eec8d50..bbc7e7a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarPhoneModule.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarPhoneModule.java
@@ -56,13 +56,13 @@
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.VibratorHelper;
-import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.init.NotificationsController;
+import com.android.systemui.statusbar.notification.interruption.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.phone.AutoHideController;
@@ -139,7 +139,7 @@
RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler,
NotificationGutsManager notificationGutsManager,
NotificationLogger notificationLogger,
- NotificationInterruptionStateProvider notificationInterruptionStateProvider,
+ NotificationInterruptStateProvider notificationInterruptStateProvider,
NotificationViewHierarchyManager notificationViewHierarchyManager,
KeyguardViewMediator keyguardViewMediator,
NotificationAlertingManager notificationAlertingManager,
@@ -218,7 +218,7 @@
remoteInputQuickSettingsDisabler,
notificationGutsManager,
notificationLogger,
- notificationInterruptionStateProvider,
+ notificationInterruptStateProvider,
notificationViewHierarchyManager,
keyguardViewMediator,
notificationAlertingManager,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
index cf9d8e1..24b9685 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryController.java
@@ -53,6 +53,12 @@
boolean isAodPowerSave();
/**
+ * Set reverse state.
+ * @param isReverse true if turn on reverse, false otherwise
+ */
+ default void setReverseState(boolean isReverse) {}
+
+ /**
* A listener that will be notified whenever a change in battery level or power save mode has
* occurred.
*/
@@ -63,6 +69,9 @@
default void onPowerSaveChanged(boolean isPowerSave) {
}
+
+ default void onReverseChanged(boolean isReverse, int level, String name) {
+ }
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
index d3e6f53..496bf68 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
@@ -59,13 +59,13 @@
private final EnhancedEstimates mEstimates;
private final BroadcastDispatcher mBroadcastDispatcher;
- private final ArrayList<BatteryController.BatteryStateChangeCallback>
+ protected final ArrayList<BatteryController.BatteryStateChangeCallback>
mChangeCallbacks = new ArrayList<>();
private final ArrayList<EstimateFetchCompletion> mFetchCallbacks = new ArrayList<>();
private final PowerManager mPowerManager;
private final Handler mMainHandler;
private final Handler mBgHandler;
- private final Context mContext;
+ protected final Context mContext;
private int mLevel;
private boolean mPluggedIn;
@@ -80,7 +80,7 @@
@VisibleForTesting
@Inject
- BatteryControllerImpl(Context context, EnhancedEstimates enhancedEstimates,
+ protected BatteryControllerImpl(Context context, EnhancedEstimates enhancedEstimates,
PowerManager powerManager, BroadcastDispatcher broadcastDispatcher,
@Main Handler mainHandler, @Background Handler bgHandler) {
mContext = context;
@@ -99,7 +99,6 @@
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
- filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING);
filter.addAction(ACTION_LEVEL_TEST);
mBroadcastDispatcher.registerReceiver(this, filter);
}
@@ -155,8 +154,6 @@
fireBatteryLevelChanged();
} else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)) {
updatePowerSave();
- } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING)) {
- setPowerSave(intent.getBooleanExtra(PowerManager.EXTRA_POWER_SAVE_MODE, false));
} else if (action.equals(ACTION_LEVEL_TEST)) {
mTestmode = true;
mMainHandler.post(new Runnable() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
index 759bad4..812ce1c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
@@ -236,7 +236,7 @@
String action = intent.getAction();
if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
- String tz = intent.getStringExtra("time-zone");
+ String tz = intent.getStringExtra(Intent.EXTRA_TIMEZONE);
handler.post(() -> {
mCalendar = Calendar.getInstance(TimeZone.getTimeZone(tz));
if (mClockFormat != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
index a3e2e76..7280a88 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceProvisionedControllerImpl.java
@@ -59,7 +59,7 @@
mUserSetupUri = Secure.getUriFor(Secure.USER_SETUP_COMPLETE);
mSettingsObserver = new ContentObserver(mainHandler) {
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, Uri uri, int flags) {
Log.d(TAG, "Setting change: " + uri);
if (mUserSetupUri.equals(uri)) {
notifySetupChanged();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
index cebcf76..54e8e72 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
@@ -577,7 +577,7 @@
}
boolean isDataDisabled() {
- return !mPhone.isDataConnectionEnabled();
+ return !mPhone.isDataConnectionAllowed();
}
@VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
index b84208c..99709402 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
@@ -630,7 +630,7 @@
@VisibleForTesting
void doUpdateMobileControllers() {
List<SubscriptionInfo> subscriptions = mSubscriptionManager
- .getActiveAndHiddenSubscriptionInfoList();
+ .getCompleteActiveSubscriptionInfoList();
if (subscriptions == null) {
subscriptions = Collections.emptyList();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
index 74739e1..e70e30a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tv/AudioRecordingDisclosureBar.java
@@ -24,6 +24,7 @@
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.IntDef;
+import android.annotation.UiThread;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
@@ -43,7 +44,6 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
-import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
@@ -98,8 +98,27 @@
private TextView mTextView;
@State private int mState = STATE_NOT_SHOWN;
- private final Set<String> mAudioRecordingApps = new HashSet<>();
- private final Queue<String> mPendingNotifications = new LinkedList<>();
+ /**
+ * Set of the applications that currently are conducting audio recording.
+ */
+ private final Set<String> mActiveAudioRecordingPackages = new ArraySet<>();
+ /**
+ * Set of applications that we've notified the user about since the indicator came up. Meaning
+ * that if an application is in this list then at some point since the indicator came up, it
+ * was expanded showing this application's title.
+ * Used not to notify the user about the same application again while the indicator is shown.
+ * We empty this set every time the indicator goes off the screen (we always call {@code
+ * mSessionNotifiedPackages.clear()} before calling {@link #hide()}).
+ */
+ private final Set<String> mSessionNotifiedPackages = new ArraySet<>();
+ /**
+ * If an application starts recording while the TV indicator is neither in {@link
+ * #STATE_NOT_SHOWN} nor in {@link #STATE_MINIMIZED}, then we add the application's package
+ * name to the queue, from which we take packages names one by one to disclose the
+ * corresponding applications' titles to the user, whenever the indicator eventually comes to
+ * one of the two aforementioned states.
+ */
+ private final Queue<String> mPendingNotificationPackages = new LinkedList<>();
AudioRecordingDisclosureBar(Context context) {
mContext = context;
@@ -115,11 +134,16 @@
new OnActiveRecordingListener());
}
+ @UiThread
private void onStartedRecording(String packageName) {
- if (!mAudioRecordingApps.add(packageName)) {
+ if (!mActiveAudioRecordingPackages.add(packageName)) {
// This app is already known to perform recording
return;
}
+ if (!mSessionNotifiedPackages.add(packageName)) {
+ // We've already notified user about this app, no need to do it again.
+ return;
+ }
switch (mState) {
case STATE_NOT_SHOWN:
@@ -137,13 +161,14 @@
case STATE_MINIMIZING:
// Currently animating or expanded. Thus add to the pending notifications, and it
// will be picked up once the indicator comes to the STATE_MINIMIZED.
- mPendingNotifications.add(packageName);
+ mPendingNotificationPackages.add(packageName);
break;
}
}
+ @UiThread
private void onDoneRecording(String packageName) {
- if (!mAudioRecordingApps.remove(packageName)) {
+ if (!mActiveAudioRecordingPackages.remove(packageName)) {
// Was not marked as an active recorder, do nothing
return;
}
@@ -151,11 +176,13 @@
// If not MINIMIZED, will check whether the indicator should be hidden when the indicator
// comes to the STATE_MINIMIZED eventually. If is in the STATE_MINIMIZED, but there are
// other active recorders - simply ignore.
- if (mState == STATE_MINIMIZED && mAudioRecordingApps.isEmpty()) {
+ if (mState == STATE_MINIMIZED && mActiveAudioRecordingPackages.isEmpty()) {
+ mSessionNotifiedPackages.clear();
hide();
}
}
+ @UiThread
private void show(String packageName) {
// Inflate the indicator view
mIndicatorView = LayoutInflater.from(mContext).inflate(
@@ -230,6 +257,7 @@
mState = STATE_APPEARING;
}
+ @UiThread
private void expand(String packageName) {
final String label = getApplicationLabel(packageName);
mTextView.setText(mContext.getString(R.string.app_accessed_mic, label));
@@ -253,6 +281,7 @@
mState = STATE_MAXIMIZING;
}
+ @UiThread
private void minimize() {
final int targetOffset = mTextsContainers.getWidth();
final AnimatorSet set = new AnimatorSet();
@@ -274,6 +303,7 @@
mState = STATE_MINIMIZING;
}
+ @UiThread
private void hide() {
final int targetOffset =
mIndicatorView.getWidth() - (int) mIconTextsContainer.getTranslationX();
@@ -294,24 +324,28 @@
mState = STATE_DISAPPEARING;
}
+ @UiThread
private void onExpanded() {
mState = STATE_SHOWN;
mIndicatorView.postDelayed(this::minimize, MAXIMIZED_DURATION);
}
+ @UiThread
private void onMinimized() {
mState = STATE_MINIMIZED;
- if (!mPendingNotifications.isEmpty()) {
+ if (!mPendingNotificationPackages.isEmpty()) {
// There is a new application that started recording, tell the user about it.
- expand(mPendingNotifications.poll());
- } else if (mAudioRecordingApps.isEmpty()) {
- // Nobody is recording anymore, remove the indicator.
+ expand(mPendingNotificationPackages.poll());
+ } else if (mActiveAudioRecordingPackages.isEmpty()) {
+ // Nobody is recording anymore, clear state and remove the indicator.
+ mSessionNotifiedPackages.clear();
hide();
}
}
+ @UiThread
private void onHidden() {
final WindowManager windowManager = (WindowManager) mContext.getSystemService(
Context.WINDOW_SERVICE);
@@ -326,8 +360,15 @@
mBgRight = null;
mState = STATE_NOT_SHOWN;
+
+ // Check if anybody started recording while we were in STATE_DISAPPEARING
+ if (!mPendingNotificationPackages.isEmpty()) {
+ // There is a new application that started recording, tell the user about it.
+ show(mPendingNotificationPackages.poll());
+ }
}
+ @UiThread
private void startPulsatingAnimation() {
final View pulsatingView = mIconTextsContainer.findViewById(R.id.pulsating_circle);
final ObjectAnimator animator =
diff --git a/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java b/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java
index 31b9952..f31f8eb 100644
--- a/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java
+++ b/packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java
@@ -43,6 +43,7 @@
import org.json.JSONException;
import org.json.JSONObject;
+import java.util.Collection;
import java.util.Map;
import java.util.Set;
@@ -99,8 +100,10 @@
Settings.Secure.getUriFor(Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES),
false,
new ContentObserver(mBgHandler) {
+
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
+ int userId) {
if (DEBUG) Log.d(TAG, "Overlay changed for user: " + userId);
if (ActivityManager.getCurrentUser() == userId) {
updateThemeOverlays();
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerServiceImpl.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerServiceImpl.java
index 142fdc2..248bdc8 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerServiceImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerServiceImpl.java
@@ -41,9 +41,9 @@
import com.android.systemui.statusbar.phone.StatusBarIconController;
import com.android.systemui.util.leak.LeakDetector;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -69,7 +69,8 @@
// Map of Uris we listen on to their settings keys.
private final ArrayMap<Uri, String> mListeningUris = new ArrayMap<>();
// Map of settings keys to the listener.
- private final HashMap<String, Set<Tunable>> mTunableLookup = new HashMap<>();
+ private final ConcurrentHashMap<String, Set<Tunable>> mTunableLookup =
+ new ConcurrentHashMap<>();
// Set of all tunables, used for leak detection.
private final HashSet<Tunable> mTunables = LeakDetector.ENABLED ? new HashSet<>() : null;
private final Context mContext;
@@ -262,10 +263,14 @@
}
@Override
- public void onChange(boolean selfChange, Uri uri, int userId) {
+ public void onChange(boolean selfChange, java.util.Collection<Uri> uris,
+ int flags, int userId) {
if (userId == ActivityManager.getCurrentUser()) {
- reloadSetting(uri);
+ for (Uri u : uris) {
+ reloadSetting(u);
+ }
}
}
+
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/util/DismissCircleView.java b/packages/SystemUI/src/com/android/systemui/util/DismissCircleView.java
new file mode 100644
index 0000000..6c3538c
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/util/DismissCircleView.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2020 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.util;
+
+import android.content.Context;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.view.Gravity;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+
+import com.android.systemui.R;
+
+/**
+ * Circular view with a semitransparent, circular background with an 'X' inside it.
+ *
+ * This is used by both Bubbles and PIP as the dismiss target.
+ */
+public class DismissCircleView extends FrameLayout {
+
+ private final ImageView mIconView = new ImageView(getContext());
+
+ public DismissCircleView(Context context) {
+ super(context);
+ final Resources res = getResources();
+
+ setBackground(res.getDrawable(R.drawable.dismiss_circle_background));
+
+ mIconView.setImageDrawable(res.getDrawable(R.drawable.dismiss_target_x));
+ addView(mIconView);
+
+ setViewSizes();
+ }
+
+ @Override
+ protected void onConfigurationChanged(Configuration newConfig) {
+ super.onConfigurationChanged(newConfig);
+ setViewSizes();
+ }
+
+ /** Retrieves the current dimensions for the icon and circle and applies them. */
+ private void setViewSizes() {
+ final Resources res = getResources();
+ final int iconSize = res.getDimensionPixelSize(R.dimen.dismiss_target_x_size);
+ mIconView.setLayoutParams(
+ new FrameLayout.LayoutParams(iconSize, iconSize, Gravity.CENTER));
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/util/magnetictarget/MagnetizedObject.kt b/packages/SystemUI/src/com/android/systemui/util/magnetictarget/MagnetizedObject.kt
index 2276ba1..812a1e4 100644
--- a/packages/SystemUI/src/com/android/systemui/util/magnetictarget/MagnetizedObject.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/magnetictarget/MagnetizedObject.kt
@@ -358,7 +358,7 @@
targetObjectIsStuckTo = targetObjectIsInMagneticFieldOf
cancelAnimations()
magnetListener.onStuckToTarget(targetObjectIsInMagneticFieldOf!!)
- animateStuckToTarget(targetObjectIsInMagneticFieldOf!!, velX, velY, false)
+ animateStuckToTarget(targetObjectIsInMagneticFieldOf, velX, velY, false)
vibrateIfEnabled(VibrationEffect.EFFECT_HEAVY_CLICK)
} else if (targetObjectIsInMagneticFieldOf == null && objectStuckToTarget) {
diff --git a/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java b/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java
index 13ba1a3c..378dde2 100644
--- a/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java
+++ b/packages/SystemUI/src/com/android/systemui/util/sensors/ProximitySensor.java
@@ -170,7 +170,11 @@
return false;
}
- mListeners.add(listener);
+ if (mListeners.contains(listener)) {
+ Log.d(TAG, "ProxListener registered multiple times: " + listener);
+ } else {
+ mListeners.add(listener);
+ }
registerInternal();
return true;
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index af218c49..ce032e2 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -65,7 +65,6 @@
import android.util.Slog;
import android.util.SparseBooleanArray;
import android.view.ContextThemeWrapper;
-import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.AccessibilityDelegate;
@@ -224,7 +223,7 @@
lp.format = PixelFormat.TRANSLUCENT;
lp.setTitle(VolumeDialogImpl.class.getSimpleName());
lp.windowAnimations = -1;
- lp.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
+ lp.gravity = mContext.getResources().getInteger(R.integer.volume_dialog_gravity);
mWindow.setAttributes(lp);
mWindow.setLayout(WRAP_CONTENT, WRAP_CONTENT);
@@ -825,7 +824,7 @@
}
protected void updateRingerH() {
- if (mState != null) {
+ if (mRinger != null && mState != null) {
final StreamState ss = mState.states.get(AudioManager.STREAM_RING);
if (ss == null) {
return;
diff --git a/packages/SystemUI/src/com/android/systemui/wm/DisplayImeController.java b/packages/SystemUI/src/com/android/systemui/wm/DisplayImeController.java
index 2f1b160..5411839 100644
--- a/packages/SystemUI/src/com/android/systemui/wm/DisplayImeController.java
+++ b/packages/SystemUI/src/com/android/systemui/wm/DisplayImeController.java
@@ -49,6 +49,8 @@
public class DisplayImeController implements DisplayController.OnDisplaysChangedListener {
private static final String TAG = "DisplayImeController";
+ private static final boolean DEBUG = false;
+
public static final int ANIMATION_DURATION_SHOW_MS = 275;
public static final int ANIMATION_DURATION_HIDE_MS = 340;
public static final Interpolator INTERPOLATOR = new PathInterpolator(0.4f, 0f, 0.2f, 1f);
@@ -209,6 +211,7 @@
if ((types & WindowInsets.Type.ime()) == 0) {
return;
}
+ if (DEBUG) Slog.d(TAG, "Got showInsets for ime");
startAnimation(true /* show */);
}
@@ -217,6 +220,7 @@
if ((types & WindowInsets.Type.ime()) == 0) {
return;
}
+ if (DEBUG) Slog.d(TAG, "Got hideInsets for ime");
startAnimation(false /* show */);
}
@@ -241,6 +245,11 @@
return;
}
mHandler.post(() -> {
+ if (DEBUG) {
+ Slog.d(TAG, "Run startAnim show:" + show + " was:"
+ + (mAnimationDirection == DIRECTION_SHOW ? "SHOW"
+ : (mAnimationDirection == DIRECTION_HIDE ? "HIDE" : "NONE")));
+ }
if ((mAnimationDirection == DIRECTION_SHOW && show)
|| (mAnimationDirection == DIRECTION_HIDE && !show)) {
return;
@@ -289,6 +298,11 @@
public void onAnimationStart(Animator animation) {
SurfaceControl.Transaction t = mTransactionPool.acquire();
t.setPosition(mImeSourceControl.getLeash(), x, startY);
+ if (DEBUG) {
+ Slog.d(TAG, "onAnimationStart d:" + mDisplayId + " top:"
+ + imeTop(imeSource, hiddenY) + "->" + imeTop(imeSource, shownY)
+ + " showing:" + (mAnimationDirection == DIRECTION_SHOW));
+ }
dispatchStartPositioning(mDisplayId, imeTop(imeSource, hiddenY),
imeTop(imeSource, shownY), mAnimationDirection == DIRECTION_SHOW,
t);
@@ -304,6 +318,7 @@
}
@Override
public void onAnimationEnd(Animator animation) {
+ if (DEBUG) Slog.d(TAG, "onAnimationEnd " + mCancelled);
SurfaceControl.Transaction t = mTransactionPool.acquire();
if (!mCancelled) {
t.setPosition(mImeSourceControl.getLeash(), x, endY);
diff --git a/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java b/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
index 23df991..381ccdb 100644
--- a/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
+++ b/packages/SystemUI/src/com/android/systemui/wm/SystemWindows.java
@@ -196,7 +196,7 @@
final Display display = mDisplayController.getDisplay(mDisplayId);
SurfaceControlViewHost viewRoot = new SurfaceControlViewHost(mContext, display, wwm);
attrs.flags |= FLAG_HARDWARE_ACCELERATED;
- viewRoot.addView(view, attrs);
+ viewRoot.setView(view, attrs);
mViewRoots.put(view, viewRoot);
}
@@ -324,7 +324,7 @@
@Override
public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
- boolean sync) {}
+ float zoom, boolean sync) {}
@Override
public void dispatchWallpaperCommand(String action, int x, int y,
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
index ea6cf33..f7daf97 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java
@@ -249,7 +249,7 @@
// STOPSHIP(b/130246708) This line makes sure that SubscriptionManager provides the
// same answer as KeyguardUpdateMonitor. Remove when this is addressed
- when(mSubscriptionManager.getActiveAndHiddenSubscriptionInfoList()).thenReturn(
+ when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(
new ArrayList<>());
when(mKeyguardUpdateMonitor.getSimState(anyInt())).thenReturn(
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
index eead120..4f4ce13 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
@@ -516,7 +516,7 @@
List<SubscriptionInfo> list = new ArrayList<>();
list.add(TEST_SUBSCRIPTION);
list.add(TEST_SUBSCRIPTION_2);
- when(mSubscriptionManager.getActiveAndHiddenSubscriptionInfoList()).thenReturn(list);
+ when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList()).thenReturn(list);
mKeyguardUpdateMonitor.mPhoneStateListener.onActiveDataSubscriptionIdChanged(
TEST_SUBSCRIPTION_2.getSubscriptionId());
mTestableLooper.processAllMessages();
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
index 6199181..353fe62 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/clock/ClockManagerTest.java
@@ -50,6 +50,8 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.util.Arrays;
+
@SmallTest
@RunWith(AndroidTestingRunner.class)
// Need to run tests on main looper because LiveData operations such as setData, observe,
@@ -126,7 +128,7 @@
when(mMockSettingsWrapper.getLockScreenCustomClockFace(anyInt())).thenReturn(null);
when(mMockSettingsWrapper.getDockedClockFace(anyInt())).thenReturn(null);
// WHEN settings change event is fired
- mContentObserver.onChange(false, SETTINGS_URI, MAIN_USER_ID);
+ mContentObserver.onChange(false, Arrays.asList(SETTINGS_URI), 0, MAIN_USER_ID);
// THEN the result is null, indicated the default clock face should be used.
assertThat(mClockManager.getCurrentClock()).isNull();
}
@@ -136,7 +138,7 @@
// GIVEN that settings is set to the bubble clock face
when(mMockSettingsWrapper.getLockScreenCustomClockFace(anyInt())).thenReturn(BUBBLE_CLOCK);
// WHEN settings change event is fired
- mContentObserver.onChange(false, SETTINGS_URI, MAIN_USER_ID);
+ mContentObserver.onChange(false, Arrays.asList(SETTINGS_URI), 0, MAIN_USER_ID);
// THEN the plugin is the bubble clock face.
assertThat(mClockManager.getCurrentClock()).isInstanceOf(BUBBLE_CLOCK_CLASS);
}
@@ -146,7 +148,7 @@
// GIVEN that settings is set to the bubble clock face
when(mMockSettingsWrapper.getLockScreenCustomClockFace(anyInt())).thenReturn(BUBBLE_CLOCK);
// WHEN settings change event is fired
- mContentObserver.onChange(false, SETTINGS_URI, MAIN_USER_ID);
+ mContentObserver.onChange(false, Arrays.asList(SETTINGS_URI), 0, MAIN_USER_ID);
// THEN the plugin is the bubble clock face.
ArgumentCaptor<ClockPlugin> captor = ArgumentCaptor.forClass(ClockPlugin.class);
verify(mMockListener1).onClockChanged(captor.capture());
@@ -158,7 +160,7 @@
// GIVEN that settings is set to the bubble clock face
when(mMockSettingsWrapper.getLockScreenCustomClockFace(anyInt())).thenReturn(BUBBLE_CLOCK);
// WHEN settings change event is fired
- mContentObserver.onChange(false, SETTINGS_URI, MAIN_USER_ID);
+ mContentObserver.onChange(false, Arrays.asList(SETTINGS_URI), 0, MAIN_USER_ID);
// THEN the listeners receive separate instances of the Bubble clock plugin.
ArgumentCaptor<ClockPlugin> captor1 = ArgumentCaptor.forClass(ClockPlugin.class);
ArgumentCaptor<ClockPlugin> captor2 = ArgumentCaptor.forClass(ClockPlugin.class);
@@ -175,7 +177,7 @@
// custom clock face.
when(mMockSettingsWrapper.getLockScreenCustomClockFace(anyInt())).thenReturn("bad value");
// WHEN settings change event is fired
- mContentObserver.onChange(false, SETTINGS_URI, MAIN_USER_ID);
+ mContentObserver.onChange(false, Arrays.asList(SETTINGS_URI), 0, MAIN_USER_ID);
// THEN the result is null.
assertThat(mClockManager.getCurrentClock()).isNull();
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
index 1b34b3d..b6537bf 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/ScreenDecorationsTest.java
@@ -23,6 +23,8 @@
import static com.android.systemui.ScreenDecorations.rectsToRegion;
+import static com.google.common.truth.Truth.assertThat;
+
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -42,6 +44,7 @@
import android.content.res.Configuration;
import android.graphics.Insets;
import android.graphics.Rect;
+import android.graphics.drawable.VectorDrawable;
import android.hardware.display.DisplayManager;
import android.os.Handler;
import android.testing.AndroidTestingRunner;
@@ -142,6 +145,8 @@
com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 0);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// no cutout
doReturn(null).when(mScreenDecorations).getCutout();
@@ -161,6 +166,8 @@
com.android.internal.R.dimen.rounded_corner_radius, 20);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 20);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// no cutout
doReturn(null).when(mScreenDecorations).getCutout();
@@ -182,6 +189,67 @@
}
@Test
+ public void testRoundingRadius_NoCutout() {
+ final int testRadius = 1;
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.dimen.rounded_corner_radius, testRadius);
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.dimen.rounded_corner_radius_top, testRadius);
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.dimen.rounded_corner_radius_bottom, testRadius);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
+
+ // no cutout
+ doReturn(null).when(mScreenDecorations).getCutout();
+
+ mScreenDecorations.start();
+ // Size of corner view should same as rounded_corner_radius{_top|_bottom}
+ assertThat(mScreenDecorations.mRoundedDefault).isEqualTo(testRadius);
+ assertThat(mScreenDecorations.mRoundedDefaultTop).isEqualTo(testRadius);
+ assertThat(mScreenDecorations.mRoundedDefaultBottom).isEqualTo(testRadius);
+ }
+
+ @Test
+ public void testRoundingMultipleRadius_NoCutout() {
+ final VectorDrawable d = (VectorDrawable) mContext.getDrawable(R.drawable.rounded);
+ final int multipleRadiusSize = Math.max(d.getIntrinsicWidth(), d.getIntrinsicHeight());
+
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
+ mContext.getOrCreateTestableResources().addOverride(
+ com.android.internal.R.dimen.rounded_corner_radius, 9999);
+ mContext.getOrCreateTestableResources()
+ .addOverride(dimen.rounded_corner_content_padding, 9999);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, true);
+
+ // no cutout
+ doReturn(null).when(mScreenDecorations).getCutout();
+
+ mScreenDecorations.start();
+ // Top and bottom windows are created for rounded corners.
+ verify(mWindowManager, times(1))
+ .addView(eq(mScreenDecorations.mOverlays[BOUNDS_POSITION_TOP]), any());
+ verify(mWindowManager, times(1))
+ .addView(eq(mScreenDecorations.mOverlays[BOUNDS_POSITION_BOTTOM]), any());
+
+ // Left and right window should be null.
+ assertNull(mScreenDecorations.mOverlays[BOUNDS_POSITION_LEFT]);
+ assertNull(mScreenDecorations.mOverlays[BOUNDS_POSITION_RIGHT]);
+
+ // One tunable.
+ verify(mTunerService, times(1)).addTunable(any(), any());
+
+ // Size of corner view should exactly match max(width, height) of R.drawable.rounded
+ assertThat(mScreenDecorations.mRoundedDefault).isEqualTo(multipleRadiusSize);
+ assertThat(mScreenDecorations.mRoundedDefaultTop).isEqualTo(multipleRadiusSize);
+ assertThat(mScreenDecorations.mRoundedDefaultBottom).isEqualTo(multipleRadiusSize);
+ }
+
+ @Test
public void testNoRounding_CutoutShortEdge() {
mContext.getOrCreateTestableResources().addOverride(
com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, true);
@@ -193,6 +261,8 @@
com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 0);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// top cutout
doReturn(new DisplayCutout(
@@ -227,6 +297,8 @@
com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 0);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// left cutout
doReturn(new DisplayCutout(
@@ -257,6 +329,8 @@
com.android.internal.R.dimen.rounded_corner_radius, 20);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 20);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// top cutout
doReturn(new DisplayCutout(
@@ -288,6 +362,8 @@
com.android.internal.R.dimen.rounded_corner_radius, 20);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 20);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// left cutout
doReturn(new DisplayCutout(
@@ -319,6 +395,8 @@
com.android.internal.R.dimen.rounded_corner_radius, 20);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 20);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// top and left cutout
doReturn(new DisplayCutout(
@@ -355,6 +433,8 @@
com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 0);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// Set to short edge cutout(top).
doReturn(new DisplayCutout(
@@ -402,6 +482,8 @@
com.android.internal.R.dimen.rounded_corner_radius_bottom, 0);
mContext.getOrCreateTestableResources()
.addOverride(dimen.rounded_corner_content_padding, 0);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
// top cutout
doReturn(new DisplayCutout(
@@ -440,6 +522,8 @@
com.android.internal.R.bool.config_fillMainBuiltInDisplayCutout, false);
mContext.getOrCreateTestableResources().addOverride(
com.android.internal.R.dimen.rounded_corner_radius, 20);
+ mContext.getOrCreateTestableResources()
+ .addOverride(R.bool.config_roundedCornerMultipleRadius, false);
mScreenDecorations.start();
assertEquals(mScreenDecorations.mRoundedDefault, 20);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
index c6c7b87..1db8e4c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthContainerViewTest.java
@@ -78,7 +78,9 @@
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_AUTHENTICATED);
- verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED));
+ verify(mCallback).onDismissed(
+ eq(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED),
+ eq(null) /* credentialAttestation */);
}
@Test
@@ -87,7 +89,9 @@
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_USER_CANCELED);
- verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_USER_CANCELED));
+ verify(mCallback).onDismissed(
+ eq(AuthDialogCallback.DISMISSED_USER_CANCELED),
+ eq(null) /* credentialAttestation */);
}
@Test
@@ -96,7 +100,9 @@
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_BUTTON_NEGATIVE);
- verify(mCallback).onDismissed(eq(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE));
+ verify(mCallback).onDismissed(
+ eq(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE),
+ eq(null) /* credentialAttestation */);
}
@Test
@@ -114,7 +120,9 @@
mAuthContainer.mBiometricCallback.onAction(
AuthBiometricView.Callback.ACTION_ERROR);
- verify(mCallback).onDismissed(AuthDialogCallback.DISMISSED_ERROR);
+ verify(mCallback).onDismissed(
+ eq(AuthDialogCallback.DISMISSED_ERROR),
+ eq(null) /* credentialAttestation */);
}
@Test
@@ -219,7 +227,8 @@
@Override
public void animateAway(int reason) {
- mConfig.mCallback.onDismissed(reason);
+ // TODO: Credential attestation should be testable/tested
+ mConfig.mCallback.onDismissed(reason, null /* credentialAttestation */);
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
index 65399bf..fc1ddf7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java
@@ -57,12 +57,14 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.AdditionalMatchers;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
+import java.util.Random;
@RunWith(AndroidTestingRunner.class)
@RunWithLooper
@@ -110,52 +112,75 @@
@Test
public void testSendsReasonUserCanceled_whenDismissedByUserCancel() throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED,
+ null /* credentialAttestation */);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testSendsReasonNegative_whenDismissedByButtonNegative() throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_NEGATIVE);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_NEGATIVE,
+ null /* credentialAttestation */);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_NEGATIVE),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testSendsReasonConfirmed_whenDismissedByButtonPositive() throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_POSITIVE);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BUTTON_POSITIVE,
+ null /* credentialAttestation */);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testSendsReasonConfirmNotRequired_whenDismissedByAuthenticated() throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BIOMETRIC_AUTHENTICATED,
+ null /* credentialAttestation */);
verify(mReceiver).onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
+ eq(BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testSendsReasonError_whenDismissedByError() throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_ERROR);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_ERROR);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_ERROR,
+ null /* credentialAttestation */);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_ERROR),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testSendsReasonServerRequested_whenDismissedByServer() throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BY_SYSTEM_SERVER);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_BY_SYSTEM_SERVER,
+ null /* credentialAttestation */);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_SERVER_REQUESTED),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testSendsReasonCredentialConfirmed_whenDeviceCredentialAuthenticated()
throws Exception {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED);
+
+ final byte[] credentialAttestation = generateRandomHAT();
+
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED,
+ credentialAttestation);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED),
+ AdditionalMatchers.aryEq(credentialAttestation));
}
// Statusbar tests
@@ -302,8 +327,13 @@
showDialog(Authenticators.DEVICE_CREDENTIAL, BiometricPrompt.TYPE_NONE);
verify(mDialog1).show(any(), any());
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED);
- verify(mReceiver).onDialogDismissed(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED);
+ final byte[] credentialAttestation = generateRandomHAT();
+
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_CREDENTIAL_AUTHENTICATED,
+ credentialAttestation);
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED),
+ AdditionalMatchers.aryEq(credentialAttestation));
mAuthController.hideAuthenticationDialog();
}
@@ -395,20 +425,24 @@
assertNull(mAuthController.mCurrentDialog);
assertNull(mAuthController.mReceiver);
verify(mDialog1).dismissWithoutCallback(true /* animate */);
- verify(mReceiver).onDialogDismissed(eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL));
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL),
+ eq(null) /* credentialAttestation */);
}
@Test
public void testDoesNotCrash_whenTryAgainPressedAfterDismissal() {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED,
+ null /* credentialAttestation */);
mAuthController.onTryAgainPressed();
}
@Test
public void testDoesNotCrash_whenDeviceCredentialPressedAfterDismissal() {
showDialog(Authenticators.BIOMETRIC_WEAK, BiometricPrompt.TYPE_FACE);
- mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED);
+ mAuthController.onDismissed(AuthDialogCallback.DISMISSED_USER_CANCELED,
+ null /* credentialAttestation */);
mAuthController.onDeviceCredentialPressed();
}
@@ -422,7 +456,9 @@
assertNull(mAuthController.mCurrentDialog);
assertNull(mAuthController.mReceiver);
verify(mDialog1).dismissWithoutCallback(true /* animate */);
- verify(mReceiver).onDialogDismissed(eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL));
+ verify(mReceiver).onDialogDismissed(
+ eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL),
+ eq(null) /* credentialAttestation */);
}
// Helpers
@@ -433,7 +469,8 @@
biometricModality,
true /* requireConfirmation */,
0 /* userId */,
- "testPackage");
+ "testPackage",
+ 0 /* operationId */);
}
private Bundle createTestDialogBundle(int authenticators) {
@@ -453,6 +490,13 @@
return bundle;
}
+ private byte[] generateRandomHAT() {
+ byte[] HAT = new byte[69];
+ Random random = new Random();
+ random.nextBytes(HAT);
+ return HAT;
+ }
+
private final class TestableAuthController extends AuthController {
private int mBuildCount = 0;
private Bundle mLastBiometricPromptBundle;
@@ -464,7 +508,7 @@
@Override
protected AuthDialog buildDialog(Bundle biometricPromptBundle,
boolean requireConfirmation, int userId, int type, String opPackageName,
- boolean skipIntro) {
+ boolean skipIntro, long operationId) {
mLastBiometricPromptBundle = biometricPromptBundle;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index 742e652..6e612d7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -45,7 +45,11 @@
import android.app.Notification;
import android.app.PendingIntent;
import android.content.res.Resources;
+import android.hardware.display.AmbientDisplayConfiguration;
import android.hardware.face.FaceManager;
+import android.os.Handler;
+import android.os.PowerManager;
+import android.service.dreams.IDreamManager;
import android.service.notification.ZenModeConfig;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -61,14 +65,12 @@
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.FeatureFlags;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
-import com.android.systemui.statusbar.NotificationPresenter;
import com.android.systemui.statusbar.NotificationRemoveInterceptor;
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
@@ -227,15 +229,17 @@
mZenModeConfig.suppressedVisualEffects = 0;
when(mZenModeController.getConfig()).thenReturn(mZenModeConfig);
- TestableNotificationInterruptionStateProvider interruptionStateProvider =
- new TestableNotificationInterruptionStateProvider(mContext,
+ TestableNotificationInterruptStateProviderImpl interruptionStateProvider =
+ new TestableNotificationInterruptStateProviderImpl(mContext.getContentResolver(),
+ mock(PowerManager.class),
+ mock(IDreamManager.class),
+ mock(AmbientDisplayConfiguration.class),
mock(NotificationFilter.class),
mock(StatusBarStateController.class),
- mock(BatteryController.class));
- interruptionStateProvider.setUpWithPresenter(
- mock(NotificationPresenter.class),
- mock(HeadsUpManager.class),
- mock(NotificationInterruptionStateProvider.HeadsUpSuppressor.class));
+ mock(BatteryController.class),
+ mock(HeadsUpManager.class),
+ mock(Handler.class)
+ );
mBubbleData = new BubbleData(mContext);
when(mFeatureFlagsOldPipeline.isNewNotifPipelineRenderingEnabled()).thenReturn(false);
mBubbleController = new TestableBubbleController(
@@ -399,7 +403,8 @@
// Switch which bubble is expanded
mBubbleController.selectBubble(mRow.getEntry().getKey());
mBubbleData.setExpanded(true);
- assertEquals(mRow.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow.getEntry(),
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry());
assertTrue(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow.getEntry()));
@@ -492,21 +497,25 @@
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow2.getEntry().getKey());
// Last added is the one that is expanded
- assertEquals(mRow2.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow2.getEntry(),
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry());
assertTrue(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow2.getEntry()));
// Dismiss currently expanded
- mBubbleController.removeBubble(stackView.getExpandedBubble().getEntry(),
+ mBubbleController.removeBubble(
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry(),
BubbleController.DISMISS_USER_GESTURE);
verify(mBubbleExpandListener).onBubbleExpandChanged(false, mRow2.getEntry().getKey());
// Make sure first bubble is selected
- assertEquals(mRow.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow.getEntry(),
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry());
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow.getEntry().getKey());
// Dismiss that one
- mBubbleController.removeBubble(stackView.getExpandedBubble().getEntry(),
+ mBubbleController.removeBubble(
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry(),
BubbleController.DISMISS_USER_GESTURE);
// Make sure state changes and collapse happens
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java
index f40fc94..866dfdc 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleDataTest.java
@@ -268,13 +268,18 @@
sendUpdatedEntryAtTime(mEntryB2, 5000);
mBubbleData.setListener(mListener);
- // Test
sendUpdatedEntryAtTime(mEntryC1, 6000);
verifyUpdateReceived();
-
- // Verify
assertBubbleRemoved(mBubbleA1, BubbleController.DISMISS_AGED);
- assertThat(mBubbleData.getOverflowBubbles()).isEqualTo(ImmutableList.of(mBubbleA1));
+ assertOverflowChangedTo(ImmutableList.of(mBubbleA1));
+
+ Bubble bubbleA1 = mBubbleData.getOrCreateBubble(mEntryA1);
+ bubbleA1.markUpdatedAt(7000L);
+ mBubbleData.notificationEntryUpdated(bubbleA1, false /* suppressFlyout*/,
+ true /* showInShade */);
+ verifyUpdateReceived();
+ assertBubbleRemoved(mBubbleA2, BubbleController.DISMISS_AGED);
+ assertOverflowChangedTo(ImmutableList.of(mBubbleA2));
}
/**
@@ -931,6 +936,11 @@
assertThat(update.expanded).named("expanded").isEqualTo(expected);
}
+ private void assertOverflowChangedTo(ImmutableList<Bubble> bubbles) {
+ BubbleData.Update update = mUpdateCaptor.getValue();
+ assertThat(update.overflowBubbles).isEqualTo(bubbles);
+ }
+
private NotificationEntry createBubbleEntry(int userId, String notifKey, String packageName) {
return createBubbleEntry(userId, notifKey, packageName, 1000);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/NewNotifPipelineBubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/NewNotifPipelineBubbleControllerTest.java
index 22ef3f3..6244644 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/NewNotifPipelineBubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/NewNotifPipelineBubbleControllerTest.java
@@ -41,7 +41,11 @@
import android.app.Notification;
import android.app.PendingIntent;
import android.content.res.Resources;
+import android.hardware.display.AmbientDisplayConfiguration;
import android.hardware.face.FaceManager;
+import android.os.Handler;
+import android.os.PowerManager;
+import android.service.dreams.IDreamManager;
import android.service.notification.ZenModeConfig;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
@@ -57,12 +61,10 @@
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.FeatureFlags;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
-import com.android.systemui.statusbar.NotificationPresenter;
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
@@ -130,19 +132,15 @@
private KeyguardBypassController mKeyguardBypassController;
@Mock
private FloatingContentCoordinator mFloatingContentCoordinator;
-
@Captor
private ArgumentCaptor<NotifCollectionListener> mNotifListenerCaptor;
-
private TestableBubbleController mBubbleController;
private NotificationShadeWindowController mNotificationShadeWindowController;
private NotifCollectionListener mEntryListener;
-
private NotificationTestHelper mNotificationTestHelper;
private ExpandableNotificationRow mRow;
private ExpandableNotificationRow mRow2;
private ExpandableNotificationRow mNonBubbleNotifRow;
-
@Mock
private BubbleController.BubbleStateChangeListener mBubbleStateChangeListener;
@Mock
@@ -216,15 +214,17 @@
mZenModeConfig.suppressedVisualEffects = 0;
when(mZenModeController.getConfig()).thenReturn(mZenModeConfig);
- TestableNotificationInterruptionStateProvider interruptionStateProvider =
- new TestableNotificationInterruptionStateProvider(mContext,
+ TestableNotificationInterruptStateProviderImpl interruptionStateProvider =
+ new TestableNotificationInterruptStateProviderImpl(mContext.getContentResolver(),
+ mock(PowerManager.class),
+ mock(IDreamManager.class),
+ mock(AmbientDisplayConfiguration.class),
mock(NotificationFilter.class),
mock(StatusBarStateController.class),
- mock(BatteryController.class));
- interruptionStateProvider.setUpWithPresenter(
- mock(NotificationPresenter.class),
- mock(HeadsUpManager.class),
- mock(NotificationInterruptionStateProvider.HeadsUpSuppressor.class));
+ mock(BatteryController.class),
+ mock(HeadsUpManager.class),
+ mock(Handler.class)
+ );
mBubbleData = new BubbleData(mContext);
when(mFeatureFlagsNewPipeline.isNewNotifPipelineRenderingEnabled()).thenReturn(true);
mBubbleController = new TestableBubbleController(
@@ -309,7 +309,7 @@
verify(mNotifCallback, times(1)).invalidateNotifications(anyString());
assertNotNull(mBubbleData.getBubbleWithKey(mRow.getEntry().getKey()));
mBubbleController.updateBubble(mRow2.getEntry());
- verify(mNotifCallback, times(2)).invalidateNotifications(anyString());
+ verify(mNotifCallback, times(2)).invalidateNotifications(anyString());
assertNotNull(mBubbleData.getBubbleWithKey(mRow2.getEntry().getKey()));
assertTrue(mBubbleController.hasBubbles());
@@ -379,7 +379,8 @@
// Switch which bubble is expanded
mBubbleController.selectBubble(mRow.getEntry().getKey());
mBubbleData.setExpanded(true);
- assertEquals(mRow.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow.getEntry(),
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry());
assertTrue(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow.getEntry()));
@@ -471,21 +472,25 @@
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow2.getEntry().getKey());
// Last added is the one that is expanded
- assertEquals(mRow2.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow2.getEntry(),
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry());
assertTrue(mBubbleController.isBubbleNotificationSuppressedFromShade(
mRow2.getEntry()));
// Dismiss currently expanded
- mBubbleController.removeBubble(stackView.getExpandedBubble().getEntry(),
+ mBubbleController.removeBubble(
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry(),
BubbleController.DISMISS_USER_GESTURE);
verify(mBubbleExpandListener).onBubbleExpandChanged(false, mRow2.getEntry().getKey());
// Make sure first bubble is selected
- assertEquals(mRow.getEntry(), stackView.getExpandedBubble().getEntry());
+ assertEquals(mRow.getEntry(),
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry());
verify(mBubbleExpandListener).onBubbleExpandChanged(true, mRow.getEntry().getKey());
// Dismiss that one
- mBubbleController.removeBubble(stackView.getExpandedBubble().getEntry(),
+ mBubbleController.removeBubble(
+ mBubbleData.getBubbleWithKey(stackView.getExpandedBubble().getKey()).getEntry(),
BubbleController.DISMISS_USER_GESTURE);
// Make sure state changes and collapse happens
@@ -645,7 +650,7 @@
}
@Test
- public void removeBubble_intercepted() {
+ public void removeBubble_intercepted() {
mEntryListener.onEntryAdded(mRow.getEntry());
mBubbleController.updateBubble(mRow.getEntry());
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableBubbleController.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableBubbleController.java
index de1fb41..d3d90c4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableBubbleController.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableBubbleController.java
@@ -23,8 +23,8 @@
import com.android.systemui.statusbar.FeatureFlags;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.ShadeController;
@@ -44,7 +44,7 @@
ShadeController shadeController,
BubbleData data,
ConfigurationController configurationController,
- NotificationInterruptionStateProvider interruptionStateProvider,
+ NotificationInterruptStateProvider interruptionStateProvider,
ZenModeController zenModeController,
NotificationLockscreenUserManager lockscreenUserManager,
NotificationGroupManager groupManager,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableNotificationInterruptStateProviderImpl.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableNotificationInterruptStateProviderImpl.java
new file mode 100644
index 0000000..17dc76b
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableNotificationInterruptStateProviderImpl.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2020 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.bubbles;
+
+import android.content.ContentResolver;
+import android.hardware.display.AmbientDisplayConfiguration;
+import android.os.Handler;
+import android.os.PowerManager;
+import android.service.dreams.IDreamManager;
+
+import com.android.systemui.plugins.statusbar.StatusBarStateController;
+import com.android.systemui.statusbar.notification.NotificationFilter;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProviderImpl;
+import com.android.systemui.statusbar.policy.BatteryController;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
+
+public class TestableNotificationInterruptStateProviderImpl
+ extends NotificationInterruptStateProviderImpl {
+
+ TestableNotificationInterruptStateProviderImpl(
+ ContentResolver contentResolver,
+ PowerManager powerManager,
+ IDreamManager dreamManager,
+ AmbientDisplayConfiguration ambientDisplayConfiguration,
+ NotificationFilter filter,
+ StatusBarStateController statusBarStateController,
+ BatteryController batteryController,
+ HeadsUpManager headsUpManager,
+ Handler mainHandler) {
+ super(contentResolver,
+ powerManager,
+ dreamManager,
+ ambientDisplayConfiguration,
+ filter,
+ batteryController,
+ statusBarStateController,
+ headsUpManager,
+ mainHandler);
+ mUseHeadsUp = true;
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableNotificationInterruptionStateProvider.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableNotificationInterruptionStateProvider.java
deleted file mode 100644
index 5d192b2..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/TestableNotificationInterruptionStateProvider.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2020 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.bubbles;
-
-import android.content.Context;
-
-import com.android.systemui.plugins.statusbar.StatusBarStateController;
-import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
-import com.android.systemui.statusbar.policy.BatteryController;
-
-public class TestableNotificationInterruptionStateProvider
- extends NotificationInterruptionStateProvider {
-
- TestableNotificationInterruptionStateProvider(Context context,
- NotificationFilter filter, StatusBarStateController controller,
- BatteryController batteryController) {
- super(context, filter, controller, batteryController);
- mUseHeadsUp = true;
- }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
index ae4581a..ec6d3e9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/ExpandedAnimationControllerTest.java
@@ -17,7 +17,6 @@
package com.android.systemui.bubbles.animation;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.verify;
import android.content.res.Configuration;
@@ -118,118 +117,6 @@
testBubblesInCorrectExpandedPositions();
}
- @Test
- @Ignore
- public void testBubbleDraggedNotDismissedSnapsBack() throws InterruptedException {
- expand();
-
- final View draggedBubble = mViews.get(0);
- mExpandedController.prepareForBubbleDrag(draggedBubble);
- mExpandedController.dragBubbleOut(draggedBubble, 500f, 500f);
-
- assertEquals(500f, draggedBubble.getTranslationX(), 1f);
- assertEquals(500f, draggedBubble.getTranslationY(), 1f);
-
- // Snap it back and make sure it made it back correctly.
- mExpandedController.snapBubbleBack(draggedBubble, 0f, 0f);
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
- testBubblesInCorrectExpandedPositions();
- }
-
- @Test
- @Ignore
- public void testBubbleDismissed() throws InterruptedException {
- expand();
-
- final View draggedBubble = mViews.get(0);
- mExpandedController.prepareForBubbleDrag(draggedBubble);
- mExpandedController.dragBubbleOut(draggedBubble, 500f, 500f);
-
- assertEquals(500f, draggedBubble.getTranslationX(), 1f);
- assertEquals(500f, draggedBubble.getTranslationY(), 1f);
-
- mLayout.removeView(draggedBubble);
- waitForLayoutMessageQueue();
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
-
- assertEquals(-1, mLayout.indexOfChild(draggedBubble));
- testBubblesInCorrectExpandedPositions();
- }
-
- @Test
- @Ignore("Flaky")
- public void testMagnetToDismiss_dismiss() throws InterruptedException {
- expand();
-
- final View draggedOutView = mViews.get(0);
- final Runnable after = Mockito.mock(Runnable.class);
-
- mExpandedController.prepareForBubbleDrag(draggedOutView);
- mExpandedController.dragBubbleOut(draggedOutView, 25, 25);
-
- // Magnet to dismiss, verify the bubble is at the dismiss target and the callback was
- // called.
- mExpandedController.magnetBubbleToDismiss(
- mViews.get(0), 100 /* velX */, 100 /* velY */, 1000 /* destY */, after);
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
- verify(after).run();
- assertEquals(1000, mViews.get(0).getTranslationY(), .1f);
-
- // Dismiss the now-magneted bubble, verify that the callback was called.
- final Runnable afterDismiss = Mockito.mock(Runnable.class);
- mExpandedController.dismissDraggedOutBubble(draggedOutView, afterDismiss);
- waitForPropertyAnimations(DynamicAnimation.ALPHA);
- verify(after).run();
-
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
-
- assertEquals(mBubblePaddingTop, mViews.get(1).getTranslationX(), 1f);
- }
-
- @Test
- @Ignore("Flaky")
- public void testMagnetToDismiss_demagnetizeThenDrag() throws InterruptedException {
- expand();
-
- final View draggedOutView = mViews.get(0);
- final Runnable after = Mockito.mock(Runnable.class);
-
- mExpandedController.prepareForBubbleDrag(draggedOutView);
- mExpandedController.dragBubbleOut(draggedOutView, 25, 25);
-
- // Magnet to dismiss, verify the bubble is at the dismiss target and the callback was
- // called.
- mExpandedController.magnetBubbleToDismiss(
- draggedOutView, 100 /* velX */, 100 /* velY */, 1000 /* destY */, after);
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
- verify(after).run();
- assertEquals(1000, mViews.get(0).getTranslationY(), .1f);
-
- // Demagnetize the bubble towards (25, 25).
- mExpandedController.demagnetizeBubbleTo(25 /* x */, 25 /* y */, 100, 100);
-
- // Start dragging towards (20, 20).
- mExpandedController.dragBubbleOut(draggedOutView, 20, 20);
-
- // Since we just demagnetized, the bubble shouldn't be at (20, 20), it should be animating
- // towards it.
- assertNotEquals(20, draggedOutView.getTranslationX());
- assertNotEquals(20, draggedOutView.getTranslationY());
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
-
- // Waiting for the animations should result in the bubble ending at (20, 20) since the
- // animation end value was updated.
- assertEquals(20, draggedOutView.getTranslationX(), 1f);
- assertEquals(20, draggedOutView.getTranslationY(), 1f);
-
- // Drag to (30, 30).
- mExpandedController.dragBubbleOut(draggedOutView, 30, 30);
-
- // It should go there instantly since the animations finished.
- assertEquals(30, draggedOutView.getTranslationX(), 1f);
- assertEquals(30, draggedOutView.getTranslationY(), 1f);
- }
-
/** Expand the stack and wait for animations to finish. */
private void expand() throws InterruptedException {
mExpandedController.expandFromStack(Mockito.mock(Runnable.class));
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
index 9cc0349..b1ac022 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
@@ -17,7 +17,6 @@
package com.android.systemui.bubbles.animation;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -41,10 +40,10 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.Mockito;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.function.IntSupplier;
@SmallTest
@RunWith(AndroidTestingRunner.class)
@@ -61,7 +60,13 @@
@Before
public void setUp() throws Exception {
super.setUp();
- mStackController = spy(new TestableStackController(mFloatingContentCoordinator));
+ mStackController = spy(new TestableStackController(
+ mFloatingContentCoordinator, new IntSupplier() {
+ @Override
+ public int getAsInt() {
+ return mLayout.getChildCount();
+ }
+ }));
mLayout.setActiveController(mStackController);
addOneMoreThanBubbleLimitBubbles();
mStackOffset = mLayout.getResources().getDimensionPixelSize(R.dimen.bubble_stack_offset);
@@ -242,61 +247,6 @@
}
@Test
- @Ignore("Flaky")
- public void testMagnetToDismiss_dismiss() throws InterruptedException {
- final Runnable after = Mockito.mock(Runnable.class);
-
- // Magnet to dismiss, verify the stack is at the dismiss target and the callback was
- // called.
- mStackController.magnetToDismiss(100 /* velX */, 100 /* velY */, 1000 /* destY */, after);
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
- verify(after).run();
- assertEquals(1000, mViews.get(0).getTranslationY(), .1f);
-
- // Dismiss the stack, verify that the callback was called.
- final Runnable afterImplode = Mockito.mock(Runnable.class);
- mStackController.implodeStack(afterImplode);
- waitForPropertyAnimations(
- DynamicAnimation.ALPHA, DynamicAnimation.SCALE_X, DynamicAnimation.SCALE_Y);
- verify(after).run();
- }
-
- @Test
- @Ignore("Flaking")
- public void testMagnetToDismiss_demagnetizeThenDrag() throws InterruptedException {
- final Runnable after = Mockito.mock(Runnable.class);
-
- // Magnet to dismiss, verify the stack is at the dismiss target and the callback was
- // called.
- mStackController.magnetToDismiss(100 /* velX */, 100 /* velY */, 1000 /* destY */, after);
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
- verify(after).run();
-
- assertEquals(1000, mViews.get(0).getTranslationY(), .1f);
-
- // Demagnetize towards (25, 25) and then send a touch event.
- mStackController.demagnetizeFromDismissToPoint(25, 25, 0, 0);
- waitForLayoutMessageQueue();
- mStackController.moveStackFromTouch(20, 20);
-
- // Since the stack is demagnetizing, it shouldn't be at the stack position yet.
- assertNotEquals(20, mStackController.getStackPosition().x, 1f);
- assertNotEquals(20, mStackController.getStackPosition().y, 1f);
-
- waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y);
-
- // Once the animation is done it should end at the touch position coordinates.
- assertEquals(20, mStackController.getStackPosition().x, 1f);
- assertEquals(20, mStackController.getStackPosition().y, 1f);
-
- mStackController.moveStackFromTouch(30, 30);
-
- // Touches after the animation are done should change the stack position instantly.
- assertEquals(30, mStackController.getStackPosition().x, 1f);
- assertEquals(30, mStackController.getStackPosition().y, 1f);
- }
-
- @Test
public void testFloatingCoordinator() {
// We should have called onContentAdded only once while adding all of the bubbles in
// setup().
@@ -352,8 +302,9 @@
*/
private class TestableStackController extends StackAnimationController {
TestableStackController(
- FloatingContentCoordinator floatingContentCoordinator) {
- super(floatingContentCoordinator);
+ FloatingContentCoordinator floatingContentCoordinator,
+ IntSupplier bubbleCountSupplier) {
+ super(floatingContentCoordinator, bubbleCountSupplier);
}
@Override
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsBindingControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsBindingControllerImplTest.kt
index eceb1dd..c25d4e2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsBindingControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsBindingControllerImplTest.kt
@@ -22,6 +22,8 @@
import android.os.UserHandle
import android.service.controls.Control
import android.service.controls.DeviceTypes
+import android.service.controls.IControlsSubscriber
+import android.service.controls.IControlsSubscription
import android.testing.AndroidTestingRunner
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
@@ -34,6 +36,8 @@
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.ArgumentCaptor
+import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
@@ -48,6 +52,7 @@
class ControlsBindingControllerImplTest : SysuiTestCase() {
companion object {
+ fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()
fun <T> any(): T = Mockito.any<T>()
private val TEST_COMPONENT_NAME_1 = ComponentName("TEST_PKG", "TEST_CLS_1")
private val TEST_COMPONENT_NAME_2 = ComponentName("TEST_PKG", "TEST_CLS_2")
@@ -57,6 +62,15 @@
@Mock
private lateinit var mockControlsController: ControlsController
+ @Captor
+ private lateinit var subscriberCaptor: ArgumentCaptor<IControlsSubscriber.Stub>
+
+ @Captor
+ private lateinit var loadSubscriberCaptor: ArgumentCaptor<IControlsSubscriber.Stub>
+
+ @Captor
+ private lateinit var listStringCaptor: ArgumentCaptor<List<String>>
+
private val user = UserHandle.of(mContext.userId)
private val otherUser = UserHandle.of(user.identifier + 1)
@@ -97,6 +111,102 @@
}
@Test
+ fun testBindAndLoad_cancel() {
+ val callback = object : ControlsBindingController.LoadCallback {
+ override fun error(message: String) {}
+
+ override fun accept(t: List<Control>) {}
+ }
+ val subscription = mock(IControlsSubscription::class.java)
+
+ val canceller = controller.bindAndLoad(TEST_COMPONENT_NAME_1, callback)
+
+ verify(providers[0]).maybeBindAndLoad(capture(loadSubscriberCaptor))
+ loadSubscriberCaptor.value.onSubscribe(Binder(), subscription)
+
+ canceller.run()
+ verify(subscription).cancel()
+ }
+
+ @Test
+ fun testBindAndLoad_noCancelAfterOnComplete() {
+ val callback = object : ControlsBindingController.LoadCallback {
+ override fun error(message: String) {}
+
+ override fun accept(t: List<Control>) {}
+ }
+ val subscription = mock(IControlsSubscription::class.java)
+
+ val canceller = controller.bindAndLoad(TEST_COMPONENT_NAME_1, callback)
+
+ verify(providers[0]).maybeBindAndLoad(capture(loadSubscriberCaptor))
+ val b = Binder()
+ loadSubscriberCaptor.value.onSubscribe(b, subscription)
+
+ loadSubscriberCaptor.value.onComplete(b)
+ canceller.run()
+ verify(subscription, never()).cancel()
+ }
+
+ @Test
+ fun testLoad_onCompleteRemovesTimeout() {
+ val callback = object : ControlsBindingController.LoadCallback {
+ override fun error(message: String) {}
+
+ override fun accept(t: List<Control>) {}
+ }
+ val subscription = mock(IControlsSubscription::class.java)
+
+ val canceller = controller.bindAndLoad(TEST_COMPONENT_NAME_1, callback)
+
+ verify(providers[0]).maybeBindAndLoad(capture(subscriberCaptor))
+ val b = Binder()
+ subscriberCaptor.value.onSubscribe(b, subscription)
+
+ subscriberCaptor.value.onComplete(b)
+ verify(providers[0]).cancelLoadTimeout()
+ }
+
+ @Test
+ fun testLoad_onErrorRemovesTimeout() {
+ val callback = object : ControlsBindingController.LoadCallback {
+ override fun error(message: String) {}
+
+ override fun accept(t: List<Control>) {}
+ }
+ val subscription = mock(IControlsSubscription::class.java)
+
+ val canceller = controller.bindAndLoad(TEST_COMPONENT_NAME_1, callback)
+
+ verify(providers[0]).maybeBindAndLoad(capture(subscriberCaptor))
+ val b = Binder()
+ subscriberCaptor.value.onSubscribe(b, subscription)
+
+ subscriberCaptor.value.onError(b, "")
+ verify(providers[0]).cancelLoadTimeout()
+ }
+
+ @Test
+ fun testBindAndLoad_noCancelAfterOnError() {
+ val callback = object : ControlsBindingController.LoadCallback {
+ override fun error(message: String) {}
+
+ override fun accept(t: List<Control>) {}
+ }
+ val subscription = mock(IControlsSubscription::class.java)
+
+ val canceller = controller.bindAndLoad(TEST_COMPONENT_NAME_1, callback)
+
+ verify(providers[0]).maybeBindAndLoad(capture(loadSubscriberCaptor))
+ val b = Binder()
+ loadSubscriberCaptor.value.onSubscribe(b, subscription)
+
+ loadSubscriberCaptor.value.onError(b, "")
+ canceller.run()
+ verify(subscription, never()).cancel()
+ }
+
+ @Test
fun testBindService() {
controller.bindService(TEST_COMPONENT_NAME_1)
executor.runAllReady()
@@ -115,8 +225,13 @@
executor.runAllReady()
+ val subs = mock(IControlsSubscription::class.java)
verify(providers[0]).maybeBindAndSubscribe(
+ capture(listStringCaptor), capture(subscriberCaptor))
+ assertEquals(listStringCaptor.value,
listOf(controlInfo1.controlId, controlInfo2.controlId))
+
+ subscriberCaptor.value.onSubscribe(providers[0].token, subs)
}
@Test
@@ -126,7 +241,7 @@
executor.runAllReady()
- verify(providers[0], never()).unsubscribe()
+ verify(providers[0], never()).cancelSubscription(any())
}
@Test
@@ -137,12 +252,21 @@
StructureInfo(TEST_COMPONENT_NAME_1, "Home", listOf(controlInfo1, controlInfo2))
controller.subscribe(structure)
-
- controller.unsubscribe()
-
executor.runAllReady()
- verify(providers[0]).unsubscribe()
+ val subs = mock(IControlsSubscription::class.java)
+ verify(providers[0]).maybeBindAndSubscribe(
+ capture(listStringCaptor), capture(subscriberCaptor))
+ assertEquals(listStringCaptor.value,
+ listOf(controlInfo1.controlId, controlInfo2.controlId))
+
+ subscriberCaptor.value.onSubscribe(providers[0].token, subs)
+ executor.runAllReady()
+
+ controller.unsubscribe()
+ executor.runAllReady()
+
+ verify(providers[0]).cancelSubscription(subs)
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsControllerImplTest.kt
index 45ea3c9..f9c9815 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsControllerImplTest.kt
@@ -234,7 +234,7 @@
loaded = true
assertEquals(1, controls.size)
val controlStatus = controls[0]
- assertEquals(ControlStatus(control, false), controlStatus)
+ assertEquals(ControlStatus(control, TEST_COMPONENT, false), controlStatus)
assertTrue(favorites.isEmpty())
assertFalse(data.errorOnLoad)
@@ -265,10 +265,10 @@
loaded = true
assertEquals(2, controls.size)
val controlStatus = controls.first { it.control.controlId == TEST_CONTROL_ID }
- assertEquals(ControlStatus(control, true), controlStatus)
+ assertEquals(ControlStatus(control, TEST_COMPONENT, true), controlStatus)
val controlStatus2 = controls.first { it.control.controlId == TEST_CONTROL_ID_2 }
- assertEquals(ControlStatus(control2, false), controlStatus2)
+ assertEquals(ControlStatus(control2, TEST_COMPONENT, false), controlStatus2)
assertEquals(1, favorites.size)
assertEquals(TEST_CONTROL_ID, favorites[0])
@@ -340,10 +340,94 @@
controlLoadCallbackCaptor.value.error("")
+ delayableExecutor.runAllReady()
+
assertTrue(loaded)
}
@Test
+ fun testCancelLoad() {
+ val canceller = object : Runnable {
+ var ran = false
+ override fun run() {
+ ran = true
+ }
+ }
+ `when`(bindingController.bindAndLoad(any(), any())).thenReturn(canceller)
+
+ var loaded = false
+ controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO)
+ delayableExecutor.runAllReady()
+ controller.loadForComponent(TEST_COMPONENT, Consumer {
+ loaded = true
+ })
+
+ controller.cancelLoad()
+ delayableExecutor.runAllReady()
+
+ assertFalse(loaded)
+ assertTrue(canceller.ran)
+ }
+
+ @Test
+ fun testCancelLoad_noCancelAfterSuccessfulLoad() {
+ val canceller = object : Runnable {
+ var ran = false
+ override fun run() {
+ ran = true
+ }
+ }
+ `when`(bindingController.bindAndLoad(any(), any())).thenReturn(canceller)
+
+ var loaded = false
+ controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO)
+ delayableExecutor.runAllReady()
+ controller.loadForComponent(TEST_COMPONENT, Consumer {
+ loaded = true
+ })
+
+ verify(bindingController).bindAndLoad(eq(TEST_COMPONENT),
+ capture(controlLoadCallbackCaptor))
+
+ controlLoadCallbackCaptor.value.accept(emptyList())
+
+ controller.cancelLoad()
+ delayableExecutor.runAllReady()
+
+ assertTrue(loaded)
+ assertFalse(canceller.ran)
+ }
+
+ @Test
+ fun testCancelLoad_noCancelAfterErrorLoad() {
+ val canceller = object : Runnable {
+ var ran = false
+ override fun run() {
+ ran = true
+ }
+ }
+ `when`(bindingController.bindAndLoad(any(), any())).thenReturn(canceller)
+
+ var loaded = false
+ controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO)
+ delayableExecutor.runAllReady()
+ controller.loadForComponent(TEST_COMPONENT, Consumer {
+ loaded = true
+ })
+
+ verify(bindingController).bindAndLoad(eq(TEST_COMPONENT),
+ capture(controlLoadCallbackCaptor))
+
+ controlLoadCallbackCaptor.value.error("")
+
+ controller.cancelLoad()
+ delayableExecutor.runAllReady()
+
+ assertTrue(loaded)
+ assertFalse(canceller.ran)
+ }
+
+ @Test
fun testFavoriteInformationModifiedOnLoad() {
controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO)
delayableExecutor.runAllReady()
@@ -408,7 +492,7 @@
fun testDisableFeature_notAvailable() {
Settings.Secure.putIntForUser(mContext.contentResolver,
ControlsControllerImpl.CONTROLS_AVAILABLE, 0, user)
- controller.settingObserver.onChange(false, ControlsControllerImpl.URI, 0)
+ controller.settingObserver.onChange(false, listOf(ControlsControllerImpl.URI), 0, 0)
assertFalse(controller.available)
}
@@ -421,7 +505,7 @@
Settings.Secure.putIntForUser(mContext.contentResolver,
ControlsControllerImpl.CONTROLS_AVAILABLE, 0, user)
- controller.settingObserver.onChange(false, ControlsControllerImpl.URI, user)
+ controller.settingObserver.onChange(false, listOf(ControlsControllerImpl.URI), 0, user)
assertTrue(controller.getFavorites().isEmpty())
}
@@ -432,7 +516,7 @@
Settings.Secure.putIntForUser(mContext.contentResolver,
ControlsControllerImpl.CONTROLS_AVAILABLE, 0, otherUser)
- controller.settingObserver.onChange(false, ControlsControllerImpl.URI, otherUser)
+ controller.settingObserver.onChange(false, listOf(ControlsControllerImpl.URI), 0, otherUser)
assertTrue(controller.available)
assertFalse(controller.getFavorites().isEmpty())
@@ -519,7 +603,7 @@
}
@Test
- fun testReplaceFavoritesForStructure_noFavorites() {
+ fun testReplaceFavoritesForStructure_noExistingFavorites() {
controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO)
delayableExecutor.runAllReady()
@@ -529,6 +613,16 @@
}
@Test
+ fun testReplaceFavoritesForStructure_doNotStoreEmptyStructure() {
+ controller.replaceFavoritesForStructure(
+ StructureInfo(TEST_COMPONENT, "Home", emptyList<ControlInfo>()))
+ delayableExecutor.runAllReady()
+
+ assertEquals(0, controller.countFavoritesForComponent(TEST_COMPONENT))
+ assertEquals(emptyList<ControlInfo>(), controller.getFavoritesForComponent(TEST_COMPONENT))
+ }
+
+ @Test
fun testReplaceFavoritesForStructure_differentComponentsAreFilteredOut() {
controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO)
controller.replaceFavoritesForStructure(TEST_STRUCTURE_INFO_2)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManagerTest.kt
index fd92ad0..2d3757c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManagerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlsProviderLifecycleManagerTest.kt
@@ -1,7 +1,7 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * Licensed under the Apache License, Version 2.0 (149the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
@@ -43,6 +43,7 @@
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito.`when`
+import org.mockito.Mockito.never
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
@@ -83,7 +84,6 @@
context,
executor,
actionCallbackService,
- subscriberService,
UserHandle.of(0),
componentName
)
@@ -144,9 +144,22 @@
}
@Test
+ fun testMaybeBindAndLoad_timeoutCancelled() {
+ manager.maybeBindAndLoad(subscriberService)
+ executor.runAllReady()
+
+ manager.cancelLoadTimeout()
+
+ executor.advanceClockToLast()
+ executor.runAllReady()
+
+ verify(subscriberService, never()).onError(any(), anyString())
+ }
+
+ @Test
fun testMaybeBindAndSubscribe() {
val list = listOf("TEST_ID")
- manager.maybeBindAndSubscribe(list)
+ manager.maybeBindAndSubscribe(list, subscriberService)
executor.runAllReady()
assertTrue(mContext.isBound(componentName))
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/StatefulControlSubscriberTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/StatefulControlSubscriberTest.kt
new file mode 100644
index 0000000..ff5c8d4
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/StatefulControlSubscriberTest.kt
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2020 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.controls.controller
+
+import android.content.ComponentName
+import android.os.Binder
+import android.service.controls.Control
+import android.service.controls.IControlsSubscription
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.util.concurrency.FakeExecutor
+import com.android.systemui.util.time.FakeSystemClock
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mock
+import org.mockito.Mockito.never
+import org.mockito.Mockito.`when`
+import org.mockito.Mockito.times
+import org.mockito.Mockito.verify
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+class StatefulControlSubscriberTest : SysuiTestCase() {
+
+ @Mock
+ private lateinit var controller: ControlsController
+
+ @Mock
+ private lateinit var subscription: IControlsSubscription
+
+ @Mock
+ private lateinit var provider: ControlsProviderLifecycleManager
+
+ @Mock
+ private lateinit var control: Control
+
+ private val executor = FakeExecutor(FakeSystemClock())
+ private val token = Binder()
+ private val badToken = Binder()
+
+ private val TEST_COMPONENT = ComponentName("TEST_PKG", "TEST_CLS_1")
+
+ private lateinit var scs: StatefulControlSubscriber
+
+ @Before
+ fun setUp() {
+ MockitoAnnotations.initMocks(this)
+
+ `when`(provider.componentName).thenReturn(TEST_COMPONENT)
+ `when`(provider.token).thenReturn(token)
+ scs = StatefulControlSubscriber(controller, provider, executor)
+ }
+
+ @Test
+ fun testOnSubscribe() {
+ scs.onSubscribe(token, subscription)
+
+ executor.runAllReady()
+ verify(provider).startSubscription(subscription)
+ }
+
+ @Test
+ fun testOnSubscribe_badToken() {
+ scs.onSubscribe(badToken, subscription)
+
+ executor.runAllReady()
+ verify(provider, never()).startSubscription(subscription)
+ }
+
+ @Test
+ fun testOnNext() {
+ scs.onSubscribe(token, subscription)
+ scs.onNext(token, control)
+
+ executor.runAllReady()
+ verify(controller).refreshStatus(TEST_COMPONENT, control)
+ }
+
+ @Test
+ fun testOnNext_multiple() {
+ scs.onSubscribe(token, subscription)
+ scs.onNext(token, control)
+ scs.onNext(token, control)
+ scs.onNext(token, control)
+
+ executor.runAllReady()
+ verify(controller, times(3)).refreshStatus(TEST_COMPONENT, control)
+ }
+
+ @Test
+ fun testOnNext_noRefreshBeforeSubscribe() {
+ scs.onNext(token, control)
+
+ executor.runAllReady()
+ verify(controller, never()).refreshStatus(TEST_COMPONENT, control)
+ }
+
+ @Test
+ fun testOnNext_noRefreshAfterCancel() {
+ scs.onSubscribe(token, subscription)
+ executor.runAllReady()
+
+ scs.cancel()
+ scs.onNext(token, control)
+
+ executor.runAllReady()
+ verify(controller, never()).refreshStatus(TEST_COMPONENT, control)
+ }
+
+ @Test
+ fun testOnNext_noRefreshAfterError() {
+ scs.onSubscribe(token, subscription)
+ scs.onError(token, "Error")
+ scs.onNext(token, control)
+
+ executor.runAllReady()
+ verify(controller, never()).refreshStatus(TEST_COMPONENT, control)
+ }
+
+ @Test
+ fun testOnNext_noRefreshAfterComplete() {
+ scs.onSubscribe(token, subscription)
+ scs.onComplete(token)
+ scs.onNext(token, control)
+
+ executor.runAllReady()
+ verify(controller, never()).refreshStatus(TEST_COMPONENT, control)
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/management/AllModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/management/AllModelTest.kt
index 68e1ec1..133df2a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/management/AllModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/management/AllModelTest.kt
@@ -17,6 +17,7 @@
package com.android.systemui.controls.management
import android.app.PendingIntent
+import android.content.ComponentName
import android.service.controls.Control
import android.testing.AndroidTestingRunner
import androidx.test.filters.SmallTest
@@ -78,6 +79,7 @@
Control.StatelessBuilder("$idPrefix$it", pendingIntent)
.setZone(zoneMap(it))
.build(),
+ ComponentName("", ""),
it in favoritesIndices
)
}
@@ -189,4 +191,4 @@
assertTrue(sameControl(it.first, it.second))
}
}
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt
index 85e937e..13a7708 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt
@@ -30,7 +30,6 @@
import com.android.systemui.util.time.FakeSystemClock
import org.junit.After
import org.junit.Assert.assertEquals
-import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -38,6 +37,7 @@
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
+import org.mockito.Mockito.inOrder
import org.mockito.Mockito.never
import org.mockito.Mockito.reset
import org.mockito.Mockito.verify
@@ -98,74 +98,18 @@
}
@Test
+ fun testInitialStateListening() {
+ verify(mockSL).setListening(true)
+ verify(mockSL).reload()
+ }
+
+ @Test
fun testStartsOnUser() {
assertEquals(user, controller.currentUserId)
}
@Test
- fun testNoServices_notListening() {
- assertTrue(controller.getCurrentServices().isEmpty())
- }
-
- @Test
- fun testStartListening_onFirstCallback() {
- controller.addCallback(mockCallback)
- executor.runAllReady()
-
- verify(mockSL).setListening(true)
- }
-
- @Test
- fun testStartListening_onlyOnce() {
- controller.addCallback(mockCallback)
- controller.addCallback(mockCallbackOther)
-
- executor.runAllReady()
-
- verify(mockSL).setListening(true)
- }
-
- @Test
- fun testStopListening_callbackRemoved() {
- controller.addCallback(mockCallback)
-
- executor.runAllReady()
-
- controller.removeCallback(mockCallback)
-
- executor.runAllReady()
-
- verify(mockSL).setListening(false)
- }
-
- @Test
- fun testStopListening_notWhileRemainingCallbacks() {
- controller.addCallback(mockCallback)
- controller.addCallback(mockCallbackOther)
-
- executor.runAllReady()
-
- controller.removeCallback(mockCallback)
-
- executor.runAllReady()
-
- verify(mockSL, never()).setListening(false)
- }
-
- @Test
- fun testReloadOnFirstCallbackAdded() {
- controller.addCallback(mockCallback)
- executor.runAllReady()
-
- verify(mockSL).reload()
- }
-
- @Test
fun testCallbackCalledWhenAdded() {
- `when`(mockSL.reload()).then {
- serviceListingCallbackCaptor.value.onServicesReloaded(emptyList())
- }
-
controller.addCallback(mockCallback)
executor.runAllReady()
verify(mockCallback).onServicesUpdated(any())
@@ -209,5 +153,11 @@
controller.changeUser(UserHandle.of(otherUser))
executor.runAllReady()
assertEquals(otherUser, controller.currentUserId)
+
+ val inOrder = inOrder(mockSL)
+ inOrder.verify(mockSL).setListening(false)
+ inOrder.verify(mockSL).addCallback(any()) // We add a callback because we replaced the SL
+ inOrder.verify(mockSL).setListening(true)
+ inOrder.verify(mockSL).reload()
}
}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsRequestReceiverTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsRequestReceiverTest.kt
new file mode 100644
index 0000000..663f011
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsRequestReceiverTest.kt
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2020 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.controls.management
+
+import android.app.ActivityManager
+import android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
+import android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE
+import android.content.ComponentName
+import android.content.Context
+import android.content.ContextWrapper
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.UserHandle
+import android.service.controls.Control
+import android.service.controls.ControlsProviderService
+import android.testing.AndroidTestingRunner
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.ArgumentMatchers.anyString
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.Mock
+import org.mockito.Mockito.`when`
+import org.mockito.MockitoAnnotations
+
+@SmallTest
+@RunWith(AndroidTestingRunner::class)
+class ControlsRequestReceiverTest : SysuiTestCase() {
+
+ @Mock
+ private lateinit var packageManager: PackageManager
+ @Mock
+ private lateinit var activityManager: ActivityManager
+ @Mock
+ private lateinit var control: Control
+
+ private val componentName = ComponentName("test_pkg", "test_cls")
+ private lateinit var receiver: ControlsRequestReceiver
+ private lateinit var wrapper: MyWrapper
+ private lateinit var intent: Intent
+
+ @Before
+ fun setUp() {
+ MockitoAnnotations.initMocks(this)
+
+ mContext.setMockPackageManager(packageManager)
+ mContext.addMockSystemService(ActivityManager::class.java, activityManager)
+
+ receiver = ControlsRequestReceiver()
+
+ wrapper = MyWrapper(context)
+
+ intent = Intent(ControlsProviderService.ACTION_ADD_CONTROL).apply {
+ putExtra(Intent.EXTRA_COMPONENT_NAME, componentName)
+ putExtra(ControlsProviderService.EXTRA_CONTROL, control)
+ }
+ }
+
+ @Test
+ fun testPackageVerification_nonExistentPackage() {
+ `when`(packageManager.getPackageUid(anyString(), anyInt()))
+ .thenThrow(PackageManager.NameNotFoundException::class.java)
+
+ assertFalse(ControlsRequestReceiver.isPackageInForeground(mContext, "TEST"))
+ }
+
+ @Test
+ fun testPackageVerification_uidNotInForeground() {
+ `when`(packageManager.getPackageUid(anyString(), anyInt())).thenReturn(12345)
+
+ `when`(activityManager.getUidImportance(anyInt())).thenReturn(IMPORTANCE_GONE)
+
+ assertFalse(ControlsRequestReceiver.isPackageInForeground(mContext, "TEST"))
+ }
+
+ @Test
+ fun testPackageVerification_OK() {
+ `when`(packageManager.getPackageUid(anyString(), anyInt())).thenReturn(12345)
+
+ `when`(activityManager.getUidImportance(anyInt())).thenReturn(IMPORTANCE_GONE)
+ `when`(activityManager.getUidImportance(12345)).thenReturn(IMPORTANCE_FOREGROUND)
+
+ assertTrue(ControlsRequestReceiver.isPackageInForeground(mContext, "TEST"))
+ }
+
+ @Test
+ fun testOnReceive_packageNotVerified_nameNotFound() {
+ `when`(packageManager.getPackageUid(eq(componentName.packageName), anyInt()))
+ .thenThrow(PackageManager.NameNotFoundException::class.java)
+
+ receiver.onReceive(wrapper, intent)
+
+ assertNull(wrapper.intent)
+ }
+
+ @Test
+ fun testOnReceive_packageNotVerified_notForeground() {
+ `when`(packageManager.getPackageUid(eq(componentName.packageName), anyInt()))
+ .thenReturn(12345)
+
+ `when`(activityManager.getUidImportance(anyInt())).thenReturn(IMPORTANCE_GONE)
+
+ receiver.onReceive(wrapper, intent)
+
+ assertNull(wrapper.intent)
+ }
+
+ @Test
+ fun testOnReceive_OK() {
+ `when`(packageManager.getPackageUid(eq(componentName.packageName), anyInt()))
+ .thenReturn(12345)
+
+ `when`(activityManager.getUidImportance(eq(12345))).thenReturn(IMPORTANCE_FOREGROUND)
+
+ receiver.onReceive(wrapper, intent)
+
+ wrapper.intent?.let {
+ assertEquals(ComponentName(wrapper, ControlsRequestDialog::class.java), it.component)
+
+ assertEquals(control, it.getParcelableExtra(ControlsProviderService.EXTRA_CONTROL))
+
+ assertEquals(componentName, it.getParcelableExtra(Intent.EXTRA_COMPONENT_NAME))
+ } ?: run { fail("Null start intent") }
+ }
+
+ class MyWrapper(context: Context) : ContextWrapper(context) {
+ var intent: Intent? = null
+
+ override fun startActivityAsUser(intent: Intent, user: UserHandle) {
+ // Always launch activity as system
+ assertTrue(user == UserHandle.SYSTEM)
+ this.intent = intent
+ }
+
+ override fun startActivity(intent: Intent) {
+ this.intent = intent
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/management/FavoriteModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/management/FavoriteModelTest.kt
index 9ffc29e..c330b38 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/controls/management/FavoriteModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/controls/management/FavoriteModelTest.kt
@@ -17,6 +17,7 @@
package com.android.systemui.controls.management
import android.app.PendingIntent
+import android.content.ComponentName
import android.service.controls.Control
import android.testing.AndroidTestingRunner
import androidx.test.filters.SmallTest
@@ -70,6 +71,7 @@
Control.StatelessBuilder("$idPrefix$it", pendingIntent)
.setZone((it % 3).toString())
.build(),
+ ComponentName("", ""),
it in favoritesIndices
)
}
@@ -195,4 +197,4 @@
verifyNoMoreInteractions(allAdapter, favoritesAdapter)
}
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java
index 9117ea8..f535351 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeScreenBrightnessTest.java
@@ -248,31 +248,6 @@
}
@Test
- public void pausingAod_softBlanks_withSpuriousSensorDuringPause() throws Exception {
- mScreen.transitionTo(UNINITIALIZED, INITIALIZED);
- mScreen.transitionTo(INITIALIZED, DOZE_AOD);
- mScreen.transitionTo(DOZE_AOD, DOZE_AOD_PAUSING);
- mScreen.transitionTo(DOZE_AOD_PAUSING, DOZE_AOD_PAUSED);
-
- reset(mDozeHost);
- mSensor.sendSensorEvent(1);
- verify(mDozeHost).setAodDimmingScrim(eq(1f));
- }
-
- @Test
- public void screenOff_softBlanks() throws Exception {
- mScreen.transitionTo(UNINITIALIZED, INITIALIZED);
- mScreen.transitionTo(INITIALIZED, DOZE_AOD);
- mScreen.transitionTo(DOZE_AOD, DOZE);
- verify(mDozeHost).setAodDimmingScrim(eq(1f));
-
- reset(mDozeHost);
- mScreen.transitionTo(DOZE, DOZE_AOD);
- mSensor.sendSensorEvent(2);
- verify(mDozeHost).setAodDimmingScrim(eq(0f));
- }
-
- @Test
public void pausingAod_unblanksAfterSensor() throws Exception {
mScreen.transitionTo(UNINITIALIZED, INITIALIZED);
mScreen.transitionTo(INITIALIZED, DOZE_AOD);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
index 8320b05..6871aad 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java
@@ -42,6 +42,7 @@
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.classifier.FalsingManagerFake;
import com.android.systemui.dump.DumpManager;
+import com.android.systemui.statusbar.phone.NavigationModeController;
import com.android.systemui.statusbar.phone.NotificationShadeWindowController;
import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
import com.android.systemui.util.DeviceConfigProxy;
@@ -71,6 +72,7 @@
private @Mock DumpManager mDumpManager;
private @Mock PowerManager mPowerManager;
private @Mock TrustManager mTrustManager;
+ private @Mock NavigationModeController mNavigationModeController;
private DeviceConfigProxy mDeviceConfig = new DeviceConfigProxyFake();
private FakeExecutor mUiBgExecutor = new FakeExecutor(new FakeSystemClock());
@@ -88,7 +90,7 @@
mContext, mFalsingManager, mLockPatternUtils, mBroadcastDispatcher,
mNotificationShadeWindowController, () -> mStatusBarKeyguardViewManager,
mDismissCallbackRegistry, mUpdateMonitor, mDumpManager, mUiBgExecutor,
- mPowerManager, mTrustManager, mDeviceConfig);
+ mPowerManager, mTrustManager, mDeviceConfig, mNavigationModeController);
mViewMediator.start();
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/pip/PipAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/pip/PipAnimationControllerTest.java
index 6c09a46..b863f14 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/pip/PipAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/pip/PipAnimationControllerTest.java
@@ -16,9 +16,10 @@
package com.android.systemui.pip;
+import static com.android.systemui.pip.PipAnimationController.TRANSITION_DIRECTION_TO_FULLSCREEN;
+import static com.android.systemui.pip.PipAnimationController.TRANSITION_DIRECTION_TO_PIP;
+
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
@@ -26,7 +27,6 @@
import android.graphics.Rect;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
-import android.view.IWindowContainer;
import android.view.SurfaceControl;
import androidx.test.filters.SmallTest;
@@ -51,22 +51,22 @@
private PipAnimationController mPipAnimationController;
@Mock
- private IWindowContainer mWindowContainer;
+ private SurfaceControl mLeash;
@Mock
private PipAnimationController.PipAnimationCallback mPipAnimationCallback;
@Before
public void setUp() throws Exception {
- mPipAnimationController = new PipAnimationController(mContext);
+ mPipAnimationController = new PipAnimationController(
+ mContext, new PipSurfaceTransactionHelper(mContext));
MockitoAnnotations.initMocks(this);
}
@Test
public void getAnimator_withAlpha_returnFloatAnimator() {
final PipAnimationController.PipTransitionAnimator animator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- new Rect(), 0f, 1f);
+ .getAnimator(mLeash, new Rect(), 0f, 1f);
assertEquals("Expect ANIM_TYPE_ALPHA animation",
animator.getAnimationType(), PipAnimationController.ANIM_TYPE_ALPHA);
@@ -75,8 +75,7 @@
@Test
public void getAnimator_withBounds_returnBoundsAnimator() {
final PipAnimationController.PipTransitionAnimator animator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- new Rect(), new Rect());
+ .getAnimator(mLeash, new Rect(), new Rect());
assertEquals("Expect ANIM_TYPE_BOUNDS animation",
animator.getAnimationType(), PipAnimationController.ANIM_TYPE_BOUNDS);
@@ -88,14 +87,12 @@
final Rect endValue1 = new Rect(100, 100, 200, 200);
final Rect endValue2 = new Rect(200, 200, 300, 300);
final PipAnimationController.PipTransitionAnimator oldAnimator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- startValue, endValue1);
+ .getAnimator(mLeash, startValue, endValue1);
oldAnimator.setSurfaceControlTransactionFactory(DummySurfaceControlTx::new);
oldAnimator.start();
final PipAnimationController.PipTransitionAnimator newAnimator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- startValue, endValue2);
+ .getAnimator(mLeash, startValue, endValue2);
assertEquals("getAnimator with same type returns same animator",
oldAnimator, newAnimator);
@@ -104,26 +101,28 @@
}
@Test
- public void getAnimator_scheduleFinishPip() {
+ public void getAnimator_setTransitionDirection() {
PipAnimationController.PipTransitionAnimator animator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- new Rect(), 0f, 1f);
- assertTrue("scheduleFinishPip is true", animator.shouldScheduleFinishPip());
+ .getAnimator(mLeash, new Rect(), 0f, 1f)
+ .setTransitionDirection(TRANSITION_DIRECTION_TO_PIP);
+ assertEquals("Transition to PiP mode",
+ animator.getTransitionDirection(), TRANSITION_DIRECTION_TO_PIP);
animator = mPipAnimationController
- .getAnimator(mWindowContainer, false /* scheduleFinishPip */,
- new Rect(), 0f, 1f);
- assertFalse("scheduleFinishPip is false", animator.shouldScheduleFinishPip());
+ .getAnimator(mLeash, new Rect(), 0f, 1f)
+ .setTransitionDirection(TRANSITION_DIRECTION_TO_FULLSCREEN);
+ assertEquals("Transition to fullscreen mode",
+ animator.getTransitionDirection(), TRANSITION_DIRECTION_TO_FULLSCREEN);
}
@Test
+ @SuppressWarnings("unchecked")
public void pipTransitionAnimator_updateEndValue() {
final Rect startValue = new Rect(0, 0, 100, 100);
final Rect endValue1 = new Rect(100, 100, 200, 200);
final Rect endValue2 = new Rect(200, 200, 300, 300);
final PipAnimationController.PipTransitionAnimator animator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- startValue, endValue1);
+ .getAnimator(mLeash, startValue, endValue1);
animator.updateEndValue(endValue2);
@@ -135,24 +134,23 @@
final Rect startValue = new Rect(0, 0, 100, 100);
final Rect endValue = new Rect(100, 100, 200, 200);
final PipAnimationController.PipTransitionAnimator animator = mPipAnimationController
- .getAnimator(mWindowContainer, true /* scheduleFinishPip */,
- startValue, endValue);
+ .getAnimator(mLeash, startValue, endValue);
animator.setSurfaceControlTransactionFactory(DummySurfaceControlTx::new);
animator.setPipAnimationCallback(mPipAnimationCallback);
// onAnimationStart triggers onPipAnimationStart
animator.onAnimationStart(animator);
- verify(mPipAnimationCallback).onPipAnimationStart(mWindowContainer, animator);
+ verify(mPipAnimationCallback).onPipAnimationStart(animator);
// onAnimationCancel triggers onPipAnimationCancel
animator.onAnimationCancel(animator);
- verify(mPipAnimationCallback).onPipAnimationCancel(mWindowContainer, animator);
+ verify(mPipAnimationCallback).onPipAnimationCancel(animator);
// onAnimationEnd triggers onPipAnimationEnd
animator.onAnimationEnd(animator);
- verify(mPipAnimationCallback).onPipAnimationEnd(eq(mWindowContainer),
- any(SurfaceControl.Transaction.class), eq(animator));
+ verify(mPipAnimationCallback).onPipAnimationEnd(any(SurfaceControl.Transaction.class),
+ eq(animator));
}
/**
@@ -176,6 +174,11 @@
}
@Override
+ public SurfaceControl.Transaction setCornerRadius(SurfaceControl leash, float radius) {
+ return this;
+ }
+
+ @Override
public void apply() {}
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/pip/PipBoundsHandlerTest.java b/packages/SystemUI/tests/src/com/android/systemui/pip/PipBoundsHandlerTest.java
index b12db2b..0bf0f04 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/pip/PipBoundsHandlerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/pip/PipBoundsHandlerTest.java
@@ -24,6 +24,7 @@
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.testing.TestableResources;
+import android.util.Size;
import android.view.DisplayInfo;
import android.view.Gravity;
@@ -51,6 +52,7 @@
private static final float MIN_ASPECT_RATIO = 0.5f;
private static final float MAX_ASPECT_RATIO = 2f;
private static final Rect EMPTY_CURRENT_BOUNDS = null;
+ private static final Size EMPTY_MINIMAL_SIZE = null;
private PipBoundsHandler mPipBoundsHandler;
private DisplayInfo mDefaultDisplayInfo;
@@ -119,7 +121,7 @@
};
for (float aspectRatio : aspectRatios) {
final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
- aspectRatio, EMPTY_CURRENT_BOUNDS);
+ aspectRatio, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
final float actualAspectRatio =
destinationBounds.width() / (destinationBounds.height() * 1f);
assertEquals("Destination bounds matches the given aspect ratio",
@@ -135,7 +137,7 @@
};
for (float aspectRatio : invalidAspectRatios) {
final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
- aspectRatio, EMPTY_CURRENT_BOUNDS);
+ aspectRatio, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
final float actualAspectRatio =
destinationBounds.width() / (destinationBounds.height() * 1f);
assertEquals("Destination bounds fallbacks to default aspect ratio",
@@ -151,7 +153,7 @@
currentBounds.right = (int) (currentBounds.height() * aspectRatio) + currentBounds.left;
final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
- aspectRatio, currentBounds);
+ aspectRatio, currentBounds, EMPTY_MINIMAL_SIZE);
final float actualAspectRatio =
destinationBounds.width() / (destinationBounds.height() * 1f);
@@ -160,14 +162,58 @@
}
@Test
+ public void getDestinationBounds_withMinSize_returnMinBounds() {
+ final float[] aspectRatios = new float[] {
+ (MIN_ASPECT_RATIO + DEFAULT_ASPECT_RATIO) / 2,
+ DEFAULT_ASPECT_RATIO,
+ (MAX_ASPECT_RATIO + DEFAULT_ASPECT_RATIO) / 2
+ };
+ final Size[] minimalSizes = new Size[] {
+ new Size((int) (100 * aspectRatios[0]), 100),
+ new Size((int) (100 * aspectRatios[1]), 100),
+ new Size((int) (100 * aspectRatios[2]), 100)
+ };
+ for (int i = 0; i < aspectRatios.length; i++) {
+ final float aspectRatio = aspectRatios[i];
+ final Size minimalSize = minimalSizes[i];
+ final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
+ aspectRatio, EMPTY_CURRENT_BOUNDS, minimalSize);
+ assertTrue("Destination bounds is no smaller than minimal requirement",
+ (destinationBounds.width() == minimalSize.getWidth()
+ && destinationBounds.height() >= minimalSize.getHeight())
+ || (destinationBounds.height() == minimalSize.getHeight()
+ && destinationBounds.width() >= minimalSize.getWidth()));
+ final float actualAspectRatio =
+ destinationBounds.width() / (destinationBounds.height() * 1f);
+ assertEquals("Destination bounds matches the given aspect ratio",
+ aspectRatio, actualAspectRatio, ASPECT_RATIO_ERROR_MARGIN);
+ }
+ }
+
+ @Test
+ public void getDestinationBounds_withCurrentBounds_ignoreMinBounds() {
+ final float aspectRatio = (DEFAULT_ASPECT_RATIO + MAX_ASPECT_RATIO) / 2;
+ final Rect currentBounds = new Rect(0, 0, 0, 100);
+ currentBounds.right = (int) (currentBounds.height() * aspectRatio) + currentBounds.left;
+ final Size minSize = new Size(currentBounds.width() / 2, currentBounds.height() / 2);
+
+ final Rect destinationBounds = mPipBoundsHandler.getDestinationBounds(
+ aspectRatio, currentBounds, minSize);
+
+ assertTrue("Destination bounds ignores minimal size",
+ destinationBounds.width() > minSize.getWidth()
+ && destinationBounds.height() > minSize.getHeight());
+ }
+
+ @Test
public void setShelfHeight_offsetBounds() {
final int shelfHeight = 100;
final Rect oldPosition = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
mPipBoundsHandler.setShelfHeight(true, shelfHeight);
final Rect newPosition = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
oldPosition.offset(0, -shelfHeight);
assertBoundsWithMargin("offsetBounds by shelf", oldPosition, newPosition);
@@ -177,11 +223,11 @@
public void onImeVisibilityChanged_offsetBounds() {
final int imeHeight = 100;
final Rect oldPosition = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
mPipBoundsHandler.onImeVisibilityChanged(true, imeHeight);
final Rect newPosition = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
oldPosition.offset(0, -imeHeight);
assertBoundsWithMargin("offsetBounds by IME", oldPosition, newPosition);
@@ -191,13 +237,13 @@
public void onSaveReentryBounds_restoreLastPosition() {
final ComponentName componentName = new ComponentName(mContext, "component1");
final Rect oldPosition = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
oldPosition.offset(0, -100);
mPipBoundsHandler.onSaveReentryBounds(componentName, oldPosition);
final Rect newPosition = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
assertBoundsWithMargin("restoreLastPosition", oldPosition, newPosition);
}
@@ -206,14 +252,14 @@
public void onResetReentryBounds_useDefaultBounds() {
final ComponentName componentName = new ComponentName(mContext, "component1");
final Rect defaultBounds = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
final Rect newBounds = new Rect(defaultBounds);
newBounds.offset(0, -100);
mPipBoundsHandler.onSaveReentryBounds(componentName, newBounds);
mPipBoundsHandler.onResetReentryBounds(componentName);
final Rect actualBounds = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
assertBoundsWithMargin("useDefaultBounds", defaultBounds, actualBounds);
}
@@ -222,14 +268,14 @@
public void onResetReentryBounds_componentMismatch_restoreLastPosition() {
final ComponentName componentName = new ComponentName(mContext, "component1");
final Rect defaultBounds = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
final Rect newBounds = new Rect(defaultBounds);
newBounds.offset(0, -100);
mPipBoundsHandler.onSaveReentryBounds(componentName, newBounds);
mPipBoundsHandler.onResetReentryBounds(new ComponentName(mContext, "component2"));
final Rect actualBounds = mPipBoundsHandler.getDestinationBounds(
- DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS);
+ DEFAULT_ASPECT_RATIO, EMPTY_CURRENT_BOUNDS, EMPTY_MINIMAL_SIZE);
assertBoundsWithMargin("restoreLastPosition", newBounds, actualBounds);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java
index 45c0cdd..ac30421 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSPanelTest.java
@@ -35,6 +35,7 @@
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dump.DumpManager;
@@ -42,6 +43,7 @@
import com.android.systemui.qs.customize.QSCustomizer;
import com.android.systemui.qs.logging.QSLogger;
import com.android.systemui.qs.tileimpl.QSTileImpl;
+import com.android.systemui.statusbar.NotificationMediaManager;
import org.junit.Before;
import org.junit.Test;
@@ -53,6 +55,7 @@
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
+import java.util.concurrent.Executor;
@RunWith(AndroidTestingRunner.class)
@RunWithLooper
@@ -79,6 +82,12 @@
private QSDetail.Callback mCallback;
@Mock
private QSTileView mQSTileView;
+ @Mock
+ private NotificationMediaManager mNotificationMediaManager;
+ @Mock
+ private Executor mBackgroundExecutor;
+ @Mock
+ private LocalBluetoothManager mLocalBluetoothManager;
@Before
public void setup() throws Exception {
@@ -88,7 +97,8 @@
mTestableLooper.runWithLooper(() -> {
mMetricsLogger = mDependency.injectMockDependency(MetricsLogger.class);
mQsPanel = new QSPanel(mContext, null, mDumpManager, mBroadcastDispatcher,
- mQSLogger);
+ mQSLogger, mNotificationMediaManager, mBackgroundExecutor,
+ mLocalBluetoothManager);
// Provides a parent with non-zero size for QSPanel
mParentView = new FrameLayout(mContext);
mParentView.addView(mQsPanel);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
index 0098012..73f3ddd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSTileHostTest.java
@@ -22,7 +22,9 @@
import static junit.framework.TestCase.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -137,6 +139,8 @@
return new TestTile1(mQSTileHost);
} else if ("spec2".equals(spec)) {
return new TestTile2(mQSTileHost);
+ } else if ("na".equals(spec)) {
+ return new NotAvailableTile(mQSTileHost);
} else if (CUSTOM_TILE_SPEC.equals(spec)) {
return mCustomTile;
} else {
@@ -283,6 +287,12 @@
assertEquals(1, specs.size());
}
+ @Test
+ public void testNotAvailableTile_specNotNull() {
+ mQSTileHost.onTuningChanged(QSTileHost.TILES_SETTING, "na");
+ verify(mQSLogger, never()).logTileDestroyed(isNull(), anyString());
+ }
+
private static class TestQSTileHost extends QSTileHost {
TestQSTileHost(Context context, StatusBarIconController iconController,
QSFactoryImpl defaultFactory, Handler mainHandler, Looper bgLooper,
@@ -369,4 +379,16 @@
super(host);
}
}
+
+ private class NotAvailableTile extends TestTile {
+
+ protected NotAvailableTile(QSHost host) {
+ super(host);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return false;
+ }
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
index 7c6da63..cffcabb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/CommandQueueTest.java
@@ -409,11 +409,12 @@
public void testShowAuthenticationDialog() {
Bundle bundle = new Bundle();
String packageName = "test";
+ final long operationId = 1;
mCommandQueue.showAuthenticationDialog(bundle, null /* receiver */, 1, true, 3,
- packageName);
+ packageName, operationId);
waitForIdleSync();
verify(mCallbacks).showAuthenticationDialog(eq(bundle), eq(null), eq(1), eq(true), eq(3),
- eq(packageName));
+ eq(packageName), eq(operationId));
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt
new file mode 100644
index 0000000..f061f34
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2020 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.statusbar
+
+import android.app.WallpaperManager
+import android.testing.AndroidTestingRunner
+import android.testing.TestableLooper.RunWithLooper
+import android.view.Choreographer
+import android.view.View
+import android.view.ViewRootImpl
+import androidx.dynamicanimation.animation.SpringAnimation
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.dump.DumpManager
+import com.android.systemui.plugins.statusbar.StatusBarStateController
+import com.android.systemui.statusbar.phone.BiometricUnlockController
+import com.android.systemui.statusbar.phone.NotificationShadeWindowController
+import com.android.systemui.statusbar.policy.KeyguardStateController
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentCaptor
+import org.mockito.ArgumentMatchers.any
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.Mock
+import org.mockito.Mockito.*
+import org.mockito.junit.MockitoJUnit
+
+@RunWith(AndroidTestingRunner::class)
+@RunWithLooper
+@SmallTest
+class NotificationShadeDepthControllerTest : SysuiTestCase() {
+
+ @Mock private lateinit var statusBarStateController: StatusBarStateController
+ @Mock private lateinit var blurUtils: BlurUtils
+ @Mock private lateinit var biometricUnlockController: BiometricUnlockController
+ @Mock private lateinit var keyguardStateController: KeyguardStateController
+ @Mock private lateinit var choreographer: Choreographer
+ @Mock private lateinit var wallpaperManager: WallpaperManager
+ @Mock private lateinit var notificationShadeWindowController: NotificationShadeWindowController
+ @Mock private lateinit var dumpManager: DumpManager
+ @Mock private lateinit var root: View
+ @Mock private lateinit var viewRootImpl: ViewRootImpl
+ @Mock private lateinit var shadeSpring: SpringAnimation
+ @JvmField @Rule val mockitoRule = MockitoJUnit.rule()
+
+ private lateinit var statusBarStateListener: StatusBarStateController.StateListener
+ private var statusBarState = StatusBarState.SHADE
+ private val maxBlur = 150
+ private lateinit var notificationShadeDepthController: NotificationShadeDepthController
+
+ @Before
+ fun setup() {
+ `when`(root.viewRootImpl).thenReturn(viewRootImpl)
+ `when`(statusBarStateController.state).then { statusBarState }
+ `when`(blurUtils.blurRadiusOfRatio(anyFloat())).then { answer ->
+ (answer.arguments[0] as Float * maxBlur).toInt()
+ }
+ notificationShadeDepthController = NotificationShadeDepthController(
+ statusBarStateController, blurUtils, biometricUnlockController,
+ keyguardStateController, choreographer, wallpaperManager,
+ notificationShadeWindowController, dumpManager)
+ notificationShadeDepthController.shadeSpring = shadeSpring
+ notificationShadeDepthController.root = root
+
+ val captor = ArgumentCaptor.forClass(StatusBarStateController.StateListener::class.java)
+ verify(statusBarStateController).addCallback(captor.capture())
+ statusBarStateListener = captor.value
+ }
+
+ @Test
+ fun setupListeners() {
+ verify(dumpManager).registerDumpable(anyString(), safeEq(notificationShadeDepthController))
+ }
+
+ @Test
+ fun onPanelExpansionChanged_apliesBlur_ifShade() {
+ notificationShadeDepthController.onPanelExpansionChanged(1f /* expansion */,
+ false /* tracking */)
+ verify(shadeSpring).animateToFinalPosition(eq(maxBlur.toFloat()))
+ }
+
+ @Test
+ fun onStateChanged_reevalutesBlurs_ifSameRadiusAndNewState() {
+ onPanelExpansionChanged_apliesBlur_ifShade()
+ clearInvocations(shadeSpring)
+
+ statusBarState = StatusBarState.KEYGUARD
+ statusBarStateListener.onStateChanged(statusBarState)
+ verify(shadeSpring).animateToFinalPosition(eq(0f))
+ }
+
+ @Test
+ fun updateGlobalDialogVisibility_schedulesUpdate() {
+ notificationShadeDepthController.updateGlobalDialogVisibility(0.5f, root)
+ verify(choreographer).postFrameCallback(any())
+ }
+
+ private fun <T : Any> safeEq(value: T): T {
+ return eq(value) ?: value
+ }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java
index fe8b89f..a58000d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/RankingBuilder.java
@@ -55,6 +55,7 @@
private boolean mIsVisuallyInterruptive = false;
private boolean mIsConversation = false;
private ShortcutInfo mShortcutInfo = null;
+ private boolean mIsBubble = false;
public RankingBuilder() {
}
@@ -82,6 +83,7 @@
mIsVisuallyInterruptive = ranking.visuallyInterruptive();
mIsConversation = ranking.isConversation();
mShortcutInfo = ranking.getShortcutInfo();
+ mIsBubble = ranking.isBubble();
}
public Ranking build() {
@@ -108,7 +110,8 @@
mCanBubble,
mIsVisuallyInterruptive,
mIsConversation,
- mShortcutInfo);
+ mShortcutInfo,
+ mIsBubble);
return ranking;
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SbnBuilder.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SbnBuilder.java
index 62f406f..1b0ed11 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/SbnBuilder.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/SbnBuilder.java
@@ -22,6 +22,8 @@
import android.os.UserHandle;
import android.service.notification.StatusBarNotification;
+import com.android.internal.logging.InstanceId;
+
/**
* Convenience builder for {@link StatusBarNotification} since its constructor is terrifying.
*
@@ -40,6 +42,7 @@
private UserHandle mUser = UserHandle.of(0);
private String mOverrideGroupKey;
private long mPostTime;
+ private InstanceId mInstanceId;
public SbnBuilder() {
}
@@ -55,6 +58,7 @@
mUser = source.getUser();
mOverrideGroupKey = source.getOverrideGroupKey();
mPostTime = source.getPostTime();
+ mInstanceId = source.getInstanceId();
}
public StatusBarNotification build() {
@@ -71,7 +75,7 @@
notification.setBubbleMetadata(mBubbleMetadata);
}
- return new StatusBarNotification(
+ StatusBarNotification result = new StatusBarNotification(
mPkg,
mOpPkg,
mId,
@@ -82,6 +86,10 @@
mUser,
mOverrideGroupKey,
mPostTime);
+ if (mInstanceId != null) {
+ result.setInstanceId(mInstanceId);
+ }
+ return result;
}
public SbnBuilder setPkg(String pkg) {
@@ -175,4 +183,9 @@
mBubbleMetadata = data;
return this;
}
+
+ public SbnBuilder setInstanceId(InstanceId instanceId) {
+ mInstanceId = instanceId;
+ return this;
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
index 312bb7f..972357e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/NotificationEntryManagerTest.java
@@ -143,7 +143,7 @@
IMPORTANCE_DEFAULT,
null, null,
null, null, null, true, sentiment, false, -1, false, null, null, false, false,
- false, null);
+ false, null, false);
return true;
}).when(mRankingMap).getRanking(eq(key), any(Ranking.class));
}
@@ -162,7 +162,7 @@
null, null,
null, null, null, true,
Ranking.USER_SENTIMENT_NEUTRAL, false, -1,
- false, smartActions, null, false, false, false, null);
+ false, smartActions, null, false, false, false, null, false);
return true;
}).when(mRankingMap).getRanking(eq(key), any(Ranking.class));
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
index b7184be..82de4a3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotifCollectionTest.java
@@ -34,16 +34,17 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import android.annotation.Nullable;
@@ -83,13 +84,13 @@
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
+import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -123,6 +124,8 @@
private NotifCollection mCollection;
private BatchableNotificationHandler mNotifHandler;
+ private InOrder mListenerInOrder;
+
private NoManSimulator mNoMan;
@Before
@@ -133,6 +136,8 @@
when(mFeatureFlags.isNewNotifPipelineRenderingEnabled()).thenReturn(true);
when(mFeatureFlags.isNewNotifPipelineEnabled()).thenReturn(true);
+ mListenerInOrder = inOrder(mCollectionListener);
+
mCollection = new NotifCollection(
mStatusBarService,
mock(DumpManager.class),
@@ -159,10 +164,12 @@
.setRank(4747));
// THEN the listener is notified
- verify(mCollectionListener).onEntryInit(mEntryCaptor.capture());
- NotificationEntry entry = mEntryCaptor.getValue();
+ final NotificationEntry entry = mCollectionListener.getEntry(notif1.key);
- verify(mCollectionListener).onEntryAdded(entry);
+ mListenerInOrder.verify(mCollectionListener).onEntryInit(entry);
+ mListenerInOrder.verify(mCollectionListener).onEntryAdded(entry);
+ mListenerInOrder.verify(mCollectionListener).onRankingApplied();
+
assertEquals(notif1.key, entry.getKey());
assertEquals(notif1.sbn, entry.getSbn());
assertEquals(notif1.ranking, entry.getRanking());
@@ -215,12 +222,11 @@
assertEquals(entry2.getRanking(), capturedUpdate.getRanking());
// THEN onBuildList is called only once
- verify(mBuildListener).onBuildList(mBuildListCaptor.capture());
- assertEquals(new ArraySet<>(Arrays.asList(
- capturedAdds.get(0),
- capturedAdds.get(1),
- capturedUpdate
- )), new ArraySet<>(mBuildListCaptor.getValue()));
+ verifyBuiltList(
+ List.of(
+ capturedAdds.get(0),
+ capturedAdds.get(1),
+ capturedUpdate));
}
@Test
@@ -234,9 +240,11 @@
.setRank(89));
// THEN the listener is notified
- verify(mCollectionListener).onEntryUpdated(mEntryCaptor.capture());
+ final NotificationEntry entry = mCollectionListener.getEntry(notif2.key);
- NotificationEntry entry = mEntryCaptor.getValue();
+ mListenerInOrder.verify(mCollectionListener).onEntryUpdated(entry);
+ mListenerInOrder.verify(mCollectionListener).onRankingApplied();
+
assertEquals(notif2.key, entry.getKey());
assertEquals(notif2.sbn, entry.getSbn());
assertEquals(notif2.ranking, entry.getRanking());
@@ -256,8 +264,10 @@
mNoMan.retractNotif(notif.sbn, REASON_APP_CANCEL);
// THEN the listener is notified
- verify(mCollectionListener).onEntryRemoved(entry, REASON_APP_CANCEL);
- verify(mCollectionListener).onEntryCleanUp(entry);
+ mListenerInOrder.verify(mCollectionListener).onEntryRemoved(entry, REASON_APP_CANCEL);
+ mListenerInOrder.verify(mCollectionListener).onEntryCleanUp(entry);
+ mListenerInOrder.verify(mCollectionListener).onRankingApplied();
+
assertEquals(notif.sbn, entry.getSbn());
assertEquals(notif.ranking, entry.getRanking());
}
@@ -415,8 +425,8 @@
// THEN the dismissed entry still appears in the notification set
assertEquals(
- new ArraySet<>(Collections.singletonList(entry1)),
- new ArraySet<>(mCollection.getActiveNotifs()));
+ new ArraySet<>(singletonList(entry1)),
+ new ArraySet<>(mCollection.getAllNotifs()));
}
@Test
@@ -444,7 +454,7 @@
mNoMan.retractNotif(notif2.sbn, REASON_CANCEL);
assertEquals(
new ArraySet<>(List.of(entry1, entry2, entry3)),
- new ArraySet<>(mCollection.getActiveNotifs()));
+ new ArraySet<>(mCollection.getAllNotifs()));
// WHEN the summary is dismissed by the user
mCollection.dismissNotification(entry1, defaultStats(entry1));
@@ -452,7 +462,7 @@
// THEN the summary is removed, but both children stick around
assertEquals(
new ArraySet<>(List.of(entry2, entry3)),
- new ArraySet<>(mCollection.getActiveNotifs()));
+ new ArraySet<>(mCollection.getAllNotifs()));
assertEquals(NOT_DISMISSED, entry2.getDismissState());
assertEquals(NOT_DISMISSED, entry3.getDismissState());
}
@@ -561,7 +571,7 @@
}
@Test
- public void testEndDismissInterceptionUpdatesDismissInterceptors() throws RemoteException {
+ public void testEndDismissInterceptionUpdatesDismissInterceptors() {
// GIVEN a collection with notifications with multiple dismiss interceptors
mInterceptor1.shouldInterceptDismissal = true;
mInterceptor2.shouldInterceptDismissal = true;
@@ -592,7 +602,7 @@
@Test(expected = IllegalStateException.class)
- public void testEndingDismissalOfNonInterceptedThrows() throws RemoteException {
+ public void testEndingDismissalOfNonInterceptedThrows() {
// GIVEN a collection with notifications with a dismiss interceptor that hasn't been called
mInterceptor1.shouldInterceptDismissal = false;
mCollection.addNotificationDismissInterceptor(mInterceptor1);
@@ -820,7 +830,7 @@
verify(mExtender3).shouldExtendLifetime(entry2, REASON_CLICK);
// THEN the entry is not removed
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
// THEN the entry properly records all extenders that returned true
assertEquals(Arrays.asList(mExtender1, mExtender2), entry2.mLifetimeExtenders);
@@ -841,7 +851,7 @@
// GIVEN a notification gets lifetime-extended by one of them
mNoMan.retractNotif(notif2.sbn, REASON_APP_CANCEL);
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
clearInvocations(mExtender1, mExtender2, mExtender3);
// WHEN the last active extender expires (but new ones become active)
@@ -856,7 +866,7 @@
verify(mExtender3).shouldExtendLifetime(entry2, REASON_APP_CANCEL);
// THEN the entry is not removed
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
// THEN the entry properly records all extenders that returned true
assertEquals(Arrays.asList(mExtender1, mExtender3), entry2.mLifetimeExtenders);
@@ -878,7 +888,7 @@
// GIVEN a notification gets lifetime-extended by a couple of them
mNoMan.retractNotif(notif2.sbn, REASON_APP_CANCEL);
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
clearInvocations(mExtender1, mExtender2, mExtender3);
// WHEN one (but not all) of the extenders expires
@@ -886,7 +896,7 @@
mExtender2.callback.onEndLifetimeExtension(mExtender2, entry2);
// THEN the entry is not removed
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
// THEN we don't re-query the extenders
verify(mExtender1, never()).shouldExtendLifetime(entry2, REASON_APP_CANCEL);
@@ -894,7 +904,7 @@
verify(mExtender3, never()).shouldExtendLifetime(entry2, REASON_APP_CANCEL);
// THEN the entry properly records all extenders that returned true
- assertEquals(Arrays.asList(mExtender1), entry2.mLifetimeExtenders);
+ assertEquals(singletonList(mExtender1), entry2.mLifetimeExtenders);
}
@Test
@@ -913,7 +923,7 @@
// GIVEN a notification gets lifetime-extended by a couple of them
mNoMan.retractNotif(notif2.sbn, REASON_UNKNOWN);
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
clearInvocations(mExtender1, mExtender2, mExtender3);
// WHEN all of the active extenders expire
@@ -923,7 +933,7 @@
mExtender1.callback.onEndLifetimeExtension(mExtender1, entry2);
// THEN the entry removed
- assertFalse(mCollection.getActiveNotifs().contains(entry2));
+ assertFalse(mCollection.getAllNotifs().contains(entry2));
verify(mCollectionListener).onEntryRemoved(entry2, REASON_UNKNOWN);
}
@@ -943,7 +953,7 @@
// GIVEN a notification gets lifetime-extended by a couple of them
mNoMan.retractNotif(notif2.sbn, REASON_UNKNOWN);
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
clearInvocations(mExtender1, mExtender2, mExtender3);
// WHEN the notification is reposted
@@ -954,7 +964,7 @@
verify(mExtender2).cancelLifetimeExtension(entry2);
// THEN the notification is still present
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
}
@Test(expected = IllegalStateException.class)
@@ -973,7 +983,7 @@
// GIVEN a notification gets lifetime-extended by a couple of them
mNoMan.retractNotif(notif2.sbn, REASON_UNKNOWN);
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
clearInvocations(mExtender1, mExtender2, mExtender3);
// WHEN a lifetime extender makes a reentrant call during cancelLifetimeExtension()
@@ -1002,7 +1012,7 @@
// GIVEN a notification gets lifetime-extended by a couple of them
mNoMan.retractNotif(notif2.sbn, REASON_UNKNOWN);
- assertTrue(mCollection.getActiveNotifs().contains(entry2));
+ assertTrue(mCollection.getAllNotifs().contains(entry2));
clearInvocations(mExtender1, mExtender2, mExtender3);
// WHEN the notification is reposted
@@ -1055,11 +1065,11 @@
// WHEN both notifications are manually dismissed together
mCollection.dismissNotifications(
- List.of(new Pair(entry1, defaultStats(entry1)),
- new Pair(entry2, defaultStats(entry2))));
+ List.of(new Pair<>(entry1, defaultStats(entry1)),
+ new Pair<>(entry2, defaultStats(entry2))));
// THEN build list is only called one time
- verify(mBuildListener).onBuildList(any(Collection.class));
+ verifyBuiltList(List.of(entry1, entry2));
}
@Test
@@ -1074,8 +1084,8 @@
DismissedByUserStats stats1 = defaultStats(entry1);
DismissedByUserStats stats2 = defaultStats(entry2);
mCollection.dismissNotifications(
- List.of(new Pair(entry1, defaultStats(entry1)),
- new Pair(entry2, defaultStats(entry2))));
+ List.of(new Pair<>(entry1, defaultStats(entry1)),
+ new Pair<>(entry2, defaultStats(entry2))));
// THEN we send the dismissals to system server
verify(mStatusBarService).onNotificationClear(
@@ -1109,8 +1119,8 @@
// WHEN both notifications are manually dismissed together
mCollection.dismissNotifications(
- List.of(new Pair(entry1, defaultStats(entry1)),
- new Pair(entry2, defaultStats(entry2))));
+ List.of(new Pair<>(entry1, defaultStats(entry1)),
+ new Pair<>(entry2, defaultStats(entry2))));
// THEN the entries are marked as dismissed
assertEquals(DISMISSED, entry1.getDismissState());
@@ -1134,8 +1144,8 @@
// WHEN both notifications are manually dismissed together
mCollection.dismissNotifications(
- List.of(new Pair(entry1, defaultStats(entry1)),
- new Pair(entry2, defaultStats(entry2))));
+ List.of(new Pair<>(entry1, defaultStats(entry1)),
+ new Pair<>(entry2, defaultStats(entry2))));
// THEN all interceptors get checked
verify(mInterceptor1).shouldInterceptDismissal(entry1);
@@ -1162,7 +1172,7 @@
mCollection.dismissAllNotifications(entry1.getSbn().getUser().getIdentifier());
// THEN build list is only called one time
- verify(mBuildListener).onBuildList(any(Collection.class));
+ verifyBuiltList(List.of(entry1, entry2));
}
@Test
@@ -1271,13 +1281,18 @@
NotificationVisibility.obtain(entry.getKey(), 7, 2, true));
}
- public CollectionEvent postNotif(NotificationEntryBuilder builder) {
+ private CollectionEvent postNotif(NotificationEntryBuilder builder) {
clearInvocations(mCollectionListener);
NotifEvent rawEvent = mNoMan.postNotif(builder);
verify(mCollectionListener).onEntryAdded(mEntryCaptor.capture());
return new CollectionEvent(rawEvent, requireNonNull(mEntryCaptor.getValue()));
}
+ private void verifyBuiltList(Collection<NotificationEntry> list) {
+ verify(mBuildListener).onBuildList(mBuildListCaptor.capture());
+ assertEquals(new ArraySet<>(list), new ArraySet<>(mBuildListCaptor.getValue()));
+ }
+
private static class RecordingCollectionListener implements NotifCollectionListener {
private final Map<String, NotificationEntry> mLastSeenEntries = new ArrayMap<>();
@@ -1303,6 +1318,14 @@
public void onEntryCleanUp(NotificationEntry entry) {
}
+ @Override
+ public void onRankingApplied() {
+ }
+
+ @Override
+ public void onRankingUpdate(RankingMap rankingMap) {
+ }
+
public NotificationEntry getEntry(String key) {
if (!mLastSeenEntries.containsKey(key)) {
throw new RuntimeException("Key not found: " + key);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java
index 92a9080..261dc82 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryBuilder.java
@@ -26,6 +26,7 @@
import android.service.notification.SnoozeCriterion;
import android.service.notification.StatusBarNotification;
+import com.android.internal.logging.InstanceId;
import com.android.systemui.statusbar.RankingBuilder;
import com.android.systemui.statusbar.SbnBuilder;
@@ -141,6 +142,11 @@
return this;
}
+ public NotificationEntryBuilder setInstanceId(InstanceId instanceId) {
+ mSbnBuilder.setInstanceId(instanceId);
+ return this;
+ }
+
/* Delegated to Notification.Builder (via SbnBuilder) */
public NotificationEntryBuilder setContentTitle(Context context, String contentTitle) {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java
index 67b1aad..407e1e6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/ForegroundCoordinatorTest.java
@@ -223,7 +223,7 @@
.setPkg(TEST_PKG)
.setId(2)
.build();
- when(mNotifPipeline.getActiveNotifs()).thenReturn(List.of(entry1, entry2, entry2Other));
+ when(mNotifPipeline.getAllNotifs()).thenReturn(List.of(entry1, entry2, entry2Other));
// GIVEN that entry2 is currently associated with a foreground service
when(mForegroundServiceController.getStandardLayoutKey(0, TEST_PKG))
@@ -253,7 +253,7 @@
.setPkg(TEST_PKG)
.setId(2)
.build();
- when(mNotifPipeline.getActiveNotifs()).thenReturn(List.of(entry));
+ when(mNotifPipeline.getAllNotifs()).thenReturn(List.of(entry));
when(mForegroundServiceController.getStandardLayoutKey(0, TEST_PKG))
.thenReturn(entry.getKey());
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProviderImplTest.java
similarity index 63%
rename from packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
rename to packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProviderImplTest.java
index 1693e7f..f9c62e1 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationInterruptionStateProviderTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/interruption/NotificationInterruptStateProviderImplTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.systemui.statusbar;
+package com.android.systemui.statusbar.notification.interruption;
import static android.app.Notification.FLAG_BUBBLE;
@@ -30,15 +30,14 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Notification;
import android.app.PendingIntent;
-import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.hardware.display.AmbientDisplayConfiguration;
+import android.os.Handler;
import android.os.PowerManager;
import android.os.RemoteException;
import android.service.dreams.IDreamManager;
@@ -50,7 +49,6 @@
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.policy.BatteryController;
@@ -68,7 +66,7 @@
*/
@RunWith(AndroidTestingRunner.class)
@SmallTest
-public class NotificationInterruptionStateProviderTest extends SysuiTestCase {
+public class NotificationInterruptStateProviderImplTest extends SysuiTestCase {
@Mock
PowerManager mPowerManager;
@@ -81,38 +79,36 @@
@Mock
StatusBarStateController mStatusBarStateController;
@Mock
- NotificationPresenter mPresenter;
- @Mock
HeadsUpManager mHeadsUpManager;
@Mock
- NotificationInterruptionStateProvider.HeadsUpSuppressor mHeadsUpSuppressor;
- @Mock
BatteryController mBatteryController;
+ @Mock
+ Handler mMockHandler;
- private NotificationInterruptionStateProvider mNotifInterruptionStateProvider;
+ private NotificationInterruptStateProviderImpl mNotifInterruptionStateProvider;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mNotifInterruptionStateProvider =
- new TestableNotificationInterruptionStateProvider(mContext,
+ new NotificationInterruptStateProviderImpl(
+ mContext.getContentResolver(),
mPowerManager,
mDreamManager,
mAmbientDisplayConfiguration,
mNotificationFilter,
+ mBatteryController,
mStatusBarStateController,
- mBatteryController);
+ mHeadsUpManager,
+ mMockHandler);
- mNotifInterruptionStateProvider.setUpWithPresenter(
- mPresenter,
- mHeadsUpManager,
- mHeadsUpSuppressor);
+ mNotifInterruptionStateProvider.mUseHeadsUp = true;
}
/**
* Sets up the state such that any requests to
- * {@link NotificationInterruptionStateProvider#canAlertCommon(NotificationEntry)} will
+ * {@link NotificationInterruptStateProviderImpl#canAlertCommon(NotificationEntry)} will
* pass as long its provided NotificationEntry fulfills group suppression check.
*/
private void ensureStateForAlertCommon() {
@@ -121,17 +117,16 @@
/**
* Sets up the state such that any requests to
- * {@link NotificationInterruptionStateProvider#canAlertAwakeCommon(NotificationEntry)} will
+ * {@link NotificationInterruptStateProviderImpl#canAlertAwakeCommon(NotificationEntry)} will
* pass as long its provided NotificationEntry fulfills launch fullscreen check.
*/
private void ensureStateForAlertAwakeCommon() {
- when(mPresenter.isDeviceInVrMode()).thenReturn(false);
when(mHeadsUpManager.isSnoozed(any())).thenReturn(false);
}
/**
* Sets up the state such that any requests to
- * {@link NotificationInterruptionStateProvider#shouldHeadsUp(NotificationEntry)} will
+ * {@link NotificationInterruptStateProviderImpl#shouldHeadsUp(NotificationEntry)} will
* pass as long its provided NotificationEntry fulfills importance & DND checks.
*/
private void ensureStateForHeadsUpWhenAwake() throws RemoteException {
@@ -141,12 +136,11 @@
when(mStatusBarStateController.isDozing()).thenReturn(false);
when(mDreamManager.isDreaming()).thenReturn(false);
when(mPowerManager.isScreenOn()).thenReturn(true);
- when(mHeadsUpSuppressor.canHeadsUp(any(), any())).thenReturn(true);
}
/**
* Sets up the state such that any requests to
- * {@link NotificationInterruptionStateProvider#shouldHeadsUp(NotificationEntry)} will
+ * {@link NotificationInterruptStateProviderImpl#shouldHeadsUp(NotificationEntry)} will
* pass as long its provided NotificationEntry fulfills importance & DND checks.
*/
private void ensureStateForHeadsUpWhenDozing() {
@@ -158,7 +152,7 @@
/**
* Sets up the state such that any requests to
- * {@link NotificationInterruptionStateProvider#shouldBubbleUp(NotificationEntry)} will
+ * {@link NotificationInterruptStateProviderImpl#shouldBubbleUp(NotificationEntry)} will
* pass as long its provided NotificationEntry fulfills importance & bubble checks.
*/
private void ensureStateForBubbleUp() {
@@ -166,75 +160,53 @@
ensureStateForAlertAwakeCommon();
}
- /**
- * Ensure that the disabled state is set correctly.
- */
@Test
- public void testDisableNotificationAlerts() {
- // Enabled by default
- assertThat(mNotifInterruptionStateProvider.areNotificationAlertsDisabled()).isFalse();
-
- // Disable alerts
- mNotifInterruptionStateProvider.setDisableNotificationAlerts(true);
- assertThat(mNotifInterruptionStateProvider.areNotificationAlertsDisabled()).isTrue();
-
- // Enable alerts
- mNotifInterruptionStateProvider.setDisableNotificationAlerts(false);
- assertThat(mNotifInterruptionStateProvider.areNotificationAlertsDisabled()).isFalse();
- }
-
- /**
- * Ensure that the disabled alert state effects whether HUNs are enabled.
- */
- @Test
- public void testHunSettingsChange_enabled_butAlertsDisabled() {
- // Set up but without a mock change observer
- mNotifInterruptionStateProvider.setUpWithPresenter(
- mPresenter,
- mHeadsUpManager,
- mHeadsUpSuppressor);
-
- // HUNs enabled by default
- assertThat(mNotifInterruptionStateProvider.getUseHeadsUp()).isTrue();
-
- // Set alerts disabled
- mNotifInterruptionStateProvider.setDisableNotificationAlerts(true);
-
- // No more HUNs
- assertThat(mNotifInterruptionStateProvider.getUseHeadsUp()).isFalse();
- }
-
- /**
- * Alerts can happen.
- */
- @Test
- public void testCanAlertCommon_true() {
- ensureStateForAlertCommon();
+ public void testDefaultSuppressorDoesNotSuppress() {
+ // GIVEN a suppressor without any overrides
+ final NotificationInterruptSuppressor defaultSuppressor =
+ new NotificationInterruptSuppressor() {
+ @Override
+ public String getName() {
+ return "defaultSuppressor";
+ }
+ };
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
- assertThat(mNotifInterruptionStateProvider.canAlertCommon(entry)).isTrue();
+
+ // THEN this suppressor doesn't suppress anything by default
+ assertThat(defaultSuppressor.suppressAwakeHeadsUp(entry)).isFalse();
+ assertThat(defaultSuppressor.suppressAwakeInterruptions(entry)).isFalse();
+ assertThat(defaultSuppressor.suppressInterruptions(entry)).isFalse();
}
- /**
- * Filtered out notifications don't alert.
- */
@Test
- public void testCanAlertCommon_false_filteredOut() {
- ensureStateForAlertCommon();
- when(mNotificationFilter.shouldFilterOut(any())).thenReturn(true);
+ public void testShouldHeadsUpAwake() throws RemoteException {
+ ensureStateForHeadsUpWhenAwake();
- NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
- assertThat(mNotifInterruptionStateProvider.canAlertCommon(entry)).isFalse();
+ NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
+ assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isTrue();
}
- /**
- * Grouped notifications have different alerting behaviours, sometimes the alert for a
- * grouped notification may be suppressed {@link android.app.Notification#GROUP_ALERT_CHILDREN}.
- */
@Test
- public void testCanAlertCommon_false_suppressedForGroups() {
- ensureStateForAlertCommon();
+ public void testShouldNotHeadsUpAwake_flteredOut() throws RemoteException {
+ // GIVEN state for "heads up when awake" is true
+ ensureStateForHeadsUpWhenAwake();
+ // WHEN this entry should be filtered out
+ NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
+ when(mNotificationFilter.shouldFilterOut(entry)).thenReturn(true);
+
+ // THEN we shouldn't heads up this entry
+ assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
+ }
+
+ @Test
+ public void testShouldNotHeadsUp_suppressedForGroups() throws RemoteException {
+ // GIVEN state for "heads up when awake" is true
+ ensureStateForHeadsUpWhenAwake();
+
+ // WHEN the alert for a grouped notification is suppressed
+ // see {@link android.app.Notification#GROUP_ALERT_CHILDREN}
NotificationEntry entry = new NotificationEntryBuilder()
.setPkg("a")
.setOpPkg("a")
@@ -247,40 +219,40 @@
.setImportance(IMPORTANCE_DEFAULT)
.build();
- assertThat(mNotifInterruptionStateProvider.canAlertCommon(entry)).isFalse();
+ // THEN this entry shouldn't HUN
+ assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
- /**
- * HUNs while dozing can happen.
- */
@Test
- public void testShouldHeadsUpWhenDozing_true() {
+ public void testShouldHeadsUpWhenDozing() {
ensureStateForHeadsUpWhenDozing();
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isTrue();
}
- /**
- * Ambient display can show HUNs for new notifications, this may be disabled.
- */
@Test
- public void testShouldHeadsUpWhenDozing_false_pulseDisabled() {
+ public void testShouldNotHeadsUpWhenDozing_pulseDisabled() {
+ // GIVEN state for "heads up when dozing" is true
ensureStateForHeadsUpWhenDozing();
+
+ // WHEN pulsing (HUNs when dozing) is disabled
when(mAmbientDisplayConfiguration.pulseOnNotificationEnabled(anyInt())).thenReturn(false);
+ // THEN this entry shouldn't HUN
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
- /**
- * If the device is not in ambient display or sleeping then we don't HUN.
- */
@Test
- public void testShouldHeadsUpWhenDozing_false_notDozing() {
+ public void testShouldNotHeadsUpWhenDozing_notDozing() {
+ // GIVEN state for "heads up when dozing" is true
ensureStateForHeadsUpWhenDozing();
+
+ // WHEN we're not dozing (in ambient display or sleeping)
when(mStatusBarStateController.isDozing()).thenReturn(false);
+ // THEN this entry shouldn't HUN
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
@@ -290,7 +262,7 @@
* {@link android.app.NotificationManager.Policy#SUPPRESSED_EFFECT_AMBIENT}.
*/
@Test
- public void testShouldHeadsUpWhenDozing_false_suppressingAmbient() {
+ public void testShouldNotHeadsUpWhenDozing_suppressingAmbient() {
ensureStateForHeadsUpWhenDozing();
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
@@ -301,23 +273,18 @@
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
- /**
- * Notifications that are < {@link android.app.NotificationManager#IMPORTANCE_DEFAULT} don't
- * get to pulse.
- */
@Test
- public void testShouldHeadsUpWhenDozing_false_lessImportant() {
+ public void testShouldNotHeadsUpWhenDozing_lessImportant() {
ensureStateForHeadsUpWhenDozing();
+ // Notifications that are < {@link android.app.NotificationManager#IMPORTANCE_DEFAULT} don't
+ // get to pulse
NotificationEntry entry = createNotification(IMPORTANCE_LOW);
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
- /**
- * Heads up can happen.
- */
@Test
- public void testShouldHeadsUp_true() throws RemoteException {
+ public void testShouldHeadsUp() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
@@ -325,38 +292,11 @@
}
/**
- * Heads up notifications can be disabled in general.
- */
- @Test
- public void testShouldHeadsUp_false_noHunsAllowed() throws RemoteException {
- ensureStateForHeadsUpWhenAwake();
-
- // Set alerts disabled, this should cause heads up to be false
- mNotifInterruptionStateProvider.setDisableNotificationAlerts(true);
- assertThat(mNotifInterruptionStateProvider.getUseHeadsUp()).isFalse();
-
- NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
- assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
- }
-
- /**
- * If the device is dozing, we don't show as heads up.
- */
- @Test
- public void testShouldHeadsUp_false_dozing() throws RemoteException {
- ensureStateForHeadsUpWhenAwake();
- when(mStatusBarStateController.isDozing()).thenReturn(true);
-
- NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
- assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
- }
-
- /**
* If the notification is a bubble, and the user is not on AOD / lockscreen, then
* the bubble is shown rather than the heads up.
*/
@Test
- public void testShouldHeadsUp_false_bubble() throws RemoteException {
+ public void testShouldNotHeadsUp_bubble() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
// Bubble bit only applies to interruption when we're in the shade
@@ -369,7 +309,7 @@
* If we're not allowed to alert in general, we shouldn't be shown as heads up.
*/
@Test
- public void testShouldHeadsUp_false_alertCommonFalse() throws RemoteException {
+ public void testShouldNotHeadsUp_filtered() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
// Make canAlertCommon false by saying it's filtered out
when(mNotificationFilter.shouldFilterOut(any())).thenReturn(true);
@@ -383,7 +323,7 @@
* {@link android.app.NotificationManager.Policy#SUPPRESSED_EFFECT_PEEK}.
*/
@Test
- public void testShouldHeadsUp_false_suppressPeek() throws RemoteException {
+ public void testShouldNotHeadsUp_suppressPeek() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
@@ -399,7 +339,7 @@
* to show as a heads up.
*/
@Test
- public void testShouldHeadsUp_false_lessImportant() throws RemoteException {
+ public void testShouldNotHeadsUp_lessImportant() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
@@ -410,7 +350,7 @@
* If the device is not in use then we shouldn't be shown as heads up.
*/
@Test
- public void testShouldHeadsUp_false_deviceNotInUse() throws RemoteException {
+ public void testShouldNotHeadsUp_deviceNotInUse() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
@@ -424,61 +364,58 @@
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
- /**
- * If something wants to suppress this heads up, then it shouldn't be shown as a heads up.
- */
@Test
- public void testShouldHeadsUp_false_suppressed() throws RemoteException {
+ public void testShouldNotHeadsUp_headsUpSuppressed() throws RemoteException {
ensureStateForHeadsUpWhenAwake();
- when(mHeadsUpSuppressor.canHeadsUp(any(), any())).thenReturn(false);
+
+ // If a suppressor is suppressing heads up, then it shouldn't be shown as a heads up.
+ mNotifInterruptionStateProvider.addSuppressor(mSuppressAwakeHeadsUp);
NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
- verify(mHeadsUpSuppressor).canHeadsUp(any(), any());
}
- /**
- * On screen alerts don't happen when the device is in VR Mode.
- */
@Test
- public void testCanAlertAwakeCommon__false_vrMode() {
- ensureStateForAlertAwakeCommon();
- when(mPresenter.isDeviceInVrMode()).thenReturn(true);
+ public void testShouldNotHeadsUpAwake_awakeInterruptsSuppressed() throws RemoteException {
+ ensureStateForHeadsUpWhenAwake();
- NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
- assertThat(mNotifInterruptionStateProvider.canAlertAwakeCommon(entry)).isFalse();
+ // If a suppressor is suppressing heads up, then it shouldn't be shown as a heads up.
+ mNotifInterruptionStateProvider.addSuppressor(mSuppressAwakeInterruptions);
+
+ NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
+ assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
/**
* On screen alerts don't happen when the notification is snoozed.
*/
@Test
- public void testCanAlertAwakeCommon_false_snoozedPackage() {
- ensureStateForAlertAwakeCommon();
- when(mHeadsUpManager.isSnoozed(any())).thenReturn(true);
-
+ public void testShouldNotHeadsUp_snoozedPackage() {
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
- assertThat(mNotifInterruptionStateProvider.canAlertAwakeCommon(entry)).isFalse();
+ ensureStateForAlertAwakeCommon();
+
+ when(mHeadsUpManager.isSnoozed(entry.getSbn().getPackageName())).thenReturn(true);
+
+ assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
- /**
- * On screen alerts don't happen when that package has just launched fullscreen.
- */
+
@Test
- public void testCanAlertAwakeCommon_false_justLaunchedFullscreen() {
+ public void testShouldNotHeadsUp_justLaunchedFullscreen() {
ensureStateForAlertAwakeCommon();
+ // On screen alerts don't happen when that package has just launched fullscreen.
NotificationEntry entry = createNotification(IMPORTANCE_DEFAULT);
entry.notifyFullScreenIntentLaunched();
- assertThat(mNotifInterruptionStateProvider.canAlertAwakeCommon(entry)).isFalse();
+ assertThat(mNotifInterruptionStateProvider.shouldHeadsUp(entry)).isFalse();
}
/**
* Bubbles can happen.
*/
@Test
- public void testShouldBubbleUp_true() {
+ public void testShouldBubbleUp() {
ensureStateForBubbleUp();
assertThat(mNotifInterruptionStateProvider.shouldBubbleUp(createBubble())).isTrue();
}
@@ -487,7 +424,7 @@
* If the notification doesn't have permission to bubble, it shouldn't bubble.
*/
@Test
- public void shouldBubbleUp_false_notAllowedToBubble() {
+ public void shouldNotBubbleUp_notAllowedToBubble() {
ensureStateForBubbleUp();
NotificationEntry entry = createBubble();
@@ -502,7 +439,7 @@
* If the notification isn't a bubble, it should definitely not show as a bubble.
*/
@Test
- public void shouldBubbleUp_false_notABubble() {
+ public void shouldNotBubbleUp_notABubble() {
ensureStateForBubbleUp();
NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
@@ -517,7 +454,7 @@
* If the notification doesn't have bubble metadata, it shouldn't bubble.
*/
@Test
- public void shouldBubbleUp_false_invalidMetadata() {
+ public void shouldNotBubbleUp_invalidMetadata() {
ensureStateForBubbleUp();
NotificationEntry entry = createNotification(IMPORTANCE_HIGH);
@@ -529,24 +466,18 @@
assertThat(mNotifInterruptionStateProvider.shouldBubbleUp(entry)).isFalse();
}
- /**
- * If the notification can't heads up in general, it shouldn't bubble.
- */
@Test
- public void shouldBubbleUp_false_alertAwakeCommonFalse() {
+ public void shouldNotBubbleUp_suppressedInterruptions() {
ensureStateForBubbleUp();
- // Make alert common return false by pretending we're in VR mode
- when(mPresenter.isDeviceInVrMode()).thenReturn(true);
+ // If the notification can't heads up in general, it shouldn't bubble.
+ mNotifInterruptionStateProvider.addSuppressor(mSuppressInterruptions);
assertThat(mNotifInterruptionStateProvider.shouldBubbleUp(createBubble())).isFalse();
}
- /**
- * If the notification can't heads up in general, it shouldn't bubble.
- */
@Test
- public void shouldBubbleUp_false_alertCommonFalse() {
+ public void shouldNotBubbleUp_filteredOut() {
ensureStateForBubbleUp();
// Make canAlertCommon false by saying it's filtered out
@@ -592,20 +523,45 @@
.build();
}
- /**
- * Testable class overriding constructor.
- */
- public static class TestableNotificationInterruptionStateProvider extends
- NotificationInterruptionStateProvider {
-
- TestableNotificationInterruptionStateProvider(Context context,
- PowerManager powerManager, IDreamManager dreamManager,
- AmbientDisplayConfiguration ambientDisplayConfiguration,
- NotificationFilter notificationFilter,
- StatusBarStateController statusBarStateController,
- BatteryController batteryController) {
- super(context, powerManager, dreamManager, ambientDisplayConfiguration,
- notificationFilter, batteryController, statusBarStateController);
+ private final NotificationInterruptSuppressor
+ mSuppressAwakeHeadsUp =
+ new NotificationInterruptSuppressor() {
+ @Override
+ public String getName() {
+ return "suppressAwakeHeadsUp";
}
- }
+
+ @Override
+ public boolean suppressAwakeHeadsUp(NotificationEntry entry) {
+ return true;
+ }
+ };
+
+ private final NotificationInterruptSuppressor
+ mSuppressAwakeInterruptions =
+ new NotificationInterruptSuppressor() {
+ @Override
+ public String getName() {
+ return "suppressAwakeInterruptions";
+ }
+
+ @Override
+ public boolean suppressAwakeInterruptions(NotificationEntry entry) {
+ return true;
+ }
+ };
+
+ private final NotificationInterruptSuppressor
+ mSuppressInterruptions =
+ new NotificationInterruptSuppressor() {
+ @Override
+ public String getName() {
+ return "suppressInterruptions";
+ }
+
+ @Override
+ public boolean suppressInterruptions(NotificationEntry entry) {
+ return true;
+ }
+ };
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
index d826ce1..d39b2c2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationLoggerTest.java
@@ -16,7 +16,10 @@
package com.android.systemui.statusbar.notification.logging;
+import static com.android.systemui.statusbar.notification.stack.NotificationSectionsManager.BUCKET_ALERTING;
+
import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
@@ -34,6 +37,7 @@
import androidx.test.filters.SmallTest;
+import com.android.internal.logging.InstanceId;
import com.android.internal.statusbar.IStatusBarService;
import com.android.internal.statusbar.NotificationVisibility;
import com.android.systemui.SysuiTestCase;
@@ -43,6 +47,7 @@
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.logging.nano.Notifications;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
import com.android.systemui.util.concurrency.FakeExecutor;
@@ -81,9 +86,10 @@
private NotificationEntry mEntry;
private TestableNotificationLogger mLogger;
- private NotificationEntryListener mNotificationEntryListener;
private ConcurrentLinkedQueue<AssertionError> mErrorQueue = new ConcurrentLinkedQueue<>();
private FakeExecutor mUiBgExecutor = new FakeExecutor(new FakeSystemClock());
+ private NotificationPanelLoggerFake mNotificationPanelLoggerFake =
+ new NotificationPanelLoggerFake();
@Before
public void setUp() {
@@ -97,6 +103,7 @@
.setUid(TEST_UID)
.setNotification(new Notification())
.setUser(UserHandle.CURRENT)
+ .setInstanceId(InstanceId.fakeInstanceId(1))
.build();
mEntry.setRow(mRow);
@@ -105,7 +112,6 @@
mExpansionStateLogger);
mLogger.setUpWithContainer(mListContainer);
verify(mEntryManager).addNotificationEntryListener(mEntryListenerCaptor.capture());
- mNotificationEntryListener = mEntryListenerCaptor.getValue();
}
@Test
@@ -164,6 +170,41 @@
verify(mBarService, times(1)).onNotificationVisibilityChanged(any(), any());
}
+ @Test
+ public void testLogPanelShownOnLoggingStart() {
+ when(mEntryManager.getVisibleNotifications()).thenReturn(Lists.newArrayList(mEntry));
+ mLogger.startNotificationLogging();
+ assertEquals(1, mNotificationPanelLoggerFake.getCalls().size());
+ assertEquals(false, mNotificationPanelLoggerFake.get(0).isLockscreen);
+ assertEquals(1, mNotificationPanelLoggerFake.get(0).list.notifications.length);
+ Notifications.Notification n = mNotificationPanelLoggerFake.get(0).list.notifications[0];
+ assertEquals(TEST_PACKAGE_NAME, n.packageName);
+ assertEquals(TEST_UID, n.uid);
+ assertEquals(1, n.instanceId);
+ assertEquals(false, n.isGroupSummary);
+ assertEquals(1 + BUCKET_ALERTING, n.section);
+ }
+
+ @Test
+ public void testLogPanelShownHandlesNullInstanceIds() {
+ // Construct a NotificationEntry like mEntry, but with a null instance id.
+ NotificationEntry entry = new NotificationEntryBuilder()
+ .setPkg(TEST_PACKAGE_NAME)
+ .setOpPkg(TEST_PACKAGE_NAME)
+ .setUid(TEST_UID)
+ .setNotification(new Notification())
+ .setUser(UserHandle.CURRENT)
+ .build();
+ entry.setRow(mRow);
+
+ when(mEntryManager.getVisibleNotifications()).thenReturn(Lists.newArrayList(entry));
+ mLogger.startNotificationLogging();
+ assertEquals(1, mNotificationPanelLoggerFake.getCalls().size());
+ assertEquals(1, mNotificationPanelLoggerFake.get(0).list.notifications.length);
+ Notifications.Notification n = mNotificationPanelLoggerFake.get(0).list.notifications[0];
+ assertEquals(0, n.instanceId);
+ }
+
private class TestableNotificationLogger extends NotificationLogger {
TestableNotificationLogger(NotificationListener notificationListener,
@@ -173,7 +214,7 @@
IStatusBarService barService,
ExpansionStateLogger expansionStateLogger) {
super(notificationListener, uiBgExecutor, entryManager, statusBarStateController,
- expansionStateLogger);
+ expansionStateLogger, mNotificationPanelLoggerFake);
mBarService = barService;
// Make this on the current thread so we can wait for it during tests.
mHandler = Handler.createAsync(Looper.myLooper());
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLoggerFake.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLoggerFake.java
new file mode 100644
index 0000000..7e97629
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/logging/NotificationPanelLoggerFake.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2020 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.statusbar.notification.logging;
+
+import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.logging.nano.Notifications;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class NotificationPanelLoggerFake implements NotificationPanelLogger {
+ private List<CallRecord> mCalls = new ArrayList<>();
+
+ List<CallRecord> getCalls() {
+ return mCalls;
+ }
+
+ CallRecord get(int index) {
+ return mCalls.get(index);
+ }
+
+ @Override
+ public void logPanelShown(boolean isLockscreen,
+ List<NotificationEntry> visibleNotifications) {
+ mCalls.add(new CallRecord(isLockscreen,
+ NotificationPanelLogger.toNotificationProto(visibleNotifications)));
+ }
+
+ public static class CallRecord {
+ public boolean isLockscreen;
+ public Notifications.NotificationList list;
+ CallRecord(boolean isLockscreen, Notifications.NotificationList list) {
+ this.isLockscreen = isLockscreen;
+ this.list = list;
+ }
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
index e960185..c356e0d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java
@@ -329,10 +329,10 @@
@Test
public void testIconScrollXAfterTranslationAndReset() throws Exception {
mGroupRow.setTranslation(50);
- assertEquals(50, -mGroupRow.getEntry().expandedIcon.getScrollX());
+ assertEquals(50, -mGroupRow.getEntry().getIcons().getShelfIcon().getScrollX());
mGroupRow.resetTranslation();
- assertEquals(0, mGroupRow.getEntry().expandedIcon.getScrollX());
+ assertEquals(0, mGroupRow.getEntry().getIcons().getShelfIcon().getScrollX());
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java
index 5d0349d..2e787ce 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationEntryManagerInflationTest.java
@@ -28,6 +28,7 @@
import static org.mockito.Mockito.when;
import android.app.Notification;
+import android.content.pm.LauncherApps;
import android.os.Handler;
import android.service.notification.NotificationListenerService;
import android.service.notification.NotificationListenerService.Ranking;
@@ -56,12 +57,14 @@
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationEntryManagerLogger;
import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.NotificationSectionsFeatureManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationRankingManager;
import com.android.systemui.statusbar.notification.collection.inflation.NotificationRowBinderImpl;
import com.android.systemui.statusbar.notification.collection.provider.HighPriorityProvider;
+import com.android.systemui.statusbar.notification.icon.IconBuilder;
+import com.android.systemui.statusbar.notification.icon.IconManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
import com.android.systemui.statusbar.notification.people.PeopleNotificationIdentifier;
import com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.InflationFlag;
@@ -108,7 +111,7 @@
@Mock private NotificationEntryListener mEntryListener;
@Mock private NotificationRowBinderImpl.BindRowCallback mBindCallback;
@Mock private HeadsUpManager mHeadsUpManager;
- @Mock private NotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+ @Mock private NotificationInterruptStateProvider mNotificationInterruptionStateProvider;
@Mock private NotificationLockscreenUserManager mLockscreenUserManager;
@Mock private NotificationGutsManager mGutsManager;
@Mock private NotificationRemoteInputManager mRemoteInputManager;
@@ -245,14 +248,13 @@
mLockscreenUserManager,
pipeline,
stage,
- true, /* allowLongPress */
- mock(KeyguardBypassController.class),
- mock(StatusBarStateController.class),
- mGroupManager,
- mGutsManager,
mNotificationInterruptionStateProvider,
RowInflaterTask::new,
- mExpandableNotificationRowComponentBuilder);
+ mExpandableNotificationRowComponentBuilder,
+ new IconManager(
+ mEntryManager,
+ mock(LauncherApps.class),
+ new IconBuilder(mContext)));
mEntryManager.setUpWithPresenter(mPresenter);
mEntryManager.addNotificationEntryListener(mEntryListener);
@@ -284,7 +286,8 @@
false,
false,
false,
- null);
+ null,
+ false);
mRankingMap = new NotificationListenerService.RankingMap(new Ranking[] {ranking});
TestableLooper.get(this).processAllMessages();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
index 54c0bde..e9dca699 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationGutsManagerTest.java
@@ -316,74 +316,9 @@
}
@Test
- public void testInitializeNotificationInfoView_showBlockingHelper() throws Exception {
- NotificationInfo notificationInfoView = mock(NotificationInfo.class);
- ExpandableNotificationRow row = spy(mHelper.createRow());
- row.setBlockingHelperShowing(true);
- modifyRanking(row.getEntry())
- .setUserSentiment(USER_SENTIMENT_NEGATIVE)
- .build();
- when(row.getIsNonblockable()).thenReturn(false);
- StatusBarNotification statusBarNotification = row.getEntry().getSbn();
- NotificationEntry entry = row.getEntry();
-
- mGutsManager.initializeNotificationInfo(row, notificationInfoView);
-
- verify(notificationInfoView).bindNotification(
- any(PackageManager.class),
- any(INotificationManager.class),
- eq(mVisualStabilityManager),
- eq(statusBarNotification.getPackageName()),
- any(NotificationChannel.class),
- anySet(),
- eq(entry),
- any(NotificationInfo.CheckSaveListener.class),
- any(NotificationInfo.OnSettingsClickListener.class),
- any(NotificationInfo.OnAppSettingsClickListener.class),
- eq(false),
- eq(false),
- eq(true) /* isForBlockingHelper */,
- eq(0),
- eq(false) /* wasShownHighPriority */);
- }
-
- @Test
- public void testInitializeNotificationInfoView_dontShowBlockingHelper() throws Exception {
- NotificationInfo notificationInfoView = mock(NotificationInfo.class);
- ExpandableNotificationRow row = spy(mHelper.createRow());
- row.setBlockingHelperShowing(false);
- modifyRanking(row.getEntry())
- .setUserSentiment(USER_SENTIMENT_NEGATIVE)
- .build();
- when(row.getIsNonblockable()).thenReturn(false);
- StatusBarNotification statusBarNotification = row.getEntry().getSbn();
- NotificationEntry entry = row.getEntry();
-
- mGutsManager.initializeNotificationInfo(row, notificationInfoView);
-
- verify(notificationInfoView).bindNotification(
- any(PackageManager.class),
- any(INotificationManager.class),
- eq(mVisualStabilityManager),
- eq(statusBarNotification.getPackageName()),
- any(NotificationChannel.class),
- anySet(),
- eq(entry),
- any(NotificationInfo.CheckSaveListener.class),
- any(NotificationInfo.OnSettingsClickListener.class),
- any(NotificationInfo.OnAppSettingsClickListener.class),
- eq(false),
- eq(false),
- eq(false) /* isForBlockingHelper */,
- eq(0),
- eq(false) /* wasShownHighPriority */);
- }
-
- @Test
public void testInitializeNotificationInfoView_highPriority() throws Exception {
NotificationInfo notificationInfoView = mock(NotificationInfo.class);
ExpandableNotificationRow row = spy(mHelper.createRow());
- row.setBlockingHelperShowing(true);
final NotificationEntry entry = row.getEntry();
modifyRanking(entry)
.setUserSentiment(USER_SENTIMENT_NEGATIVE)
@@ -403,13 +338,10 @@
any(NotificationChannel.class),
anySet(),
eq(entry),
- any(NotificationInfo.CheckSaveListener.class),
any(NotificationInfo.OnSettingsClickListener.class),
any(NotificationInfo.OnAppSettingsClickListener.class),
eq(false),
eq(false),
- eq(true) /* isForBlockingHelper */,
- eq(IMPORTANCE_HIGH),
eq(true) /* wasShownHighPriority */);
}
@@ -437,13 +369,10 @@
any(NotificationChannel.class),
anySet(),
eq(entry),
- any(NotificationInfo.CheckSaveListener.class),
any(NotificationInfo.OnSettingsClickListener.class),
any(NotificationInfo.OnAppSettingsClickListener.class),
eq(true),
eq(false),
- eq(false) /* isForBlockingHelper */,
- eq(0),
eq(false) /* wasShownHighPriority */);
}
@@ -469,13 +398,10 @@
any(NotificationChannel.class),
anySet(),
eq(entry),
- any(NotificationInfo.CheckSaveListener.class),
any(NotificationInfo.OnSettingsClickListener.class),
any(NotificationInfo.OnAppSettingsClickListener.class),
eq(false),
eq(false),
- eq(true) /* isForBlockingHelper */,
- eq(0),
eq(false) /* wasShownHighPriority */);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
index c62487a..98ef691 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationInfoTest.java
@@ -119,15 +119,10 @@
@Mock
private PackageManager mMockPackageManager;
@Mock
- private NotificationBlockingHelperManager mBlockingHelperManager;
- @Mock
private VisualStabilityManager mVisualStabilityManager;
@Before
public void setUp() throws Exception {
- mDependency.injectTestDependency(
- NotificationBlockingHelperManager.class,
- mBlockingHelperManager);
mTestableLooper = TestableLooper.get(this);
mDependency.injectTestDependency(Dependency.BG_LOOPER, mTestableLooper.getLooper());
@@ -183,13 +178,6 @@
NOTIFICATION_NEW_INTERRUPTION_MODEL, 0);
}
- // TODO: if tests are taking too long replace this with something that makes the animation
- // finish instantly.
- private void waitForUndoButton() {
- PollingCheck.waitFor(1000,
- () -> VISIBLE == mNotificationInfo.findViewById(R.id.confirmation).getVisibility());
- }
-
@Test
public void testBindNotification_SetsTextApplicationName() throws Exception {
when(mMockPackageManager.getApplicationLabel(any())).thenReturn("App Name");
@@ -203,12 +191,10 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
- final TextView textView = mNotificationInfo.findViewById(R.id.pkgname);
+ final TextView textView = mNotificationInfo.findViewById(R.id.pkg_name);
assertTrue(textView.getText().toString().contains("App Name"));
assertEquals(VISIBLE, mNotificationInfo.findViewById(R.id.header).getVisibility());
}
@@ -228,12 +214,10 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
- final ImageView iconView = mNotificationInfo.findViewById(R.id.pkgicon);
+ final ImageView iconView = mNotificationInfo.findViewById(R.id.pkg_icon);
assertEquals(iconDrawable, iconView.getDrawable());
}
@@ -249,14 +233,12 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView nameView = mNotificationInfo.findViewById(R.id.delegate_name);
assertEquals(GONE, nameView.getVisibility());
- final TextView dividerView = mNotificationInfo.findViewById(R.id.pkg_divider);
+ final TextView dividerView = mNotificationInfo.findViewById(R.id.group_divider);
assertEquals(GONE, dividerView.getVisibility());
}
@@ -281,16 +263,12 @@
entry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView nameView = mNotificationInfo.findViewById(R.id.delegate_name);
assertEquals(VISIBLE, nameView.getVisibility());
assertTrue(nameView.getText().toString().contains("Proxied"));
- final TextView dividerView = mNotificationInfo.findViewById(R.id.pkg_divider);
- assertEquals(VISIBLE, dividerView.getVisibility());
}
@Test
@@ -305,13 +283,13 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView groupNameView = mNotificationInfo.findViewById(R.id.group_name);
assertEquals(GONE, groupNameView.getVisibility());
+ final TextView dividerView = mNotificationInfo.findViewById(R.id.group_divider);
+ assertEquals(GONE, dividerView.getVisibility());
}
@Test
@@ -332,14 +310,14 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView groupNameView = mNotificationInfo.findViewById(R.id.group_name);
assertEquals(View.VISIBLE, groupNameView.getVisibility());
assertEquals("Test Group Name", groupNameView.getText());
+ final TextView dividerView = mNotificationInfo.findViewById(R.id.group_divider);
+ assertEquals(View.VISIBLE, dividerView.getVisibility());
}
@Test
@@ -354,10 +332,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView textView = mNotificationInfo.findViewById(R.id.channel_name);
assertEquals(TEST_CHANNEL_NAME, textView.getText());
@@ -375,10 +351,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView textView = mNotificationInfo.findViewById(R.id.channel_name);
assertEquals(GONE, textView.getVisibility());
@@ -387,7 +361,7 @@
@Test
public void testBindNotification_DefaultChannelUsesChannelNameIfMoreChannelsExist()
throws Exception {
- // Package has one channel by default.
+ // Package has more than one channel by default.
when(mMockINotificationManager.getNumNotificationChannelsForPackage(
eq(TEST_PACKAGE_NAME), eq(TEST_UID), anyBoolean())).thenReturn(10);
mNotificationInfo.bindNotification(
@@ -400,10 +374,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView textView = mNotificationInfo.findViewById(R.id.channel_name);
assertEquals(VISIBLE, textView.getVisibility());
@@ -421,42 +393,14 @@
mEntry,
null,
null,
- null,
true,
true,
- IMPORTANCE_DEFAULT,
true);
final TextView textView = mNotificationInfo.findViewById(R.id.channel_name);
assertEquals(VISIBLE, textView.getVisibility());
}
@Test
- public void testBindNotification_BlockLink_BlockingHelper() throws Exception {
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet,
- mEntry,
- null,
- mock(NotificationInfo.OnSettingsClickListener.class),
- null,
- true,
- false,
- true /* isBlockingHelper */,
- IMPORTANCE_DEFAULT,
- true);
- final View block =
- mNotificationInfo.findViewById(R.id.blocking_helper_turn_off_notifications);
- final View interruptivenessSettings = mNotificationInfo.findViewById(
- R.id.inline_controls);
- assertEquals(VISIBLE, block.getVisibility());
- assertEquals(GONE, interruptivenessSettings.getVisibility());
- }
-
- @Test
public void testBindNotification_SetsOnClickListenerForSettings() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
mNotificationInfo.bindNotification(
@@ -467,7 +411,6 @@
mNotificationChannel,
mNotificationChannelSet,
mEntry,
- null,
(View v, NotificationChannel c, int appUid) -> {
assertEquals(mNotificationChannel, c);
latch.countDown();
@@ -475,7 +418,6 @@
null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final View settingsButton = mNotificationInfo.findViewById(R.id.info);
@@ -496,10 +438,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final View settingsButton = mNotificationInfo.findViewById(R.id.info);
assertTrue(settingsButton.getVisibility() != View.VISIBLE);
@@ -516,14 +456,12 @@
mNotificationChannel,
mNotificationChannelSet,
mEntry,
- null,
(View v, NotificationChannel c, int appUid) -> {
assertEquals(mNotificationChannel, c);
},
null,
false,
false,
- IMPORTANCE_DEFAULT,
true);
final View settingsButton = mNotificationInfo.findViewById(R.id.info);
assertTrue(settingsButton.getVisibility() != View.VISIBLE);
@@ -541,10 +479,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
mNotificationInfo.bindNotification(
mMockPackageManager,
@@ -554,89 +490,16 @@
mNotificationChannel,
mNotificationChannelSet,
mEntry,
- null,
(View v, NotificationChannel c, int appUid) -> { },
null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final View settingsButton = mNotificationInfo.findViewById(R.id.info);
assertEquals(View.VISIBLE, settingsButton.getVisibility());
}
@Test
- public void testBindNotificationLogging_notBlockingHelper() throws Exception {
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet,
- mEntry,
- null,
- null,
- null,
- true,
- false,
- IMPORTANCE_DEFAULT,
- true);
- verify(mMetricsLogger).write(argThat(logMaker ->
- logMaker.getCategory() == MetricsEvent.ACTION_NOTE_CONTROLS
- && logMaker.getType() == MetricsEvent.TYPE_OPEN
- && logMaker.getSubtype() == MetricsEvent.BLOCKING_HELPER_UNKNOWN
- ));
- }
-
- @Test
- public void testBindNotificationLogging_BlockingHelper() throws Exception {
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet,
- mEntry,
- null,
- null,
- null,
- false,
- true,
- true,
- IMPORTANCE_DEFAULT,
- true);
- verify(mMetricsLogger).write(argThat(logMaker ->
- logMaker.getCategory() == MetricsEvent.ACTION_NOTE_CONTROLS
- && logMaker.getType() == MetricsEvent.TYPE_OPEN
- && logMaker.getSubtype() == MetricsEvent.BLOCKING_HELPER_DISPLAY
- ));
- }
-
- @Test
- public void testLogBlockingHelperCounter_logsForBlockingHelper() throws Exception {
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet,
- mEntry,
- null,
- null,
- null,
- false,
- true,
- true,
- IMPORTANCE_DEFAULT,
- true);
- mNotificationInfo.logBlockingHelperCounter("HowCanNotifsBeRealIfAppsArent");
- verify(mMetricsLogger).count(eq("HowCanNotifsBeRealIfAppsArent"), eq(1));
- }
-
- @Test
public void testOnClickListenerPassesNullChannelForBundle() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
mNotificationInfo.bindNotification(
@@ -646,7 +509,6 @@
TEST_PACKAGE_NAME, mNotificationChannel,
createMultipleChannelSet(MULTIPLE_CHANNEL_COUNT),
mEntry,
- null,
(View v, NotificationChannel c, int appUid) -> {
assertEquals(null, c);
latch.countDown();
@@ -654,7 +516,6 @@
null,
true,
true,
- IMPORTANCE_DEFAULT,
true);
mNotificationInfo.findViewById(R.id.info).performClick();
@@ -676,10 +537,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
final TextView channelNameView =
mNotificationInfo.findViewById(R.id.channel_name);
@@ -699,10 +558,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
assertEquals(GONE, mNotificationInfo.findViewById(
R.id.interruptiveness_settings).getVisibility());
@@ -722,10 +579,8 @@
mEntry,
null,
null,
- null,
true,
true,
- IMPORTANCE_DEFAULT,
true);
final TextView view = mNotificationInfo.findViewById(R.id.non_configurable_text);
assertEquals(View.VISIBLE, view.getVisibility());
@@ -747,10 +602,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
assertTrue(mNotificationInfo.findViewById(R.id.alert).isSelected());
}
@@ -767,10 +620,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
false);
assertTrue(mNotificationInfo.findViewById(R.id.silence).isSelected());
}
@@ -787,10 +638,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
mTestableLooper.processAllMessages();
verify(mMockINotificationManager, never()).updateNotificationChannelForPackage(
@@ -810,10 +659,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_LOW,
false);
mNotificationInfo.findViewById(R.id.alert).performClick();
@@ -836,10 +683,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
mNotificationInfo.findViewById(R.id.silence).performClick();
@@ -862,10 +707,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
mNotificationInfo.handleCloseControls(true, false);
@@ -889,10 +732,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_UNSPECIFIED,
true);
mNotificationInfo.handleCloseControls(true, false);
@@ -904,225 +745,6 @@
}
@Test
- public void testCloseControls_nonNullCheckSaveListenerDoesntDelayKeepShowing_BlockingHelper()
- throws Exception {
- NotificationInfo.CheckSaveListener listener =
- mock(NotificationInfo.CheckSaveListener.class);
- mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel /* notificationChannel */,
- createMultipleChannelSet(10) /* numUniqueChannelsInRow */,
- mEntry,
- listener /* checkSaveListener */,
- null /* onSettingsClick */,
- null /* onAppSettingsClick */,
- true /* provisioned */,
- false /* isNonblockable */,
- true /* isForBlockingHelper */,
- IMPORTANCE_DEFAULT,
- true);
-
- NotificationGuts guts = spy(new NotificationGuts(mContext, null));
- when(guts.getWindowToken()).thenReturn(mock(IBinder.class));
- doNothing().when(guts).animateClose(anyInt(), anyInt(), anyBoolean());
- doNothing().when(guts).setExposed(anyBoolean(), anyBoolean());
- guts.setGutsContent(mNotificationInfo);
- mNotificationInfo.setGutsParent(guts);
-
- mNotificationInfo.findViewById(R.id.keep_showing).performClick();
-
- verify(mBlockingHelperManager).dismissCurrentBlockingHelper();
- mTestableLooper.processAllMessages();
- verify(mMockINotificationManager, times(1))
- .setNotificationsEnabledWithImportanceLockForPackage(
- anyString(), eq(TEST_UID), eq(true));
- }
-
- @Test
- public void testCloseControls_nonNullCheckSaveListenerDoesntDelayDismiss_BlockingHelper()
- throws Exception {
- NotificationInfo.CheckSaveListener listener =
- mock(NotificationInfo.CheckSaveListener.class);
- mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel /* notificationChannel */,
- createMultipleChannelSet(10) /* numUniqueChannelsInRow */,
- mEntry,
- listener /* checkSaveListener */,
- null /* onSettingsClick */,
- null /* onAppSettingsClick */,
- false /* isNonblockable */,
- true /* isForBlockingHelper */,
- true, IMPORTANCE_DEFAULT,
- true);
-
- mNotificationInfo.handleCloseControls(true /* save */, false /* force */);
-
- mTestableLooper.processAllMessages();
- verify(listener, times(0)).checkSave(any(Runnable.class), eq(mSbn));
- }
-
- @Test
- public void testCloseControls_checkSaveListenerDelaysStopNotifications_BlockingHelper()
- throws Exception {
- NotificationInfo.CheckSaveListener listener =
- mock(NotificationInfo.CheckSaveListener.class);
- mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel /* notificationChannel */,
- createMultipleChannelSet(10) /* numUniqueChannelsInRow */,
- mEntry,
- listener /* checkSaveListener */,
- null /* onSettingsClick */,
- null /* onAppSettingsClick */,
- true /* provisioned */,
- false /* isNonblockable */,
- true /* isForBlockingHelper */,
- IMPORTANCE_DEFAULT,
- true);
-
- mNotificationInfo.findViewById(R.id.deliver_silently).performClick();
- mTestableLooper.processAllMessages();
- verify(listener).checkSave(any(Runnable.class), eq(mSbn));
- }
-
- @Test
- public void testCloseControls_blockingHelperDismissedIfShown() throws Exception {
- mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet /* numChannels */,
- mEntry,
- null /* checkSaveListener */,
- null /* onSettingsClick */,
- null /* onAppSettingsClick */,
- false /* isNonblockable */,
- true /* isForBlockingHelper */,
- true,
- IMPORTANCE_DEFAULT,
- true);
- NotificationGuts guts = mock(NotificationGuts.class);
- doCallRealMethod().when(guts).closeControls(anyInt(), anyInt(), anyBoolean(), anyBoolean());
- mNotificationInfo.setGutsParent(guts);
-
- mNotificationInfo.closeControls(mNotificationInfo, true);
-
- verify(mBlockingHelperManager).dismissCurrentBlockingHelper();
- }
-
- @Test
- public void testSilentlyChangedCallsUpdateNotificationChannel_blockingHelper()
- throws Exception {
- mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet /* numChannels */,
- mEntry,
- null /* checkSaveListener */,
- null /* onSettingsClick */,
- null /* onAppSettingsClick */,
- true /*provisioned */,
- false /* isNonblockable */,
- true /* isForBlockingHelper */,
- IMPORTANCE_DEFAULT,
- true);
-
- mNotificationInfo.findViewById(R.id.deliver_silently).performClick();
- waitForUndoButton();
- mNotificationInfo.handleCloseControls(true, false);
-
- mTestableLooper.processAllMessages();
- ArgumentCaptor<NotificationChannel> updated =
- ArgumentCaptor.forClass(NotificationChannel.class);
- verify(mMockINotificationManager, times(1)).updateNotificationChannelForPackage(
- anyString(), eq(TEST_UID), updated.capture());
- assertTrue((updated.getValue().getUserLockedFields()
- & USER_LOCKED_IMPORTANCE) != 0);
- assertEquals(IMPORTANCE_LOW, updated.getValue().getImportance());
- }
-
- @Test
- public void testKeepUpdatesNotificationChannel_blockingHelper() throws Exception {
- mNotificationChannel.setImportance(IMPORTANCE_LOW);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet,
- mEntry,
- null,
- null,
- null,
- true,
- true,
- IMPORTANCE_LOW,
- false);
-
- mNotificationInfo.findViewById(R.id.keep_showing).performClick();
- mNotificationInfo.handleCloseControls(true, false);
-
- mTestableLooper.processAllMessages();
- ArgumentCaptor<NotificationChannel> updated =
- ArgumentCaptor.forClass(NotificationChannel.class);
- verify(mMockINotificationManager, times(1)).updateNotificationChannelForPackage(
- anyString(), eq(TEST_UID), updated.capture());
- assertTrue(0 != (mNotificationChannel.getUserLockedFields() & USER_LOCKED_IMPORTANCE));
- assertEquals(IMPORTANCE_LOW, mNotificationChannel.getImportance());
- }
-
- @Test
- public void testNoActionsUpdatesNotificationChannel_blockingHelper() throws Exception {
- mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
- mNotificationInfo.bindNotification(
- mMockPackageManager,
- mMockINotificationManager,
- mVisualStabilityManager,
- TEST_PACKAGE_NAME,
- mNotificationChannel,
- mNotificationChannelSet,
- mEntry,
- null,
- null,
- null,
- true,
- true,
- IMPORTANCE_DEFAULT,
- true);
-
- mNotificationInfo.handleCloseControls(true, false);
-
- mTestableLooper.processAllMessages();
- ArgumentCaptor<NotificationChannel> updated =
- ArgumentCaptor.forClass(NotificationChannel.class);
- verify(mMockINotificationManager, times(1)).updateNotificationChannelForPackage(
- anyString(), eq(TEST_UID), updated.capture());
- assertTrue(0 != (mNotificationChannel.getUserLockedFields() & USER_LOCKED_IMPORTANCE));
- assertEquals(IMPORTANCE_DEFAULT, mNotificationChannel.getImportance());
- }
-
- @Test
public void testSilenceCallsUpdateNotificationChannel() throws Exception {
mNotificationChannel.setImportance(IMPORTANCE_DEFAULT);
mNotificationInfo.bindNotification(
@@ -1135,10 +757,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
mNotificationInfo.findViewById(R.id.silence).performClick();
@@ -1168,10 +788,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_LOW,
false);
mNotificationInfo.findViewById(R.id.alert).performClick();
@@ -1202,10 +820,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_UNSPECIFIED,
true);
mNotificationInfo.findViewById(R.id.silence).performClick();
@@ -1236,10 +852,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_MIN,
false);
assertEquals(mContext.getString(R.string.inline_done_button),
@@ -1273,10 +887,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_MIN,
false);
assertEquals(mContext.getString(R.string.inline_done_button),
@@ -1309,10 +921,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_DEFAULT,
true);
mNotificationInfo.findViewById(R.id.silence).performClick();
@@ -1336,10 +946,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_LOW,
false);
assertEquals(mContext.getString(R.string.inline_done_button),
@@ -1366,10 +974,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_LOW,
false);
mNotificationInfo.findViewById(R.id.alert).performClick();
@@ -1399,10 +1005,8 @@
mEntry,
null,
null,
- null,
true,
false,
- IMPORTANCE_LOW,
false);
mNotificationInfo.findViewById(R.id.alert).performClick();
@@ -1425,14 +1029,10 @@
mNotificationChannel,
mNotificationChannelSet,
mEntry,
- (Runnable saveImportance, StatusBarNotification sbn) -> {
- saveImportance.run();
- },
null,
null,
true,
false,
- IMPORTANCE_LOW,
false
);
@@ -1460,14 +1060,10 @@
mNotificationChannel,
mNotificationChannelSet,
mEntry,
- (Runnable saveImportance, StatusBarNotification sbn) -> {
- saveImportance.run();
- },
null,
null,
true,
false,
- IMPORTANCE_LOW,
false
);
@@ -1488,14 +1084,10 @@
mNotificationChannel,
mNotificationChannelSet,
mEntry,
- (Runnable saveImportance, StatusBarNotification sbn) -> {
- saveImportance.run();
- },
null,
null,
true,
false,
- IMPORTANCE_LOW,
false
);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java
index 5a89fc4..dc3374b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationTestHelper.java
@@ -34,6 +34,7 @@
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
+import android.content.pm.LauncherApps;
import android.graphics.drawable.Icon;
import android.os.UserHandle;
import android.service.notification.StatusBarNotification;
@@ -53,6 +54,8 @@
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection;
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener;
+import com.android.systemui.statusbar.notification.icon.IconBuilder;
+import com.android.systemui.statusbar.notification.icon.IconManager;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow.ExpansionLogger;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow.OnExpandClickListener;
import com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.InflationFlag;
@@ -93,6 +96,7 @@
private final NotifBindPipeline mBindPipeline;
private final NotifCollectionListener mBindPipelineEntryListener;
private final RowContentBindStage mBindStage;
+ private final IconManager mIconManager;
private StatusBarStateController mStatusBarStateController;
public NotificationTestHelper(Context context, TestableDependency dependency) {
@@ -106,6 +110,10 @@
mock(KeyguardBypassController.class), mock(NotificationGroupManager.class),
mock(ConfigurationControllerImpl.class));
mGroupManager.setHeadsUpManager(mHeadsUpManager);
+ mIconManager = new IconManager(
+ mock(CommonNotifCollection.class),
+ mock(LauncherApps.class),
+ new IconBuilder(mContext));
NotificationContentInflater contentBinder = new NotificationContentInflater(
mock(NotifRemoteViewCache.class),
@@ -377,7 +385,7 @@
.build();
entry.setRow(row);
- entry.createIcons(mContext, entry.getSbn());
+ mIconManager.createIcons(entry);
row.setEntry(entry);
mBindPipelineEntryListener.onEntryInit(entry);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
index 0cb6585..ef2071e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutTest.java
@@ -46,6 +46,7 @@
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto;
+import com.android.internal.logging.testing.UiEventLoggerFake;
import com.android.systemui.ExpandHelper;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
@@ -139,6 +140,7 @@
private UserChangedListener mUserChangedListener;
private TestableNotificationEntryManager mEntryManager;
private int mOriginalInterruptionModelSetting;
+ private UiEventLoggerFake mUiEventLoggerFake = new UiEventLoggerFake();
@Before
@@ -214,7 +216,8 @@
mFeatureFlags,
mock(NotifPipeline.class),
mEntryManager,
- mock(NotifCollection.class)
+ mock(NotifCollection.class),
+ mUiEventLoggerFake
);
verify(mLockscreenUserManager).addUserChangedListener(userChangedCaptor.capture());
mUserChangedListener = userChangedCaptor.getValue();
@@ -506,6 +509,22 @@
MetricsProto.MetricsEvent.TYPE_ACTION));
}
+ @Test
+ public void testClearNotifications_All() {
+ mStackScroller.clearNotifications(NotificationStackScrollLayout.ROWS_ALL, true);
+ assertEquals(1, mUiEventLoggerFake.numLogs());
+ assertEquals(NotificationStackScrollLayout.NotificationPanelEvent
+ .DISMISS_ALL_NOTIFICATIONS_PANEL.getId(), mUiEventLoggerFake.eventId(0));
+ }
+
+ @Test
+ public void testClearNotifications_Gentle() {
+ mStackScroller.clearNotifications(NotificationStackScrollLayout.ROWS_GENTLE, false);
+ assertEquals(1, mUiEventLoggerFake.numLogs());
+ assertEquals(NotificationStackScrollLayout.NotificationPanelEvent
+ .DISMISS_SILENT_NOTIFICATIONS_PANEL.getId(), mUiEventLoggerFake.eventId(0));
+ }
+
private void setBarStateForTest(int state) {
// Can't inject this through the listener or we end up on the actual implementation
// rather than the mock because the spy just coppied the anonymous inner /shruggie.
@@ -517,8 +536,4 @@
mEntryManager.addActiveNotificationForTest(e);
}
}
-
- private void addActiveNotificationsToManager(List<NotificationEntry> entries) {
- mEntryManager.setActiveNotificationList(entries);
- }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextViewTest.java
new file mode 100644
index 0000000..291c039
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardIndicationTextViewTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2020 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.statusbar.phone;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+import android.view.View;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.systemui.SysuiTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@SmallTest
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper
+public class KeyguardIndicationTextViewTest extends SysuiTestCase {
+
+ private KeyguardIndicationTextView mKeyguardIndicationTextView;
+
+ @Before
+ public void setup() {
+ mKeyguardIndicationTextView = new KeyguardIndicationTextView(mContext);
+ }
+
+ @Test
+ public void switchIndication_null_hideIndication() {
+ mKeyguardIndicationTextView.switchIndication(null /* text */);
+
+ assertThat(mKeyguardIndicationTextView.getVisibility()).isEqualTo(View.INVISIBLE);
+ assertThat(mKeyguardIndicationTextView.getText()).isEqualTo("");
+ }
+
+ @Test
+ public void switchIndication_emptyText_hideIndication() {
+ mKeyguardIndicationTextView.switchIndication("" /* text */);
+
+ assertThat(mKeyguardIndicationTextView.getVisibility()).isEqualTo(View.INVISIBLE);
+ assertThat(mKeyguardIndicationTextView.getText()).isEqualTo("");
+ }
+
+ @Test
+ public void switchIndication_newText_updateProperly() {
+ mKeyguardIndicationTextView.switchIndication("test_indication" /* text */);
+
+ assertThat(mKeyguardIndicationTextView.getVisibility()).isEqualTo(View.VISIBLE);
+ assertThat(mKeyguardIndicationTextView.getText()).isEqualTo("test_indication");
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LockscreenIconControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LockscreenIconControllerTest.java
index 05f10e3..487885a 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LockscreenIconControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/LockscreenIconControllerTest.java
@@ -29,8 +29,10 @@
import com.android.internal.widget.LockPatternUtils;
import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.systemui.SysuiTestCase;
+import com.android.systemui.dock.DockManager;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.KeyguardIndicationController;
+import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.policy.AccessibilityController;
import com.android.systemui.statusbar.policy.ConfigurationController;
@@ -63,6 +65,13 @@
private StatusBarStateController mStatusBarStateController;
@Mock
private ConfigurationController mConfigurationController;
+ @Mock
+ private NotificationWakeUpCoordinator mNotificationWakeUpCoordinator;
+ @Mock
+ private KeyguardBypassController mKeyguardBypassController;
+ @Mock
+ private DockManager mDockManager;
+
@Before
public void setUp() {
@@ -71,7 +80,8 @@
mLockIconController = new LockscreenLockIconController(
mLockscreenGestureLogger, mKeyguardUpdateMonitor, mLockPatternUtils,
mShadeController, mAccessibilityController, mKeyguardIndicationController,
- mStatusBarStateController, mConfigurationController);
+ mStatusBarStateController, mConfigurationController, mNotificationWakeUpCoordinator,
+ mKeyguardBypassController, mDockManager);
mLockIconController.attach(mLockIcon);
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowControllerTest.java
index 83e89bd..5320ecd 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowControllerTest.java
@@ -20,6 +20,7 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -27,6 +28,7 @@
import android.app.IActivityManager;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper.RunWithLooper;
+import android.view.View;
import android.view.WindowManager;
import androidx.test.filters.SmallTest;
@@ -110,4 +112,13 @@
public void testSetForcePluginOpen_beforeStatusBarInitialization() {
mNotificationShadeWindowController.setForcePluginOpen(true);
}
+
+ @Test
+ public void setBackgroundBlurRadius_expandedWithBlurs() {
+ mNotificationShadeWindowController.setBackgroundBlurRadius(10);
+ verify(mNotificationShadeWindowView).setVisibility(eq(View.VISIBLE));
+
+ mNotificationShadeWindowController.setBackgroundBlurRadius(0);
+ verify(mNotificationShadeWindowView).setVisibility(eq(View.INVISIBLE));
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewTest.java
index c5b6969..cc2d1c2 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationShadeWindowViewTest.java
@@ -37,7 +37,7 @@
import com.android.systemui.statusbar.CommandQueue;
import com.android.systemui.statusbar.DragDownHelper;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
-import com.android.systemui.statusbar.NotificationShadeWindowBlurController;
+import com.android.systemui.statusbar.NotificationShadeDepthController;
import com.android.systemui.statusbar.PulseExpansionHandler;
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
@@ -81,7 +81,7 @@
@Mock private DockManager mDockManager;
@Mock private NotificationPanelViewController mNotificationPanelViewController;
@Mock private NotificationStackScrollLayout mNotificationStackScrollLayout;
- @Mock private NotificationShadeWindowBlurController mNotificationShadeWindowBlurController;
+ @Mock private NotificationShadeDepthController mNotificationShadeDepthController;
@Mock private SuperStatusBarViewFactory mStatusBarViewFactory;
@Before
@@ -116,7 +116,7 @@
new CommandQueue(mContext),
mShadeController,
mDockManager,
- mNotificationShadeWindowBlurController,
+ mNotificationShadeDepthController,
mView,
mNotificationPanelViewController,
mStatusBarViewFactory);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
index 408dfc0..23f2637 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java
@@ -50,6 +50,7 @@
import com.android.systemui.SysuiTestCase;
import com.android.systemui.colorextraction.SysuiColorExtractor;
import com.android.systemui.dock.DockManager;
+import com.android.systemui.statusbar.BlurUtils;
import com.android.systemui.statusbar.ScrimView;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.util.wakelock.DelayedWakeLock;
@@ -101,6 +102,8 @@
private SysuiColorExtractor mSysuiColorExtractor;
@Mock
private DockManager mDockManager;
+ @Mock
+ private BlurUtils mBlurUtils;
private static class AnimatorListener implements Animator.AnimatorListener {
@@ -215,7 +218,7 @@
mScrimController = new ScrimController(mLightBarController,
mDozeParamenters, mAlarmManager, mKeyguardStateController, mDelayedWakeLockBuilder,
new FakeHandler(mLooper.getLooper()), mKeyguardUpdateMonitor, mSysuiColorExtractor,
- mDockManager);
+ mDockManager, mBlurUtils);
mScrimController.setScrimVisibleListener(visible -> mScrimVisibility = visible);
mScrimController.attachViews(mScrimBehind, mScrimInFront, mScrimForBubble);
mScrimController.setAnimatorListener(mAnimatorListener);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
index 1e4df27..b9c5b7c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
@@ -67,10 +67,10 @@
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
import com.android.systemui.statusbar.notification.NotificationActivityStarter;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.collection.NotifCollection;
import com.android.systemui.statusbar.notification.collection.NotifPipeline;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.NotificationTestHelper;
import com.android.systemui.statusbar.policy.KeyguardStateController;
@@ -183,7 +183,7 @@
mock(StatusBarRemoteInputCallback.class), mock(NotificationGroupManager.class),
mock(NotificationLockscreenUserManager.class),
mKeyguardStateController,
- mock(NotificationInterruptionStateProvider.class), mock(MetricsLogger.class),
+ mock(NotificationInterruptStateProvider.class), mock(MetricsLogger.class),
mock(LockPatternUtils.class), mHandler, mHandler, mUiBgExecutor,
mActivityIntentHelper, mBubbleController, mShadeController, mFeatureFlags,
mNotifPipeline, mNotifCollection)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
index b9d2d22..318e9b8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationPresenterTest.java
@@ -16,8 +16,9 @@
import static android.view.Display.DEFAULT_DISPLAY;
-import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Notification;
@@ -35,6 +36,7 @@
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.logging.testing.FakeMetricsLogger;
+import com.android.systemui.ForegroundServiceNotificationListener;
import com.android.systemui.InitController;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
@@ -48,12 +50,12 @@
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProvider;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptSuppressor;
import com.android.systemui.statusbar.notification.row.ActivatableNotificationView;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.notification.stack.NotificationListContainer;
@@ -62,6 +64,7 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
@@ -72,6 +75,9 @@
private StatusBarNotificationPresenter mStatusBarNotificationPresenter;
+ private NotificationInterruptStateProvider mNotificationInterruptStateProvider =
+ mock(NotificationInterruptStateProvider.class);
+ private NotificationInterruptSuppressor mInterruptSuppressor;
private CommandQueue mCommandQueue;
private FakeMetricsLogger mMetricsLogger;
private ShadeController mShadeController = mock(ShadeController.class);
@@ -95,11 +101,11 @@
mDependency.injectMockDependency(NotificationViewHierarchyManager.class);
mDependency.injectMockDependency(NotificationRemoteInputManager.Callback.class);
mDependency.injectMockDependency(NotificationLockscreenUserManager.class);
- mDependency.injectMockDependency(NotificationInterruptionStateProvider.class);
mDependency.injectMockDependency(NotificationMediaManager.class);
mDependency.injectMockDependency(VisualStabilityManager.class);
mDependency.injectMockDependency(NotificationGutsManager.class);
mDependency.injectMockDependency(NotificationShadeWindowController.class);
+ mDependency.injectMockDependency(ForegroundServiceNotificationListener.class);
NotificationEntryManager entryManager =
mDependency.injectMockDependency(NotificationEntryManager.class);
when(entryManager.getActiveNotificationsForCurrentUser()).thenReturn(new ArrayList<>());
@@ -107,18 +113,25 @@
NotificationShadeWindowView notificationShadeWindowView =
mock(NotificationShadeWindowView.class);
when(notificationShadeWindowView.getResources()).thenReturn(mContext.getResources());
+
mStatusBarNotificationPresenter = new StatusBarNotificationPresenter(mContext,
mock(NotificationPanelViewController.class), mock(HeadsUpManagerPhone.class),
notificationShadeWindowView, mock(NotificationListContainerViewGroup.class),
mock(DozeScrimController.class), mock(ScrimController.class),
mock(ActivityLaunchAnimator.class), mock(DynamicPrivacyController.class),
- mock(NotificationAlertingManager.class), mock(KeyguardStateController.class),
+ mock(KeyguardStateController.class),
mock(KeyguardIndicationController.class), mStatusBar,
- mock(ShadeControllerImpl.class), mCommandQueue, mInitController);
+ mock(ShadeControllerImpl.class), mCommandQueue, mInitController,
+ mNotificationInterruptStateProvider);
+ mInitController.executePostInitTasks();
+ ArgumentCaptor<NotificationInterruptSuppressor> suppressorCaptor =
+ ArgumentCaptor.forClass(NotificationInterruptSuppressor.class);
+ verify(mNotificationInterruptStateProvider).addSuppressor(suppressorCaptor.capture());
+ mInterruptSuppressor = suppressorCaptor.getValue();
}
@Test
- public void testHeadsUp_disabledStatusBar() {
+ public void testSuppressHeadsUp_disabledStatusBar() {
Notification n = new Notification.Builder(getContext(), "a").build();
NotificationEntry entry = new NotificationEntryBuilder()
.setPkg("a")
@@ -130,12 +143,12 @@
false /* animate */);
TestableLooper.get(this).processAllMessages();
- assertFalse("The panel shouldn't allow heads up while disabled",
- mStatusBarNotificationPresenter.canHeadsUp(entry, entry.getSbn()));
+ assertTrue("The panel should suppress heads up while disabled",
+ mInterruptSuppressor.suppressAwakeHeadsUp(entry));
}
@Test
- public void testHeadsUp_disabledNotificationShade() {
+ public void testSuppressHeadsUp_disabledNotificationShade() {
Notification n = new Notification.Builder(getContext(), "a").build();
NotificationEntry entry = new NotificationEntryBuilder()
.setPkg("a")
@@ -147,8 +160,39 @@
false /* animate */);
TestableLooper.get(this).processAllMessages();
- assertFalse("The panel shouldn't allow heads up while notitifcation shade disabled",
- mStatusBarNotificationPresenter.canHeadsUp(entry, entry.getSbn()));
+ assertTrue("The panel should suppress interruptions while notification shade "
+ + "disabled",
+ mInterruptSuppressor.suppressAwakeHeadsUp(entry));
+ }
+
+ @Test
+ public void testSuppressInterruptions_vrMode() {
+ Notification n = new Notification.Builder(getContext(), "a").build();
+ NotificationEntry entry = new NotificationEntryBuilder()
+ .setPkg("a")
+ .setOpPkg("a")
+ .setTag("a")
+ .setNotification(n)
+ .build();
+ mStatusBarNotificationPresenter.mVrMode = true;
+
+ assertTrue("Vr mode should suppress interruptions",
+ mInterruptSuppressor.suppressAwakeInterruptions(entry));
+ }
+
+ @Test
+ public void testSuppressInterruptions_statusBarAlertsDisabled() {
+ Notification n = new Notification.Builder(getContext(), "a").build();
+ NotificationEntry entry = new NotificationEntryBuilder()
+ .setPkg("a")
+ .setOpPkg("a")
+ .setTag("a")
+ .setNotification(n)
+ .build();
+ when(mStatusBar.areNotificationAlertsDisabled()).thenReturn(true);
+
+ assertTrue("StatusBar alerts disabled shouldn't allow interruptions",
+ mInterruptSuppressor.suppressInterruptions(entry));
}
@Test
@@ -172,4 +216,3 @@
}
}
}
-
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
index 0d7734e..679ac22 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
@@ -42,7 +42,7 @@
import android.app.StatusBarManager;
import android.app.trust.TrustManager;
import android.content.BroadcastReceiver;
-import android.content.Context;
+import android.content.ContentResolver;
import android.content.IntentFilter;
import android.hardware.display.AmbientDisplayConfiguration;
import android.hardware.fingerprint.FingerprintManager;
@@ -109,19 +109,20 @@
import com.android.systemui.statusbar.StatusBarStateControllerImpl;
import com.android.systemui.statusbar.SuperStatusBarViewFactory;
import com.android.systemui.statusbar.VibratorHelper;
-import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier;
import com.android.systemui.statusbar.notification.DynamicPrivacyController;
-import com.android.systemui.statusbar.notification.NotificationAlertingManager;
import com.android.systemui.statusbar.notification.NotificationEntryListener;
import com.android.systemui.statusbar.notification.NotificationEntryManager;
import com.android.systemui.statusbar.notification.NotificationFilter;
-import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.init.NotificationsController;
+import com.android.systemui.statusbar.notification.interruption.BypassHeadsUpNotifier;
+import com.android.systemui.statusbar.notification.interruption.NotificationAlertingManager;
+import com.android.systemui.statusbar.notification.interruption.NotificationInterruptStateProviderImpl;
import com.android.systemui.statusbar.notification.logging.NotificationLogger;
+import com.android.systemui.statusbar.notification.logging.NotificationPanelLoggerFake;
import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout;
import com.android.systemui.statusbar.phone.dagger.StatusBarComponent;
@@ -129,6 +130,7 @@
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
import com.android.systemui.statusbar.policy.ExtensionController;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler;
@@ -160,7 +162,7 @@
private StatusBar mStatusBar;
private FakeMetricsLogger mMetricsLogger;
private PowerManager mPowerManager;
- private TestableNotificationInterruptionStateProvider mNotificationInterruptionStateProvider;
+ private TestableNotificationInterruptStateProviderImpl mNotificationInterruptStateProvider;
@Mock private NotificationsController mNotificationsController;
@Mock private LightBarController mLightBarController;
@@ -178,7 +180,6 @@
@Mock private DozeScrimController mDozeScrimController;
@Mock private Lazy<BiometricUnlockController> mBiometricUnlockControllerLazy;
@Mock private BiometricUnlockController mBiometricUnlockController;
- @Mock private NotificationInterruptionStateProvider.HeadsUpSuppressor mHeadsUpSuppressor;
@Mock private VisualStabilityManager mVisualStabilityManager;
@Mock private NotificationListener mNotificationListener;
@Mock private KeyguardViewMediator mKeyguardViewMediator;
@@ -192,9 +193,9 @@
@Mock private NotificationEntryListener mEntryListener;
@Mock private NotificationFilter mNotificationFilter;
@Mock private NotificationAlertingManager mNotificationAlertingManager;
+ @Mock private AmbientDisplayConfiguration mAmbientDisplayConfiguration;
@Mock private NotificationLogger.ExpansionStateLogger mExpansionStateLogger;
@Mock private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
- @Mock private AmbientDisplayConfiguration mAmbientDisplayConfiguration;
@Mock private NotificationShadeWindowView mNotificationShadeWindowView;
@Mock private BroadcastDispatcher mBroadcastDispatcher;
@Mock private AssistManager mAssistManager;
@@ -262,10 +263,12 @@
mPowerManager = new PowerManager(mContext, powerManagerService, thermalService,
Handler.createAsync(Looper.myLooper()));
- mNotificationInterruptionStateProvider =
- new TestableNotificationInterruptionStateProvider(mContext, mPowerManager,
+ mNotificationInterruptStateProvider =
+ new TestableNotificationInterruptStateProviderImpl(mContext.getContentResolver(),
+ mPowerManager,
mDreamManager, mAmbientDisplayConfiguration, mNotificationFilter,
- mStatusBarStateController, mBatteryController);
+ mStatusBarStateController, mBatteryController, mHeadsUpManager,
+ new Handler(TestableLooper.get(this).getLooper()));
mContext.addMockSystemService(TrustManager.class, mock(TrustManager.class));
mContext.addMockSystemService(FingerprintManager.class, mock(FingerprintManager.class));
@@ -273,7 +276,7 @@
mMetricsLogger = new FakeMetricsLogger();
NotificationLogger notificationLogger = new NotificationLogger(mNotificationListener,
mUiBgExecutor, mock(NotificationEntryManager.class), mStatusBarStateController,
- mExpansionStateLogger);
+ mExpansionStateLogger, new NotificationPanelLoggerFake());
notificationLogger.setVisibilityReporter(mock(Runnable.class));
when(mCommandQueue.asBinder()).thenReturn(new Binder());
@@ -298,9 +301,6 @@
return null;
}).when(mStatusBarKeyguardViewManager).addAfterKeyguardGoneRunnable(any());
- mNotificationInterruptionStateProvider.setUpWithPresenter(mNotificationPresenter,
- mHeadsUpManager, mHeadsUpSuppressor);
-
when(mRemoteInputManager.getController()).thenReturn(mRemoteInputController);
WakefulnessLifecycle wakefulnessLifecycle = new WakefulnessLifecycle();
@@ -347,7 +347,7 @@
),
mNotificationGutsManager,
notificationLogger,
- mNotificationInterruptionStateProvider,
+ mNotificationInterruptStateProvider,
mNotificationViewHierarchyManager,
mKeyguardViewMediator,
mNotificationAlertingManager,
@@ -561,7 +561,6 @@
when(mHeadsUpManager.isSnoozed(anyString())).thenReturn(false);
when(mNotificationFilter.shouldFilterOut(any())).thenReturn(false);
when(mDreamManager.isDreaming()).thenReturn(false);
- when(mHeadsUpSuppressor.canHeadsUp(any(), any())).thenReturn(true);
Notification n = new Notification.Builder(getContext(), "a")
.setGroup("a")
@@ -577,7 +576,7 @@
.setImportance(IMPORTANCE_HIGH)
.build();
- assertTrue(mNotificationInterruptionStateProvider.shouldHeadsUp(entry));
+ assertTrue(mNotificationInterruptStateProvider.shouldHeadsUp(entry));
}
@Test
@@ -586,7 +585,6 @@
when(mHeadsUpManager.isSnoozed(anyString())).thenReturn(false);
when(mNotificationFilter.shouldFilterOut(any())).thenReturn(false);
when(mDreamManager.isDreaming()).thenReturn(false);
- when(mHeadsUpSuppressor.canHeadsUp(any(), any())).thenReturn(true);
Notification n = new Notification.Builder(getContext(), "a")
.setGroup("a")
@@ -602,7 +600,7 @@
.setImportance(IMPORTANCE_HIGH)
.build();
- assertFalse(mNotificationInterruptionStateProvider.shouldHeadsUp(entry));
+ assertFalse(mNotificationInterruptStateProvider.shouldHeadsUp(entry));
}
@Test
@@ -611,7 +609,6 @@
when(mHeadsUpManager.isSnoozed(anyString())).thenReturn(false);
when(mNotificationFilter.shouldFilterOut(any())).thenReturn(false);
when(mDreamManager.isDreaming()).thenReturn(false);
- when(mHeadsUpSuppressor.canHeadsUp(any(), any())).thenReturn(true);
Notification n = new Notification.Builder(getContext(), "a").build();
@@ -624,7 +621,7 @@
.setSuppressedVisualEffects(SUPPRESSED_EFFECT_PEEK)
.build();
- assertFalse(mNotificationInterruptionStateProvider.shouldHeadsUp(entry));
+ assertFalse(mNotificationInterruptStateProvider.shouldHeadsUp(entry));
}
@Test
@@ -633,7 +630,6 @@
when(mHeadsUpManager.isSnoozed(anyString())).thenReturn(false);
when(mNotificationFilter.shouldFilterOut(any())).thenReturn(false);
when(mDreamManager.isDreaming()).thenReturn(false);
- when(mHeadsUpSuppressor.canHeadsUp(any(), any())).thenReturn(true);
Notification n = new Notification.Builder(getContext(), "a").build();
@@ -645,7 +641,7 @@
.setImportance(IMPORTANCE_HIGH)
.build();
- assertTrue(mNotificationInterruptionStateProvider.shouldHeadsUp(entry));
+ assertTrue(mNotificationInterruptStateProvider.shouldHeadsUp(entry));
}
@Test
@@ -871,19 +867,21 @@
verify(mDozeServiceHost).setDozeSuppressed(false);
}
- public static class TestableNotificationInterruptionStateProvider extends
- NotificationInterruptionStateProvider {
+ public static class TestableNotificationInterruptStateProviderImpl extends
+ NotificationInterruptStateProviderImpl {
- TestableNotificationInterruptionStateProvider(
- Context context,
+ TestableNotificationInterruptStateProviderImpl(
+ ContentResolver contentResolver,
PowerManager powerManager,
IDreamManager dreamManager,
AmbientDisplayConfiguration ambientDisplayConfiguration,
NotificationFilter filter,
StatusBarStateController controller,
- BatteryController batteryController) {
- super(context, powerManager, dreamManager, ambientDisplayConfiguration, filter,
- batteryController, controller);
+ BatteryController batteryController,
+ HeadsUpManager headsUpManager,
+ Handler mainHandler) {
+ super(contentResolver, powerManager, dreamManager, ambientDisplayConfiguration, filter,
+ batteryController, controller, headsUpManager, mainHandler);
mUseHeadsUp = true;
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
index a0d551c..cddbb9f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerBaseTest.java
@@ -207,7 +207,7 @@
protected void setupNetworkController() {
// For now just pretend to be the data sim, so we can test that too.
mSubId = SubscriptionManager.DEFAULT_SUBSCRIPTION_ID;
- when(mMockTm.isDataConnectionEnabled()).thenReturn(true);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(true);
setDefaultSubId(mSubId);
setSubscriptions(mSubId);
mMobileSignalController = mNetworkController.mMobileSignalControllers.get(mSubId);
@@ -235,7 +235,7 @@
subs.add(subscription);
}
when(mMockSm.getActiveSubscriptionInfoList()).thenReturn(subs);
- when(mMockSm.getActiveAndHiddenSubscriptionInfoList()).thenReturn(subs);
+ when(mMockSm.getCompleteActiveSubscriptionInfoList()).thenReturn(subs);
mNetworkController.doUpdateMobileControllers();
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
index 3eb0c44..d8b6aac 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerDataTest.java
@@ -119,7 +119,7 @@
@Test
public void testNoInternetIcon_withDefaultSub() {
setupNetworkController();
- when(mMockTm.isDataConnectionEnabled()).thenReturn(false);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(false);
setupDefaultSignal();
updateDataConnectionState(TelephonyManager.DATA_CONNECTED, 0);
setConnectivityViaBroadcast(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
@@ -133,7 +133,7 @@
@Test
public void testDataDisabledIcon_withDefaultSub() {
setupNetworkController();
- when(mMockTm.isDataConnectionEnabled()).thenReturn(false);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(false);
setupDefaultSignal();
updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
setConnectivityViaBroadcast(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
@@ -147,7 +147,7 @@
@Test
public void testNonDefaultSIM_showsFullSignal_connected() {
setupNetworkController();
- when(mMockTm.isDataConnectionEnabled()).thenReturn(false);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(false);
setupDefaultSignal();
setDefaultSubId(mSubId + 1);
updateDataConnectionState(TelephonyManager.DATA_CONNECTED, 0);
@@ -162,7 +162,7 @@
@Test
public void testNonDefaultSIM_showsFullSignal_disconnected() {
setupNetworkController();
- when(mMockTm.isDataConnectionEnabled()).thenReturn(false);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(false);
setupDefaultSignal();
setDefaultSubId(mSubId + 1);
updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
@@ -177,7 +177,7 @@
@Test
public void testDataDisabledIcon_UserNotSetup() {
setupNetworkController();
- when(mMockTm.isDataConnectionEnabled()).thenReturn(false);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(false);
setupDefaultSignal();
updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED, 0);
setConnectivityViaBroadcast(NetworkCapabilities.TRANSPORT_CELLULAR, false, false);
@@ -192,7 +192,7 @@
@Test
public void testAlwaysShowDataRatIcon() {
setupDefaultSignal();
- when(mMockTm.isDataConnectionEnabled()).thenReturn(false);
+ when(mMockTm.isDataConnectionAllowed()).thenReturn(false);
updateDataConnectionState(TelephonyManager.DATA_DISCONNECTED,
TelephonyManager.NETWORK_TYPE_GSM);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java
index 37b315f..526fba7 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/util/sensors/ProximitySensorTest.java
@@ -104,6 +104,30 @@
}
@Test
+ public void testDuplicateListener() {
+ TestableListener listenerA = new TestableListener();
+
+ assertFalse(mProximitySensor.isRegistered());
+
+ mProximitySensor.register(listenerA);
+ waitForSensorManager();
+ assertTrue(mProximitySensor.isRegistered());
+ mProximitySensor.register(listenerA);
+ waitForSensorManager();
+ assertTrue(mProximitySensor.isRegistered());
+ assertNull(listenerA.mLastEvent);
+
+ mFakeProximitySensor.sendProximityResult(true);
+ assertFalse(listenerA.mLastEvent.getNear());
+ assertEquals(listenerA.mCallCount, 1);
+ mFakeProximitySensor.sendProximityResult(false);
+ assertTrue(listenerA.mLastEvent.getNear());
+ assertEquals(listenerA.mCallCount, 2);
+
+ mProximitySensor.unregister(listenerA);
+ waitForSensorManager();
+ }
+ @Test
public void testUnregister() {
TestableListener listener = new TestableListener();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java
index 701b2fa..a853f1d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/EventsTest.java
@@ -102,9 +102,9 @@
assertEquals(mExpectedMetrics[1], logs.remove().getCategory());
}
}
- Queue<UiEventLoggerFake.FakeUiEvent> events = mUiEventLogger.getLogs();
if (mUiEvent != null) {
- assertEquals(mUiEvent.getId(), events.remove().eventId);
+ assertEquals(1, mUiEventLogger.numLogs());
+ assertEquals(mUiEvent.getId(), mUiEventLogger.eventId(0));
}
}
diff --git a/packages/Tethering/common/TetheringLib/Android.bp b/packages/Tethering/common/TetheringLib/Android.bp
index 5b73dd5..2fbba68 100644
--- a/packages/Tethering/common/TetheringLib/Android.bp
+++ b/packages/Tethering/common/TetheringLib/Android.bp
@@ -62,26 +62,14 @@
apex_available: ["com.android.tethering"],
}
-droidstubs {
- name: "framework-tethering-stubs-sources",
- defaults: ["framework-module-stubs-defaults-module_libs_api"],
+stubs_defaults {
+ name: "framework-tethering-stubs-defaults",
srcs: [
"src/android/net/TetheredClient.java",
"src/android/net/TetheringManager.java",
"src/android/net/TetheringConstants.java",
],
- libs: [
- "tethering-aidl-interfaces-java",
- "framework-all",
- ],
- sdk_version: "core_platform",
-}
-
-java_library {
- name: "framework-tethering-stubs",
- srcs: [":framework-tethering-stubs-sources"],
- libs: ["framework-all"],
- sdk_version: "core_platform",
+ libs: ["tethering-aidl-interfaces-java"],
}
filegroup {
@@ -101,3 +89,53 @@
],
path: "src"
}
+
+droidstubs {
+ name: "framework-tethering-stubs-srcs-publicapi",
+ defaults: [
+ "framework-module-stubs-defaults-publicapi",
+ "framework-tethering-stubs-defaults",
+ ],
+}
+
+droidstubs {
+ name: "framework-tethering-stubs-srcs-systemapi",
+ defaults: [
+ "framework-module-stubs-defaults-systemapi",
+ "framework-tethering-stubs-defaults",
+ ],
+}
+
+droidstubs {
+ name: "framework-tethering-api-module_libs_api",
+ defaults: [
+ "framework-module-api-defaults-module_libs_api",
+ "framework-tethering-stubs-defaults",
+ ],
+}
+
+droidstubs {
+ name: "framework-tethering-stubs-srcs-module_libs_api",
+ defaults: [
+ "framework-module-stubs-defaults-module_libs_api",
+ "framework-tethering-stubs-defaults",
+ ],
+}
+
+java_library {
+ name: "framework-tethering-stubs-publicapi",
+ srcs: [":framework-tethering-stubs-srcs-publicapi"],
+ sdk_version: "current",
+}
+
+java_library {
+ name: "framework-tethering-stubs-systemapi",
+ srcs: [":framework-tethering-stubs-srcs-systemapi"],
+ sdk_version: "system_current",
+}
+
+java_library {
+ name: "framework-tethering-stubs-module_libs_api",
+ srcs: [":framework-tethering-stubs-srcs-module_libs_api"],
+ sdk_version: "module_current",
+}
diff --git a/packages/Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl b/packages/Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl
index a554193..b4e3ba4 100644
--- a/packages/Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl
+++ b/packages/Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl
@@ -35,4 +35,5 @@
void onConfigurationChanged(in TetheringConfigurationParcel config);
void onTetherStatesChanged(in TetherStatesParcel states);
void onTetherClientsChanged(in List<TetheredClient> clients);
+ void onOffloadStatusChanged(int status);
}
diff --git a/packages/Tethering/common/TetheringLib/src/android/net/TetheredClient.java b/packages/Tethering/common/TetheringLib/src/android/net/TetheredClient.java
index 8b8b9e5..48be0d9 100644
--- a/packages/Tethering/common/TetheringLib/src/android/net/TetheredClient.java
+++ b/packages/Tethering/common/TetheringLib/src/android/net/TetheredClient.java
@@ -64,16 +64,26 @@
dest.writeInt(mTetheringType);
}
+ /**
+ * Get the MAC address used to identify the client.
+ */
@NonNull
public MacAddress getMacAddress() {
return mMacAddress;
}
+ /**
+ * Get information on the list of addresses that are associated with the client.
+ */
@NonNull
public List<AddressInfo> getAddresses() {
return new ArrayList<>(mAddresses);
}
+ /**
+ * Get the type of tethering used by the client.
+ * @return one of the {@code TetheringManager#TETHERING_*} constants.
+ */
public int getTetheringType() {
return mTetheringType;
}
@@ -115,45 +125,47 @@
private final LinkAddress mAddress;
@Nullable
private final String mHostname;
- // TODO: use LinkAddress expiration time once it is supported
- private final long mExpirationTime;
/** @hide */
public AddressInfo(@NonNull LinkAddress address, @Nullable String hostname) {
- this(address, hostname, 0);
- }
-
- /** @hide */
- public AddressInfo(@NonNull LinkAddress address, String hostname, long expirationTime) {
this.mAddress = address;
this.mHostname = hostname;
- this.mExpirationTime = expirationTime;
}
private AddressInfo(Parcel in) {
- this(in.readParcelable(null), in.readString(), in.readLong());
+ this(in.readParcelable(null), in.readString());
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeParcelable(mAddress, flags);
dest.writeString(mHostname);
- dest.writeLong(mExpirationTime);
}
+ /**
+ * Get the link address (including prefix length and lifetime) used by the client.
+ *
+ * This may be an IPv4 or IPv6 address.
+ */
@NonNull
public LinkAddress getAddress() {
return mAddress;
}
+ /**
+ * Get the hostname that was advertised by the client when obtaining its address, if any.
+ */
@Nullable
public String getHostname() {
return mHostname;
}
- /** @hide TODO: use expiration time in LinkAddress */
+ /**
+ * Get the expiration time of the address assigned to the client.
+ * @hide
+ */
public long getExpirationTime() {
- return mExpirationTime;
+ return mAddress.getExpirationTime();
}
@Override
@@ -163,7 +175,7 @@
@Override
public int hashCode() {
- return Objects.hash(mAddress, mHostname, mExpirationTime);
+ return Objects.hash(mAddress, mHostname);
}
@Override
@@ -173,8 +185,7 @@
// Use .equals() for addresses as all changes, including address expiry changes,
// should be included.
return other.mAddress.equals(mAddress)
- && Objects.equals(mHostname, other.mHostname)
- && mExpirationTime == other.mExpirationTime;
+ && Objects.equals(mHostname, other.mHostname);
}
@NonNull
diff --git a/packages/Tethering/common/TetheringLib/src/android/net/TetheringCallbackStartedParcel.aidl b/packages/Tethering/common/TetheringLib/src/android/net/TetheringCallbackStartedParcel.aidl
index c064aa4..253eacb 100644
--- a/packages/Tethering/common/TetheringLib/src/android/net/TetheringCallbackStartedParcel.aidl
+++ b/packages/Tethering/common/TetheringLib/src/android/net/TetheringCallbackStartedParcel.aidl
@@ -31,4 +31,5 @@
TetheringConfigurationParcel config;
TetherStatesParcel states;
List<TetheredClient> tetheredClients;
-}
\ No newline at end of file
+ int offloadStatus;
+}
diff --git a/packages/Tethering/common/TetheringLib/src/android/net/TetheringConstants.java b/packages/Tethering/common/TetheringLib/src/android/net/TetheringConstants.java
index a18f5da..fd6f171 100644
--- a/packages/Tethering/common/TetheringLib/src/android/net/TetheringConstants.java
+++ b/packages/Tethering/common/TetheringLib/src/android/net/TetheringConstants.java
@@ -32,7 +32,7 @@
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
-public class TetheringConstants {
+public final class TetheringConstants {
/** An explicit private class to avoid exposing constructor.*/
private TetheringConstants() { }
diff --git a/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java b/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java
index fd9f713..7f831ce 100644
--- a/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java
+++ b/packages/Tethering/common/TetheringLib/src/android/net/TetheringManager.java
@@ -18,6 +18,7 @@
import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
import android.Manifest;
+import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
@@ -34,6 +35,8 @@
import com.android.internal.annotations.GuardedBy;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -172,6 +175,23 @@
public static final int TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION = 14;
public static final int TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION = 15;
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(flag = false, value = {
+ TETHER_HARDWARE_OFFLOAD_STOPPED,
+ TETHER_HARDWARE_OFFLOAD_STARTED,
+ TETHER_HARDWARE_OFFLOAD_FAILED,
+ })
+ public @interface TetherOffloadStatus {
+ }
+
+ /** Tethering offload status is stopped. */
+ public static final int TETHER_HARDWARE_OFFLOAD_STOPPED = 0;
+ /** Tethering offload status is started. */
+ public static final int TETHER_HARDWARE_OFFLOAD_STARTED = 1;
+ /** Fail to start tethering offload. */
+ public static final int TETHER_HARDWARE_OFFLOAD_FAILED = 2;
+
/**
* Create a TetheringManager object for interacting with the tethering service.
*
@@ -378,6 +398,9 @@
@Override
public void onTetherClientsChanged(List<TetheredClient> clients) { }
+ @Override
+ public void onOffloadStatusChanged(int status) { }
+
public void waitForStarted() {
mWaitForCallback.block(DEFAULT_TIMEOUT_MS);
throwIfPermissionFailure(mError);
@@ -802,6 +825,14 @@
* @param clients The new set of tethered clients; the collection is not ordered.
*/
public void onClientsChanged(@NonNull Collection<TetheredClient> clients) {}
+
+ /**
+ * Called when tethering offload status changes.
+ *
+ * <p>This will be called immediately after the callback is registered.
+ * @param status The offload status.
+ */
+ public void onOffloadStatusChanged(@TetherOffloadStatus int status) {}
}
/**
@@ -925,6 +956,7 @@
maybeSendTetherableIfacesChangedCallback(parcel.states);
maybeSendTetheredIfacesChangedCallback(parcel.states);
callback.onClientsChanged(parcel.tetheredClients);
+ callback.onOffloadStatusChanged(parcel.offloadStatus);
});
}
@@ -960,6 +992,11 @@
public void onTetherClientsChanged(final List<TetheredClient> clients) {
executor.execute(() -> callback.onClientsChanged(clients));
}
+
+ @Override
+ public void onOffloadStatusChanged(final int status) {
+ executor.execute(() -> callback.onOffloadStatusChanged(status));
+ }
};
getConnector(c -> c.registerTetheringEventCallback(remoteCallback, callerPkg));
mTetheringEventCallbacks.put(callback, remoteCallback);
@@ -1131,6 +1168,25 @@
public boolean isTetheringSupported() {
final String callerPkg = mContext.getOpPackageName();
+ return isTetheringSupported(callerPkg);
+ }
+
+ /**
+ * Check if the device allows for tethering. It may be disabled via {@code ro.tether.denied}
+ * system property, Settings.TETHER_SUPPORTED or due to device configuration. This is useful
+ * for system components that query this API on behalf of an app. In particular, Bluetooth
+ * has @UnsupportedAppUsage calls that will let apps turn on bluetooth tethering if they have
+ * the right permissions, but such an app needs to know whether it can (permissions as well
+ * as support from the device) turn on tethering in the first place to show the appropriate UI.
+ *
+ * @param callerPkg The caller package name, if it is not matching the calling uid,
+ * SecurityException would be thrown.
+ * @return a boolean - {@code true} indicating Tethering is supported.
+ * @hide
+ */
+ @SystemApi(client = MODULE_LIBRARIES)
+ public boolean isTetheringSupported(@NonNull final String callerPkg) {
+
final RequestDispatcher dispatcher = new RequestDispatcher();
final int ret = dispatcher.waitForResult((connector, listener) -> {
try {
diff --git a/packages/Tethering/res/values/config.xml b/packages/Tethering/res/values/config.xml
index 4af5c53..04d6215 100644
--- a/packages/Tethering/res/values/config.xml
+++ b/packages/Tethering/res/values/config.xml
@@ -157,4 +157,49 @@
<!-- ComponentName of the service used to run no ui tether provisioning. -->
<string translatable="false" name="config_wifi_tether_enable">com.android.settings/.wifi.tether.TetherService</string>
+
+ <!-- Enable tethering notification -->
+ <!-- Icons for showing tether enable notification.
+ Each item should have two elements and be separated with ";".
+
+ The first element is downstream types which is one of tethering. This element has to be
+ made by WIFI, USB, BT, and OR'd with the others. Use "|" to combine multiple downstream
+ types and use "," to separate each combinations. Such as
+
+ USB|BT,WIFI|USB|BT
+
+ The second element is icon for the item. This element has to be composed by
+ <package name>:drawable/<resource name>. Such as
+
+ 1. com.android.networkstack.tethering:drawable/stat_sys_tether_general
+ 2. android:drawable/xxx
+
+ So the entire string of each item would be
+
+ USB|BT,WIFI|USB|BT;com.android.networkstack.tethering:drawable/stat_sys_tether_general
+
+ NOTE: One config can be separated into two or more for readability. Such as
+
+ WIFI|USB,WIFI|BT,USB|BT,WIFI|USB|BT;android:drawable/xxx
+
+ can be separated into
+
+ WIFI|USB;android:drawable/xxx
+ WIFI|BT;android:drawable/xxx
+ USB|BT;android:drawable/xxx
+ WIFI|USB|BT;android:drawable/xxx
+
+ Notification will not show if the downstream type isn't listed in array.
+ Empty array means disable notifications. -->
+ <!-- In AOSP, hotspot is configured to no notification by default. Because status bar has showed
+ an icon on the right side already -->
+ <string-array translatable="false" name="tethering_notification_icons">
+ <item>USB;com.android.networkstack.tethering:drawable/stat_sys_tether_usb</item>
+ <item>BT;com.android.networkstack.tethering:drawable/stat_sys_tether_bluetooth</item>
+ <item>WIFI|USB,WIFI|BT,USB|BT,WIFI|USB|BT;com.android.networkstack.tethering:drawable/stat_sys_tether_general</item>
+ </string-array>
+ <!-- String for tether enable notification title. -->
+ <string name="tethering_notification_title">@string/tethered_notification_title</string>
+ <!-- String for tether enable notification message. -->
+ <string name="tethering_notification_message">@string/tethered_notification_message</string>
</resources>
diff --git a/packages/Tethering/res/values/overlayable.xml b/packages/Tethering/res/values/overlayable.xml
index fe025c7..bbba3f3 100644
--- a/packages/Tethering/res/values/overlayable.xml
+++ b/packages/Tethering/res/values/overlayable.xml
@@ -16,6 +16,7 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<overlayable name="TetheringConfig">
<policy type="product|system|vendor">
+ <!-- Params from config.xml that can be overlaid -->
<item type="array" name="config_tether_usb_regexs"/>
<item type="array" name="config_tether_ncm_regexs" />
<item type="array" name="config_tether_wifi_regexs"/>
@@ -31,6 +32,45 @@
<item type="string" name="config_mobile_hotspot_provision_response"/>
<item type="integer" name="config_mobile_hotspot_provision_check_period"/>
<item type="string" name="config_wifi_tether_enable"/>
+ <!-- Configuration values for TetheringNotificationUpdater -->
+ <!-- Icons for showing tether enable notification.
+ Each item should have two elements and be separated with ";".
+
+ The first element is downstream types which is one of tethering. This element has to be
+ made by WIFI, USB, BT, and OR'd with the others. Use "|" to combine multiple downstream
+ types and use "," to separate each combinations. Such as
+
+ USB|BT,WIFI|USB|BT
+
+ The second element is icon for the item. This element has to be composed by
+ <package name>:drawable/<resource name>. Such as
+
+ 1. com.android.networkstack.tethering:drawable/stat_sys_tether_general
+ 2. android:drawable/xxx
+
+ So the entire string of each item would be
+
+ USB|BT,WIFI|USB|BT;com.android.networkstack.tethering:drawable/stat_sys_tether_general
+
+ NOTE: One config can be separated into two or more for readability. Such as
+
+ WIFI|USB,WIFI|BT,USB|BT,WIFI|USB|BT;android:drawable/xxx
+
+ can be separated into
+
+ WIFI|USB;android:drawable/xxx
+ WIFI|BT;android:drawable/xxx
+ USB|BT;android:drawable/xxx
+ WIFI|USB|BT;android:drawable/xxx
+
+ Notification will not show if the downstream type isn't listed in array.
+ Empty array means disable notifications. -->
+ <item type="array" name="tethering_notification_icons"/>
+ <!-- String for tether enable notification title. -->
+ <item type="string" name="tethering_notification_title"/>
+ <!-- String for tether enable notification message. -->
+ <item type="string" name="tethering_notification_message"/>
+ <!-- Params from config.xml that can be overlaid -->
</policy>
</overlayable>
</resources>
diff --git a/packages/Tethering/res/values/strings.xml b/packages/Tethering/res/values/strings.xml
index 792bce9..ba98a66 100644
--- a/packages/Tethering/res/values/strings.xml
+++ b/packages/Tethering/res/values/strings.xml
@@ -15,19 +15,21 @@
-->
<resources>
<!-- Shown when the device is tethered -->
- <!-- Strings for tethered notification title [CHAR LIMIT=200] -->
+ <!-- String for tethered notification title [CHAR LIMIT=200] -->
<string name="tethered_notification_title">Tethering or hotspot active</string>
- <!-- Strings for tethered notification message [CHAR LIMIT=200] -->
+ <!-- String for tethered notification message [CHAR LIMIT=200] -->
<string name="tethered_notification_message">Tap to set up.</string>
<!-- This notification is shown when tethering has been disabled on a user's device.
The device is managed by the user's employer. Tethering can't be turned on unless the
IT administrator allows it. The noun "admin" is another reference for "IT administrator." -->
- <!-- Strings for tether disabling notification title [CHAR LIMIT=200] -->
+ <!-- String for tether disabling notification title [CHAR LIMIT=200] -->
<string name="disable_tether_notification_title">Tethering is disabled</string>
- <!-- Strings for tether disabling notification message [CHAR LIMIT=200] -->
+ <!-- String for tether disabling notification message [CHAR LIMIT=200] -->
<string name="disable_tether_notification_message">Contact your admin for details</string>
- <!-- Strings for tether notification channel name [CHAR LIMIT=200] -->
+ <!-- This string should be consistent with the "Hotspot & tethering" text in the "Network and
+ Internet" settings page. That is currently the tether_settings_title_all string. -->
+ <!-- String for tether notification channel name [CHAR LIMIT=200] -->
<string name="notification_channel_tethering_status">Hotspot & tethering status</string>
</resources>
\ No newline at end of file
diff --git a/packages/Tethering/src/android/net/ip/IpServer.java b/packages/Tethering/src/android/net/ip/IpServer.java
index 3acc766..6c0c432 100644
--- a/packages/Tethering/src/android/net/ip/IpServer.java
+++ b/packages/Tethering/src/android/net/ip/IpServer.java
@@ -24,6 +24,7 @@
import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
import static android.net.util.NetworkConstants.asByte;
import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
+import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
import android.net.INetd;
import android.net.INetworkStackStatusCallback;
@@ -448,7 +449,9 @@
final ArrayList<TetheredClient> leases = new ArrayList<>();
for (DhcpLeaseParcelable lease : leaseParcelables) {
final LinkAddress address = new LinkAddress(
- intToInet4AddressHTH(lease.netAddr), lease.prefixLength);
+ intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
+ 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
+ lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
final MacAddress macAddress;
try {
@@ -460,7 +463,7 @@
}
final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
- address, lease.hostname, lease.expTime);
+ address, lease.hostname);
leases.add(new TetheredClient(
macAddress,
Collections.singletonList(addressInfo),
@@ -810,7 +813,7 @@
rule.dstMac.toByteArray());
mIpv6ForwardingRules.put(rule.address, rule);
} catch (RemoteException | ServiceSpecificException e) {
- Log.e(TAG, "Could not add IPv6 downstream rule: " + e);
+ mLog.e("Could not add IPv6 downstream rule: ", e);
}
}
@@ -821,10 +824,17 @@
mIpv6ForwardingRules.remove(rule.address);
}
} catch (RemoteException | ServiceSpecificException e) {
- Log.e(TAG, "Could not remove IPv6 downstream rule: " + e);
+ mLog.e("Could not remove IPv6 downstream rule: ", e);
}
}
+ private void clearIpv6ForwardingRules() {
+ for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
+ removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
+ }
+ mIpv6ForwardingRules.clear();
+ }
+
// Convenience method to replace a rule with the same rule on a new upstream interface.
// Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
// Relies on the fact that rules are in a map indexed by IP address.
@@ -837,6 +847,12 @@
// changes or if a neighbor event is received.
private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
NeighborEvent e) {
+ // If we no longer have an upstream, clear forwarding rules and do nothing else.
+ if (upstreamIfindex == 0) {
+ clearIpv6ForwardingRules();
+ return;
+ }
+
// If the upstream interface has changed, remove all rules and re-add them with the new
// upstream interface.
if (prevUpstreamIfindex != upstreamIfindex) {
@@ -846,13 +862,14 @@
}
// If we're here to process a NeighborEvent, do so now.
+ // mInterfaceParams must be non-null or the event would not have arrived.
if (e == null) return;
if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
|| e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
return;
}
- Ipv6ForwardingRule rule = new Ipv6ForwardingRule(mLastIPv6UpstreamIfindex,
+ Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
e.macAddr);
if (e.isValid()) {
@@ -1095,6 +1112,7 @@
for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
mUpstreamIfaceSet = null;
+ clearIpv6ForwardingRules();
}
private void cleanupUpstreamInterface(String upstreamIface) {
diff --git a/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadController.java b/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadController.java
index cc36f4a..a402ffa 100644
--- a/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadController.java
+++ b/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadController.java
@@ -288,10 +288,18 @@
@Override
public void setLimit(String iface, long quotaBytes) {
- mLog.i("setLimit: " + iface + "," + quotaBytes);
// Listen for all iface is necessary since upstream might be changed after limit
// is set.
mHandler.post(() -> {
+ final Long curIfaceQuota = mInterfaceQuotas.get(iface);
+
+ // If the quota is set to unlimited, the value set to HAL is Long.MAX_VALUE,
+ // which is ~8.4 x 10^6 TiB, no one can actually reach it. Thus, it is not
+ // useful to set it multiple times.
+ // Otherwise, the quota needs to be updated to tell HAL to re-count from now even
+ // if the quota is the same as the existing one.
+ if (null == curIfaceQuota && QUOTA_UNLIMITED == quotaBytes) return;
+
if (quotaBytes == QUOTA_UNLIMITED) {
mInterfaceQuotas.remove(iface);
} else {
@@ -323,7 +331,6 @@
@Override
public void requestStatsUpdate(int token) {
- mLog.i("requestStatsUpdate: " + token);
// Do not attempt to update stats by querying the offload HAL
// synchronously from a different thread than the Handler thread. http://b/64771555.
mHandler.post(() -> {
diff --git a/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java b/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java
index ca74430..3d8dbab 100644
--- a/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java
+++ b/packages/Tethering/src/com/android/server/connectivity/tethering/Tethering.java
@@ -44,6 +44,9 @@
import static android.net.TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
import static android.net.TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
import static android.net.TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
+import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_FAILED;
+import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STARTED;
+import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STOPPED;
import static android.net.util.TetheringMessageBase.BASE_MASTER;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE;
@@ -56,10 +59,8 @@
import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
+import static com.android.server.connectivity.tethering.TetheringNotificationUpdater.DOWNSTREAM_NONE;
+
import android.app.usage.NetworkStatsManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothPan;
@@ -69,7 +70,6 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.res.Resources;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.EthernetManager;
@@ -125,7 +125,6 @@
import com.android.internal.util.MessageUtils;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
-import com.android.networkstack.tethering.R;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -220,14 +219,14 @@
private final UserRestrictionActionListener mTetheringRestriction;
private final ActiveDataSubIdListener mActiveDataSubIdListener;
private final ConnectedClientsTracker mConnectedClientsTracker;
+ private final TetheringThreadExecutor mExecutor;
+ private final TetheringNotificationUpdater mNotificationUpdater;
private int mActiveDataSubId = INVALID_SUBSCRIPTION_ID;
// All the usage of mTetheringEventCallback should run in the same thread.
private ITetheringEventCallback mTetheringEventCallback = null;
private volatile TetheringConfiguration mConfig;
private InterfaceSet mCurrentUpstreamIfaceSet;
- private Notification.Builder mTetheredNotificationBuilder;
- private int mLastNotificationId;
private boolean mRndisEnabled; // track the RNDIS function enabled state
// True iff. WiFi tethering should be started when soft AP is ready.
@@ -236,6 +235,7 @@
private TetherStatesParcel mTetherStatesParcel;
private boolean mDataSaverEnabled = false;
private String mWifiP2pTetherInterface = null;
+ private int mOffloadStatus = TETHER_HARDWARE_OFFLOAD_STOPPED;
@GuardedBy("mPublicSync")
private EthernetManager.TetheredInterfaceRequest mEthernetIfaceRequest;
@@ -250,6 +250,7 @@
mContext = mDeps.getContext();
mNetd = mDeps.getINetd(mContext);
mLooper = mDeps.getTetheringLooper();
+ mNotificationUpdater = mDeps.getNotificationUpdater(mContext);
mPublicSync = new Object();
@@ -296,8 +297,8 @@
final UserManager userManager = (UserManager) mContext.getSystemService(
Context.USER_SERVICE);
mTetheringRestriction = new UserRestrictionActionListener(userManager, this);
- final TetheringThreadExecutor executor = new TetheringThreadExecutor(mHandler);
- mActiveDataSubIdListener = new ActiveDataSubIdListener(executor);
+ mExecutor = new TetheringThreadExecutor(mHandler);
+ mActiveDataSubIdListener = new ActiveDataSubIdListener(mExecutor);
// Load tethering configuration.
updateConfiguration();
@@ -315,9 +316,7 @@
final WifiManager wifiManager = getWifiManager();
if (wifiManager != null) {
- wifiManager.registerSoftApCallback(
- mHandler::post /* executor */,
- new TetheringSoftApCallback());
+ wifiManager.registerSoftApCallback(mExecutor, new TetheringSoftApCallback());
}
}
@@ -606,14 +605,17 @@
Context.ETHERNET_SERVICE);
synchronized (mPublicSync) {
if (enable) {
+ if (mEthernetCallback != null) return TETHER_ERROR_NO_ERROR;
+
mEthernetCallback = new EthernetCallback();
- mEthernetIfaceRequest = em.requestTetheredInterface(mEthernetCallback);
+ mEthernetIfaceRequest = em.requestTetheredInterface(mExecutor, mEthernetCallback);
} else {
- if (mConfiguredEthernetIface != null) {
- stopEthernetTetheringLocked();
+ stopEthernetTetheringLocked();
+ if (mEthernetCallback != null) {
mEthernetIfaceRequest.release();
+ mEthernetCallback = null;
+ mEthernetIfaceRequest = null;
}
- mEthernetCallback = null;
}
}
return TETHER_ERROR_NO_ERROR;
@@ -732,13 +734,10 @@
final ArrayList<String> erroredList = new ArrayList<>();
final ArrayList<Integer> lastErrorList = new ArrayList<>();
- boolean wifiTethered = false;
- boolean usbTethered = false;
- boolean bluetoothTethered = false;
-
final TetheringConfiguration cfg = mConfig;
mTetherStatesParcel = new TetherStatesParcel();
+ int downstreamTypesMask = DOWNSTREAM_NONE;
synchronized (mPublicSync) {
for (int i = 0; i < mTetherStates.size(); i++) {
TetherState tetherState = mTetherStates.valueAt(i);
@@ -752,11 +751,11 @@
localOnlyList.add(iface);
} else if (tetherState.lastState == IpServer.STATE_TETHERED) {
if (cfg.isUsb(iface)) {
- usbTethered = true;
+ downstreamTypesMask |= (1 << TETHERING_USB);
} else if (cfg.isWifi(iface)) {
- wifiTethered = true;
+ downstreamTypesMask |= (1 << TETHERING_WIFI);
} else if (cfg.isBluetooth(iface)) {
- bluetoothTethered = true;
+ downstreamTypesMask |= (1 << TETHERING_BLUETOOTH);
}
tetherList.add(iface);
}
@@ -790,98 +789,7 @@
"error", TextUtils.join(",", erroredList)));
}
- if (usbTethered) {
- if (wifiTethered || bluetoothTethered) {
- showTetheredNotification(R.drawable.stat_sys_tether_general);
- } else {
- showTetheredNotification(R.drawable.stat_sys_tether_usb);
- }
- } else if (wifiTethered) {
- if (bluetoothTethered) {
- showTetheredNotification(R.drawable.stat_sys_tether_general);
- } else {
- /* We now have a status bar icon for WifiTethering, so drop the notification */
- clearTetheredNotification();
- }
- } else if (bluetoothTethered) {
- showTetheredNotification(R.drawable.stat_sys_tether_bluetooth);
- } else {
- clearTetheredNotification();
- }
- }
-
- private void showTetheredNotification(int id) {
- showTetheredNotification(id, true);
- }
-
- @VisibleForTesting
- protected void showTetheredNotification(int id, boolean tetheringOn) {
- NotificationManager notificationManager =
- (NotificationManager) mContext.createContextAsUser(UserHandle.ALL, 0)
- .getSystemService(Context.NOTIFICATION_SERVICE);
- if (notificationManager == null) {
- return;
- }
- final NotificationChannel channel = new NotificationChannel(
- "TETHERING_STATUS",
- mContext.getResources().getString(R.string.notification_channel_tethering_status),
- NotificationManager.IMPORTANCE_LOW);
- notificationManager.createNotificationChannel(channel);
-
- if (mLastNotificationId != 0) {
- if (mLastNotificationId == id) {
- return;
- }
- notificationManager.cancel(null, mLastNotificationId);
- mLastNotificationId = 0;
- }
-
- Intent intent = new Intent();
- intent.setClassName("com.android.settings", "com.android.settings.TetherSettings");
- intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
-
- PendingIntent pi = PendingIntent.getActivity(
- mContext.createContextAsUser(UserHandle.CURRENT, 0), 0, intent, 0, null);
-
- Resources r = mContext.getResources();
- final CharSequence title;
- final CharSequence message;
-
- if (tetheringOn) {
- title = r.getText(R.string.tethered_notification_title);
- message = r.getText(R.string.tethered_notification_message);
- } else {
- title = r.getText(R.string.disable_tether_notification_title);
- message = r.getText(R.string.disable_tether_notification_message);
- }
-
- if (mTetheredNotificationBuilder == null) {
- mTetheredNotificationBuilder = new Notification.Builder(mContext, channel.getId());
- mTetheredNotificationBuilder.setWhen(0)
- .setOngoing(true)
- .setColor(mContext.getColor(
- android.R.color.system_notification_accent_color))
- .setVisibility(Notification.VISIBILITY_PUBLIC)
- .setCategory(Notification.CATEGORY_STATUS);
- }
- mTetheredNotificationBuilder.setSmallIcon(id)
- .setContentTitle(title)
- .setContentText(message)
- .setContentIntent(pi);
- mLastNotificationId = id;
-
- notificationManager.notify(null, mLastNotificationId, mTetheredNotificationBuilder.build());
- }
-
- @VisibleForTesting
- protected void clearTetheredNotification() {
- NotificationManager notificationManager =
- (NotificationManager) mContext.createContextAsUser(UserHandle.ALL, 0)
- .getSystemService(Context.NOTIFICATION_SERVICE);
- if (notificationManager != null && mLastNotificationId != 0) {
- notificationManager.cancel(null, mLastNotificationId);
- mLastNotificationId = 0;
- }
+ mNotificationUpdater.onDownstreamChanged(downstreamTypesMask);
}
private class StateReceiver extends BroadcastReceiver {
@@ -1075,12 +983,10 @@
return;
}
- mWrapper.clearTetheredNotification();
+ // TODO: Add user restrictions notification.
final boolean isTetheringActiveOnDevice = (mWrapper.getTetheredIfaces().length != 0);
if (newlyDisallowed && isTetheringActiveOnDevice) {
- mWrapper.showTetheredNotification(
- R.drawable.stat_sys_tether_general, false);
mWrapper.untetherAll();
// TODO(b/148139325): send tetheringSupported on restriction change
}
@@ -1899,12 +1805,15 @@
// OffloadController implementation.
class OffloadWrapper {
public void start() {
- mOffloadController.start();
+ final int status = mOffloadController.start() ? TETHER_HARDWARE_OFFLOAD_STARTED
+ : TETHER_HARDWARE_OFFLOAD_FAILED;
+ updateOffloadStatus(status);
sendOffloadExemptPrefixes();
}
public void stop() {
mOffloadController.stop();
+ updateOffloadStatus(TETHER_HARDWARE_OFFLOAD_STOPPED);
}
public void updateUpstreamNetworkState(UpstreamNetworkState ns) {
@@ -1965,6 +1874,13 @@
mOffloadController.setLocalPrefixes(localPrefixes);
}
+
+ private void updateOffloadStatus(final int newStatus) {
+ if (newStatus == mOffloadStatus) return;
+
+ mOffloadStatus = newStatus;
+ reportOffloadStatusChanged(mOffloadStatus);
+ }
}
}
@@ -1999,6 +1915,7 @@
parcel.tetheredClients = hasListPermission
? mConnectedClientsTracker.getLastTetheredClients()
: Collections.emptyList();
+ parcel.offloadStatus = mOffloadStatus;
try {
callback.onCallbackStarted(parcel);
} catch (RemoteException e) {
@@ -2093,6 +2010,21 @@
}
}
+ private void reportOffloadStatusChanged(final int status) {
+ final int length = mTetheringEventCallbacks.beginBroadcast();
+ try {
+ for (int i = 0; i < length; i++) {
+ try {
+ mTetheringEventCallbacks.getBroadcastItem(i).onOffloadStatusChanged(status);
+ } catch (RemoteException e) {
+ // Not really very much to do here.
+ }
+ }
+ } finally {
+ mTetheringEventCallbacks.finishBroadcast();
+ }
+ }
+
void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer, @Nullable String[] args) {
// Binder.java closes the resource for us.
@SuppressWarnings("resource")
diff --git a/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java b/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java
index e019c3a..0330dad 100644
--- a/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java
+++ b/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java
@@ -26,6 +26,8 @@
import android.os.IBinder;
import android.os.Looper;
+import androidx.annotation.NonNull;
+
import com.android.internal.util.StateMachine;
import java.util.ArrayList;
@@ -102,6 +104,13 @@
}
/**
+ * Get a reference to the TetheringNotificationUpdater to be used by tethering.
+ */
+ public TetheringNotificationUpdater getNotificationUpdater(@NonNull final Context ctx) {
+ return new TetheringNotificationUpdater(ctx);
+ }
+
+ /**
* Get tethering thread looper.
*/
public abstract Looper getTetheringLooper();
diff --git a/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringNotificationUpdater.java b/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringNotificationUpdater.java
new file mode 100644
index 0000000..b97f752
--- /dev/null
+++ b/packages/Tethering/src/com/android/server/connectivity/tethering/TetheringNotificationUpdater.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2020 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.connectivity.tethering;
+
+import static android.net.TetheringManager.TETHERING_BLUETOOTH;
+import static android.net.TetheringManager.TETHERING_USB;
+import static android.net.TetheringManager.TETHERING_WIFI;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.os.UserHandle;
+import android.provider.Settings;
+import android.text.TextUtils;
+import android.util.Log;
+import android.util.SparseArray;
+
+import androidx.annotation.ArrayRes;
+import androidx.annotation.DrawableRes;
+import androidx.annotation.IntRange;
+import androidx.annotation.NonNull;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.networkstack.tethering.R;
+
+/**
+ * A class to display tethering-related notifications.
+ *
+ * <p>This class is not thread safe, it is intended to be used only from the tethering handler
+ * thread. However the constructor is an exception, as it is called on another thread ;
+ * therefore for thread safety all members of this class MUST either be final or initialized
+ * to their default value (0, false or null).
+ *
+ * @hide
+ */
+public class TetheringNotificationUpdater {
+ private static final String TAG = TetheringNotificationUpdater.class.getSimpleName();
+ private static final String CHANNEL_ID = "TETHERING_STATUS";
+ private static final boolean NOTIFY_DONE = true;
+ private static final boolean NO_NOTIFY = false;
+ // Id to update and cancel tethering notification. Must be unique within the tethering app.
+ private static final int NOTIFY_ID = 20191115;
+ @VisibleForTesting
+ static final int NO_ICON_ID = 0;
+ @VisibleForTesting
+ static final int DOWNSTREAM_NONE = 0;
+ private final Context mContext;
+ private final NotificationManager mNotificationManager;
+ private final NotificationChannel mChannel;
+ // Downstream type is one of ConnectivityManager.TETHERING_* constants, 0 1 or 2.
+ // This value has to be made 1 2 and 4, and OR'd with the others.
+ // WARNING : the constructor is called on a different thread. Thread safety therefore
+ // relies on this value being initialized to 0, and not any other value. If you need
+ // to change this, you will need to change the thread where the constructor is invoked,
+ // or to introduce synchronization.
+ private int mDownstreamTypesMask = DOWNSTREAM_NONE;
+
+ public TetheringNotificationUpdater(@NonNull final Context context) {
+ mContext = context;
+ mNotificationManager = (NotificationManager) context.createContextAsUser(UserHandle.ALL, 0)
+ .getSystemService(Context.NOTIFICATION_SERVICE);
+ mChannel = new NotificationChannel(
+ CHANNEL_ID,
+ context.getResources().getString(R.string.notification_channel_tethering_status),
+ NotificationManager.IMPORTANCE_LOW);
+ mNotificationManager.createNotificationChannel(mChannel);
+ }
+
+ /** Called when downstream has changed */
+ public void onDownstreamChanged(@IntRange(from = 0, to = 7) final int downstreamTypesMask) {
+ if (mDownstreamTypesMask == downstreamTypesMask) return;
+ mDownstreamTypesMask = downstreamTypesMask;
+ updateNotification();
+ }
+
+ private void updateNotification() {
+ final boolean tetheringInactive = mDownstreamTypesMask <= DOWNSTREAM_NONE;
+
+ if (tetheringInactive || setupNotification() == NO_NOTIFY) {
+ clearNotification();
+ }
+ }
+
+ private void clearNotification() {
+ mNotificationManager.cancel(null /* tag */, NOTIFY_ID);
+ }
+
+ /**
+ * Returns the downstream types mask which convert from given string.
+ *
+ * @param types This string has to be made by "WIFI", "USB", "BT", and OR'd with the others.
+ *
+ * @return downstream types mask value.
+ */
+ @IntRange(from = 0, to = 7)
+ private int getDownstreamTypesMask(@NonNull final String types) {
+ int downstreamTypesMask = DOWNSTREAM_NONE;
+ final String[] downstreams = types.split("\\|");
+ for (String downstream : downstreams) {
+ if ("USB".equals(downstream.trim())) {
+ downstreamTypesMask |= (1 << TETHERING_USB);
+ } else if ("WIFI".equals(downstream.trim())) {
+ downstreamTypesMask |= (1 << TETHERING_WIFI);
+ } else if ("BT".equals(downstream.trim())) {
+ downstreamTypesMask |= (1 << TETHERING_BLUETOOTH);
+ }
+ }
+ return downstreamTypesMask;
+ }
+
+ /**
+ * Returns the icons {@link android.util.SparseArray} which get from given string-array resource
+ * id.
+ *
+ * @param id String-array resource id
+ *
+ * @return {@link android.util.SparseArray} with downstream types and icon id info.
+ */
+ @NonNull
+ private SparseArray<Integer> getIcons(@ArrayRes int id) {
+ final Resources res = mContext.getResources();
+ final String[] array = res.getStringArray(id);
+ final SparseArray<Integer> icons = new SparseArray<>();
+ for (String config : array) {
+ if (TextUtils.isEmpty(config)) continue;
+
+ final String[] elements = config.split(";");
+ if (elements.length != 2) {
+ Log.wtf(TAG,
+ "Unexpected format in Tethering notification configuration : " + config);
+ continue;
+ }
+
+ final String[] types = elements[0].split(",");
+ for (String type : types) {
+ int mask = getDownstreamTypesMask(type);
+ if (mask == DOWNSTREAM_NONE) continue;
+ icons.put(mask, res.getIdentifier(
+ elements[1].trim(), null /* defType */, null /* defPackage */));
+ }
+ }
+ return icons;
+ }
+
+ private boolean setupNotification() {
+ final Resources res = mContext.getResources();
+ final SparseArray<Integer> downstreamIcons = getIcons(R.array.tethering_notification_icons);
+
+ final int iconId = downstreamIcons.get(mDownstreamTypesMask, NO_ICON_ID);
+ if (iconId == NO_ICON_ID) return NO_NOTIFY;
+
+ final String title = res.getString(R.string.tethering_notification_title);
+ final String message = res.getString(R.string.tethering_notification_message);
+
+ showNotification(iconId, title, message);
+ return NOTIFY_DONE;
+ }
+
+ private void showNotification(@DrawableRes final int iconId, @NonNull final String title,
+ @NonNull final String message) {
+ final Intent intent = new Intent(Settings.ACTION_TETHER_SETTINGS);
+ final PendingIntent pi = PendingIntent.getActivity(
+ mContext.createContextAsUser(UserHandle.CURRENT, 0),
+ 0 /* requestCode */, intent, 0 /* flags */, null /* options */);
+ final Notification notification =
+ new Notification.Builder(mContext, mChannel.getId())
+ .setSmallIcon(iconId)
+ .setContentTitle(title)
+ .setContentText(message)
+ .setOngoing(true)
+ .setColor(mContext.getColor(
+ android.R.color.system_notification_accent_color))
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .setCategory(Notification.CATEGORY_STATUS)
+ .setContentIntent(pi)
+ .build();
+
+ mNotificationManager.notify(null /* tag */, NOTIFY_ID, notification);
+ }
+}
diff --git a/packages/Tethering/tests/unit/src/android/net/TetheredClientTest.kt b/packages/Tethering/tests/unit/src/android/net/TetheredClientTest.kt
index d85389a..a20a0df 100644
--- a/packages/Tethering/tests/unit/src/android/net/TetheredClientTest.kt
+++ b/packages/Tethering/tests/unit/src/android/net/TetheredClientTest.kt
@@ -20,6 +20,7 @@
import android.net.TetheredClient.AddressInfo
import android.net.TetheringManager.TETHERING_BLUETOOTH
import android.net.TetheringManager.TETHERING_USB
+import android.system.OsConstants.RT_SCOPE_UNIVERSE
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import com.android.testutils.assertParcelSane
@@ -30,11 +31,19 @@
private val TEST_MACADDR = MacAddress.fromBytes(byteArrayOf(12, 23, 34, 45, 56, 67))
private val TEST_OTHER_MACADDR = MacAddress.fromBytes(byteArrayOf(23, 34, 45, 56, 67, 78))
-private val TEST_ADDR1 = LinkAddress(parseNumericAddress("192.168.113.3"), 24)
-private val TEST_ADDR2 = LinkAddress(parseNumericAddress("fe80::1:2:3"), 64)
+private val TEST_ADDR1 = makeLinkAddress("192.168.113.3", prefixLength = 24, expTime = 123L)
+private val TEST_ADDR2 = makeLinkAddress("fe80::1:2:3", prefixLength = 64, expTime = 456L)
private val TEST_ADDRINFO1 = AddressInfo(TEST_ADDR1, "test_hostname")
private val TEST_ADDRINFO2 = AddressInfo(TEST_ADDR2, null)
+private fun makeLinkAddress(addr: String, prefixLength: Int, expTime: Long) = LinkAddress(
+ parseNumericAddress(addr),
+ prefixLength,
+ 0 /* flags */,
+ RT_SCOPE_UNIVERSE,
+ expTime /* deprecationTime */,
+ expTime /* expirationTime */)
+
@RunWith(AndroidJUnit4::class)
@SmallTest
class TetheredClientTest {
diff --git a/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java b/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
index 33b3558..948266d 100644
--- a/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
+++ b/packages/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
@@ -43,6 +43,7 @@
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
@@ -546,9 +547,9 @@
reset(mNetd);
// Link-local and multicast neighbors are ignored.
- recvNewNeigh(notMyIfindex, neighLL, NUD_REACHABLE, macA);
+ recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, macA);
verifyNoMoreInteractions(mNetd);
- recvNewNeigh(notMyIfindex, neighMC, NUD_REACHABLE, macA);
+ recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, macA);
verifyNoMoreInteractions(mNetd);
// A neighbor that is no longer valid causes the rule to be removed.
@@ -578,6 +579,52 @@
eq(neighB.getAddress()), eq(myMac.toByteArray()), eq(macB.toByteArray()));
inOrder.verify(mNetd).tetherRuleRemoveDownstreamIpv6(eq(UPSTREAM_IFINDEX),
eq(neighB.getAddress()));
+ reset(mNetd);
+
+ // When the upstream is lost, rules are removed.
+ dispatchTetherConnectionChanged(null, null);
+ verify(mNetd).tetherRuleRemoveDownstreamIpv6(eq(UPSTREAM_IFINDEX2),
+ eq(neighA.getAddress()));
+ verify(mNetd).tetherRuleRemoveDownstreamIpv6(eq(UPSTREAM_IFINDEX2),
+ eq(neighB.getAddress()));
+ reset(mNetd);
+
+ // If the upstream is IPv4-only, no rules are added.
+ dispatchTetherConnectionChanged(UPSTREAM_IFACE);
+ reset(mNetd);
+ recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
+ verifyNoMoreInteractions(mNetd);
+
+ // Rules can be added again once upstream IPv6 connectivity is available.
+ lp.setInterfaceName(UPSTREAM_IFACE);
+ dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp);
+ recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
+ verify(mNetd).tetherRuleAddDownstreamIpv6(eq(myIfindex), eq(UPSTREAM_IFINDEX),
+ eq(neighB.getAddress()), eq(myMac.toByteArray()), eq(macB.toByteArray()));
+ verify(mNetd, never()).tetherRuleAddDownstreamIpv6(anyInt(), anyInt(),
+ eq(neighA.getAddress()), any(), any());
+
+ // If upstream IPv6 connectivity is lost, rules are removed.
+ reset(mNetd);
+ dispatchTetherConnectionChanged(UPSTREAM_IFACE, null);
+ verify(mNetd).tetherRuleRemoveDownstreamIpv6(eq(UPSTREAM_IFINDEX), eq(neighB.getAddress()));
+
+ // When the interface goes down, rules are removed.
+ lp.setInterfaceName(UPSTREAM_IFACE);
+ dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp);
+ recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
+ recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
+ verify(mNetd).tetherRuleAddDownstreamIpv6(eq(myIfindex), eq(UPSTREAM_IFINDEX),
+ eq(neighA.getAddress()), eq(myMac.toByteArray()), eq(macA.toByteArray()));
+ verify(mNetd).tetherRuleAddDownstreamIpv6(eq(myIfindex), eq(UPSTREAM_IFINDEX),
+ eq(neighB.getAddress()), eq(myMac.toByteArray()), eq(macB.toByteArray()));
+ reset(mNetd);
+
+ mIpServer.stop();
+ mLooper.dispatchAll();
+ verify(mNetd).tetherRuleRemoveDownstreamIpv6(eq(UPSTREAM_IFINDEX), eq(neighA.getAddress()));
+ verify(mNetd).tetherRuleRemoveDownstreamIpv6(eq(UPSTREAM_IFINDEX), eq(neighB.getAddress()));
+ reset(mNetd);
}
private void assertDhcpStarted(IpPrefix expectedPrefix) throws Exception {
@@ -624,16 +671,15 @@
* @param v6lp IPv6 LinkProperties of the upstream interface, or null for an IPv4-only upstream.
*/
private void dispatchTetherConnectionChanged(String upstreamIface, LinkProperties v6lp) {
- mIpServer.sendMessage(IpServer.CMD_TETHER_CONNECTION_CHANGED,
- new InterfaceSet(upstreamIface));
- if (v6lp != null) {
- mIpServer.sendMessage(IpServer.CMD_IPV6_TETHER_UPDATE, v6lp);
- }
+ dispatchTetherConnectionChanged(upstreamIface);
+ mIpServer.sendMessage(IpServer.CMD_IPV6_TETHER_UPDATE, v6lp);
mLooper.dispatchAll();
}
private void dispatchTetherConnectionChanged(String upstreamIface) {
- dispatchTetherConnectionChanged(upstreamIface, null);
+ final InterfaceSet ifs = (upstreamIface != null) ? new InterfaceSet(upstreamIface) : null;
+ mIpServer.sendMessage(IpServer.CMD_TETHER_CONNECTION_CHANGED, ifs);
+ mLooper.dispatchAll();
}
private void assertIPv4AddressAndDirectlyConnectedRoute(LinkProperties lp) {
diff --git a/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/ConnectedClientsTrackerTest.kt b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/ConnectedClientsTrackerTest.kt
index 56f3e21..1cdc3bb 100644
--- a/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/ConnectedClientsTrackerTest.kt
+++ b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/ConnectedClientsTrackerTest.kt
@@ -46,23 +46,28 @@
private val client1Addr = MacAddress.fromString("01:23:45:67:89:0A")
private val client1 = TetheredClient(client1Addr, listOf(
- AddressInfo(LinkAddress("192.168.43.44/32"), null /* hostname */, clock.time + 20)),
+ makeAddrInfo("192.168.43.44/32", null /* hostname */, clock.time + 20)),
TETHERING_WIFI)
private val wifiClient1 = makeWifiClient(client1Addr)
private val client2Addr = MacAddress.fromString("02:34:56:78:90:AB")
- private val client2Exp30AddrInfo = AddressInfo(
- LinkAddress("192.168.43.45/32"), "my_hostname", clock.time + 30)
+ private val client2Exp30AddrInfo = makeAddrInfo(
+ "192.168.43.45/32", "my_hostname", clock.time + 30)
private val client2 = TetheredClient(client2Addr, listOf(
client2Exp30AddrInfo,
- AddressInfo(LinkAddress("2001:db8:12::34/72"), "other_hostname", clock.time + 10)),
+ makeAddrInfo("2001:db8:12::34/72", "other_hostname", clock.time + 10)),
TETHERING_WIFI)
private val wifiClient2 = makeWifiClient(client2Addr)
private val client3Addr = MacAddress.fromString("03:45:67:89:0A:BC")
private val client3 = TetheredClient(client3Addr,
- listOf(AddressInfo(LinkAddress("2001:db8:34::34/72"), "other_other_hostname",
- clock.time + 10)),
+ listOf(makeAddrInfo("2001:db8:34::34/72", "other_other_hostname", clock.time + 10)),
TETHERING_USB)
+ private fun makeAddrInfo(addr: String, hostname: String?, expTime: Long) =
+ LinkAddress(addr).let {
+ AddressInfo(LinkAddress(it.address, it.prefixLength, it.flags, it.scope,
+ expTime /* deprecationTime */, expTime /* expirationTime */), hostname)
+ }
+
@Test
fun testUpdateConnectedClients() {
doReturn(emptyList<TetheredClient>()).`when`(server1).allLeases
diff --git a/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java
index f2074bd..820c852 100644
--- a/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java
+++ b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java
@@ -28,11 +28,15 @@
import static android.net.TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
import static android.net.TetheringManager.EXTRA_ACTIVE_TETHER;
import static android.net.TetheringManager.EXTRA_AVAILABLE_TETHER;
+import static android.net.TetheringManager.TETHERING_ETHERNET;
import static android.net.TetheringManager.TETHERING_NCM;
import static android.net.TetheringManager.TETHERING_USB;
import static android.net.TetheringManager.TETHERING_WIFI;
import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
import static android.net.TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
+import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_FAILED;
+import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STARTED;
+import static android.net.TetheringManager.TETHER_HARDWARE_OFFLOAD_STOPPED;
import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME;
import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE;
@@ -42,6 +46,8 @@
import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+import static com.android.server.connectivity.tethering.TetheringNotificationUpdater.DOWNSTREAM_NONE;
+
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -49,7 +55,6 @@
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.notNull;
-import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
@@ -75,6 +80,8 @@
import android.content.res.Resources;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
+import android.net.EthernetManager;
+import android.net.EthernetManager.TetheredInterfaceRequest;
import android.net.INetd;
import android.net.ITetheringEventCallback;
import android.net.InetAddresses;
@@ -166,6 +173,7 @@
@Mock private Context mContext;
@Mock private NetworkStatsManager mStatsManager;
@Mock private OffloadHardwareInterface mOffloadHardwareInterface;
+ @Mock private OffloadHardwareInterface.ForwardedStats mForwardedStats;
@Mock private Resources mResources;
@Mock private TelephonyManager mTelephonyManager;
@Mock private UsbManager mUsbManager;
@@ -180,6 +188,8 @@
@Mock private UserManager mUserManager;
@Mock private NetworkRequest mNetworkRequest;
@Mock private ConnectivityManager mCm;
+ @Mock private EthernetManager mEm;
+ @Mock private TetheringNotificationUpdater mNotificationUpdater;
private final MockIpServerDependencies mIpServerDependencies =
spy(new MockIpServerDependencies());
@@ -199,6 +209,7 @@
private PhoneStateListener mPhoneStateListener;
private InterfaceConfigurationParcel mInterfaceConfiguration;
+
private class TestContext extends BroadcastInterceptingContext {
TestContext(Context base) {
super(base);
@@ -232,6 +243,7 @@
if (Context.USER_SERVICE.equals(name)) return mUserManager;
if (Context.NETWORK_STATS_SERVICE.equals(name)) return mStatsManager;
if (Context.CONNECTIVITY_SERVICE.equals(name)) return mCm;
+ if (Context.ETHERNET_SERVICE.equals(name)) return mEm;
return super.getSystemService(name);
}
@@ -240,11 +252,6 @@
if (TelephonyManager.class.equals(serviceClass)) return Context.TELEPHONY_SERVICE;
return super.getSystemServiceName(serviceClass);
}
-
- @Override
- public Context createContextAsUser(UserHandle user, int flags) {
- return mContext;
- }
}
public class MockIpServerDependencies extends IpServer.Dependencies {
@@ -306,12 +313,10 @@
public class MockTetheringDependencies extends TetheringDependencies {
StateMachine mUpstreamNetworkMonitorMasterSM;
ArrayList<IpServer> mIpv6CoordinatorNotifyList;
- int mIsTetheringSupportedCalls;
public void reset() {
mUpstreamNetworkMonitorMasterSM = null;
mIpv6CoordinatorNotifyList = null;
- mIsTetheringSupportedCalls = 0;
}
@Override
@@ -345,7 +350,6 @@
@Override
public boolean isTetheringSupported() {
- mIsTetheringSupportedCalls++;
return true;
}
@@ -375,6 +379,11 @@
// TODO: add test for bluetooth tethering.
return null;
}
+
+ @Override
+ public TetheringNotificationUpdater getNotificationUpdater(Context ctx) {
+ return mNotificationUpdater;
+ }
}
private static UpstreamNetworkState buildMobileUpstreamState(boolean withIPv4,
@@ -458,9 +467,11 @@
mInterfaceConfiguration.flags = new String[0];
when(mRouterAdvertisementDaemon.start())
.thenReturn(true);
+ initOffloadConfiguration(true /* offloadConfig */, true /* offloadControl */,
+ 0 /* defaultDisabled */);
+ when(mOffloadHardwareInterface.getForwardedStats(any())).thenReturn(mForwardedStats);
mServiceContext = new TestContext(mContext);
- when(mContext.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(null);
mContentResolver = new MockContentResolver(mServiceContext);
mContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
mIntents = new Vector<>();
@@ -593,7 +604,8 @@
// it creates a IpServer and sends out a broadcast indicating that the
// interface is "available".
if (emulateInterfaceStatusChanged) {
- assertEquals(1, mTetheringDependencies.mIsTetheringSupportedCalls);
+ // There is 1 IpServer state change event: STATE_AVAILABLE
+ verify(mNotificationUpdater, times(1)).onDownstreamChanged(DOWNSTREAM_NONE);
verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER);
verify(mWifiManager).updateInterfaceIpState(
TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
@@ -677,9 +689,8 @@
verifyNoMoreInteractions(mWifiManager);
verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_ACTIVE_LOCAL_ONLY);
verify(mUpstreamNetworkMonitor, times(1)).startObserveAllNetworks();
- // This will be called twice, one is on entering IpServer.STATE_AVAILABLE,
- // and another one is on IpServer.STATE_TETHERED/IpServer.STATE_LOCAL_ONLY.
- assertEquals(2, mTetheringDependencies.mIsTetheringSupportedCalls);
+ // There are 2 IpServer state change events: STATE_AVAILABLE -> STATE_LOCAL_ONLY
+ verify(mNotificationUpdater, times(2)).onDownstreamChanged(DOWNSTREAM_NONE);
// Emulate externally-visible WifiManager effects, when hotspot mode
// is being torn down.
@@ -905,7 +916,8 @@
sendWifiApStateChanged(WIFI_AP_STATE_ENABLED);
mLooper.dispatchAll();
- assertEquals(1, mTetheringDependencies.mIsTetheringSupportedCalls);
+ // There is 1 IpServer state change event: STATE_AVAILABLE
+ verify(mNotificationUpdater, times(1)).onDownstreamChanged(DOWNSTREAM_NONE);
verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER);
verify(mWifiManager).updateInterfaceIpState(
TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
@@ -949,9 +961,9 @@
// In tethering mode, in the default configuration, an explicit request
// for a mobile network is also made.
verify(mUpstreamNetworkMonitor, times(1)).registerMobileNetworkRequest();
- // This will be called twice, one is on entering IpServer.STATE_AVAILABLE,
- // and another one is on IpServer.STATE_TETHERED/IpServer.STATE_LOCAL_ONLY.
- assertEquals(2, mTetheringDependencies.mIsTetheringSupportedCalls);
+ // There are 2 IpServer state change events: STATE_AVAILABLE -> STATE_TETHERED
+ verify(mNotificationUpdater, times(1)).onDownstreamChanged(DOWNSTREAM_NONE);
+ verify(mNotificationUpdater, times(1)).onDownstreamChanged(eq(1 << TETHERING_WIFI));
/////
// We do not currently emulate any upstream being found.
@@ -1022,9 +1034,10 @@
TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_UNSPECIFIED);
verify(mWifiManager).updateInterfaceIpState(
TEST_WLAN_IFNAME, WifiManager.IFACE_IP_MODE_TETHERED);
- // There are 3 state change event:
- // AVAILABLE -> STATE_TETHERED -> STATE_AVAILABLE.
- assertEquals(3, mTetheringDependencies.mIsTetheringSupportedCalls);
+ // There are 3 IpServer state change event:
+ // STATE_AVAILABLE -> STATE_TETHERED -> STATE_AVAILABLE.
+ verify(mNotificationUpdater, times(2)).onDownstreamChanged(DOWNSTREAM_NONE);
+ verify(mNotificationUpdater, times(1)).onDownstreamChanged(eq(1 << TETHERING_WIFI));
verifyTetheringBroadcast(TEST_WLAN_IFNAME, EXTRA_AVAILABLE_TETHER);
// This is called, but will throw.
verify(mNetd, times(1)).ipfwdEnableForwarding(TETHERING_NAME);
@@ -1059,9 +1072,6 @@
ural.onUserRestrictionsChanged();
verify(mockTethering, times(expectedInteractionsWithShowNotification))
- .showTetheredNotification(anyInt(), eq(false));
-
- verify(mockTethering, times(expectedInteractionsWithShowNotification))
.untetherAll();
}
@@ -1131,6 +1141,7 @@
private final ArrayList<TetheringConfigurationParcel> mTetheringConfigs =
new ArrayList<>();
private final ArrayList<TetherStatesParcel> mTetherStates = new ArrayList<>();
+ private final ArrayList<Integer> mOffloadStatus = new ArrayList<>();
// This function will remove the recorded callbacks, so it must be called once for
// each callback. If this is called after multiple callback, the order matters.
@@ -1166,6 +1177,11 @@
assertNoConfigChangeCallback();
}
+ public void expectOffloadStatusChanged(final int expectedStatus) {
+ assertOffloadStatusChangedCallback();
+ assertEquals(mOffloadStatus.remove(0), new Integer(expectedStatus));
+ }
+
public TetherStatesParcel pollTetherStatesChanged() {
assertStateChangeCallback();
return mTetherStates.remove(0);
@@ -1192,10 +1208,16 @@
}
@Override
+ public void onOffloadStatusChanged(final int status) {
+ mOffloadStatus.add(status);
+ }
+
+ @Override
public void onCallbackStarted(TetheringCallbackStartedParcel parcel) {
mActualUpstreams.add(parcel.upstreamNetwork);
mTetheringConfigs.add(parcel.config);
mTetherStates.add(parcel.states);
+ mOffloadStatus.add(parcel.offloadStatus);
}
@Override
@@ -1217,6 +1239,10 @@
assertFalse(mTetherStates.isEmpty());
}
+ public void assertOffloadStatusChangedCallback() {
+ assertFalse(mOffloadStatus.isEmpty());
+ }
+
public void assertNoCallback() {
assertNoUpstreamChangeCallback();
assertNoConfigChangeCallback();
@@ -1265,6 +1291,7 @@
mTethering.getTetheringConfiguration().toStableParcelable());
TetherStatesParcel tetherState = callback.pollTetherStatesChanged();
assertTetherStatesNotNullButEmpty(tetherState);
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED);
// 2. Enable wifi tethering.
UpstreamNetworkState upstreamState = buildMobileDualStackUpstreamState();
when(mUpstreamNetworkMonitor.getCurrentPreferredUpstream()).thenReturn(upstreamState);
@@ -1282,6 +1309,7 @@
tetherState = callback.pollTetherStatesChanged();
assertArrayEquals(tetherState.tetheredList, new String[] {TEST_WLAN_IFNAME});
callback.expectUpstreamChanged(upstreamState.network);
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STARTED);
// 3. Register second callback.
mTethering.registerTetheringEventCallback(callback2);
@@ -1291,6 +1319,7 @@
mTethering.getTetheringConfiguration().toStableParcelable());
tetherState = callback2.pollTetherStatesChanged();
assertEquals(tetherState.tetheredList, new String[] {TEST_WLAN_IFNAME});
+ callback2.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STARTED);
// 4. Unregister first callback and disable wifi tethering
mTethering.unregisterTetheringEventCallback(callback);
@@ -1302,10 +1331,59 @@
assertArrayEquals(tetherState.availableList, new String[] {TEST_WLAN_IFNAME});
mLooper.dispatchAll();
callback2.expectUpstreamChanged(new Network[] {null});
+ callback2.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED);
callback.assertNoCallback();
}
@Test
+ public void testReportFailCallbackIfOffloadNotSupported() throws Exception {
+ final UpstreamNetworkState upstreamState = buildMobileDualStackUpstreamState();
+ TestTetheringEventCallback callback = new TestTetheringEventCallback();
+ mTethering.registerTetheringEventCallback(callback);
+ mLooper.dispatchAll();
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED);
+
+ // 1. Offload fail if no OffloadConfig.
+ initOffloadConfiguration(false /* offloadConfig */, true /* offloadControl */,
+ 0 /* defaultDisabled */);
+ runUsbTethering(upstreamState);
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_FAILED);
+ runStopUSBTethering();
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED);
+ reset(mUsbManager);
+ // 2. Offload fail if no OffloadControl.
+ initOffloadConfiguration(true /* offloadConfig */, false /* offloadControl */,
+ 0 /* defaultDisabled */);
+ runUsbTethering(upstreamState);
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_FAILED);
+ runStopUSBTethering();
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED);
+ reset(mUsbManager);
+ // 3. Offload fail if disabled by settings.
+ initOffloadConfiguration(true /* offloadConfig */, true /* offloadControl */,
+ 1 /* defaultDisabled */);
+ runUsbTethering(upstreamState);
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_FAILED);
+ runStopUSBTethering();
+ callback.expectOffloadStatusChanged(TETHER_HARDWARE_OFFLOAD_STOPPED);
+ }
+
+ private void runStopUSBTethering() {
+ mTethering.stopTethering(TETHERING_USB);
+ mLooper.dispatchAll();
+ mTethering.interfaceRemoved(TEST_USB_IFNAME);
+ mLooper.dispatchAll();
+ }
+
+ private void initOffloadConfiguration(final boolean offloadConfig,
+ final boolean offloadControl, final int defaultDisabled) {
+ when(mOffloadHardwareInterface.initOffloadConfig()).thenReturn(offloadConfig);
+ when(mOffloadHardwareInterface.initOffloadControl(any())).thenReturn(offloadControl);
+ when(mOffloadHardwareInterface.getDefaultTetherOffloadDisabled()).thenReturn(
+ defaultDisabled);
+ }
+
+ @Test
public void testMultiSimAware() throws Exception {
final TetheringConfiguration initailConfig = mTethering.getTetheringConfiguration();
assertEquals(INVALID_SUBSCRIPTION_ID, initailConfig.activeDataSubId);
@@ -1316,6 +1394,24 @@
assertEquals(fakeSubId, newConfig.activeDataSubId);
}
+ @Test
+ public void testNoDuplicatedEthernetRequest() throws Exception {
+ final TetheredInterfaceRequest mockRequest = mock(TetheredInterfaceRequest.class);
+ when(mEm.requestTetheredInterface(any(), any())).thenReturn(mockRequest);
+ mTethering.startTethering(createTetheringRquestParcel(TETHERING_ETHERNET), null);
+ mLooper.dispatchAll();
+ verify(mEm, times(1)).requestTetheredInterface(any(), any());
+ mTethering.startTethering(createTetheringRquestParcel(TETHERING_ETHERNET), null);
+ mLooper.dispatchAll();
+ verifyNoMoreInteractions(mEm);
+ mTethering.stopTethering(TETHERING_ETHERNET);
+ mLooper.dispatchAll();
+ verify(mockRequest, times(1)).release();
+ mTethering.stopTethering(TETHERING_ETHERNET);
+ mLooper.dispatchAll();
+ verifyNoMoreInteractions(mEm);
+ }
+
private void workingWifiP2pGroupOwner(
boolean emulateInterfaceStatusChanged) throws Exception {
if (emulateInterfaceStatusChanged) {
@@ -1331,9 +1427,8 @@
verifyNoMoreInteractions(mNetd);
verifyTetheringBroadcast(TEST_P2P_IFNAME, EXTRA_ACTIVE_LOCAL_ONLY);
verify(mUpstreamNetworkMonitor, times(1)).startObserveAllNetworks();
- // This will be called twice, one is on entering IpServer.STATE_AVAILABLE,
- // and another one is on IpServer.STATE_TETHERED/IpServer.STATE_LOCAL_ONLY.
- assertEquals(2, mTetheringDependencies.mIsTetheringSupportedCalls);
+ // There are 2 IpServer state change events: STATE_AVAILABLE -> STATE_LOCAL_ONLY
+ verify(mNotificationUpdater, times(2)).onDownstreamChanged(DOWNSTREAM_NONE);
assertEquals(TETHER_ERROR_NO_ERROR, mTethering.getLastTetherError(TEST_P2P_IFNAME));
diff --git a/packages/overlays/DisplayCutoutEmulationWaterfallOverlay/res/values/config.xml b/packages/overlays/DisplayCutoutEmulationWaterfallOverlay/res/values/config.xml
index 6f692c8..b9c5f1d 100644
--- a/packages/overlays/DisplayCutoutEmulationWaterfallOverlay/res/values/config.xml
+++ b/packages/overlays/DisplayCutoutEmulationWaterfallOverlay/res/values/config.xml
@@ -16,6 +16,9 @@
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string translatable="false" name="config_mainBuiltInDisplayCutout"></string>
+ <string translatable="false" name="config_mainBuiltInDisplayCutoutRectApproximation"></string>
+
<!-- Height of the status bar in portrait. The height should be
Max((status bar content height + waterfall top size), top cutout size) -->
<dimen name="status_bar_height_portrait">28dp</dimen>
diff --git a/services/Android.bp b/services/Android.bp
index ef47867..c4be003 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -78,7 +78,7 @@
libs: [
"android.hidl.manager-V1.0-java",
- "framework-tethering-stubs",
+ "framework-tethering-stubs-module_libs_api",
],
plugins: [
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
index 5d699c0..5d97d21 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityWindowManager.java
@@ -1232,6 +1232,7 @@
*/
public boolean computePartialInteractiveRegionForWindowLocked(int windowId,
@NonNull Region outRegion) {
+ windowId = resolveParentWindowIdLocked(windowId);
final DisplayWindowsObserver observer = getDisplayWindowObserverByWindowIdLocked(windowId);
if (observer != null) {
return observer.computePartialInteractiveRegionForWindowLocked(windowId, outRegion);
@@ -1436,6 +1437,7 @@
*/
@Nullable
public WindowInfo findWindowInfoByIdLocked(int windowId) {
+ windowId = resolveParentWindowIdLocked(windowId);
final DisplayWindowsObserver observer = getDisplayWindowObserverByWindowIdLocked(windowId);
if (observer != null) {
return observer.findWindowInfoByIdLocked(windowId);
diff --git a/services/api/current.txt b/services/api/current.txt
index 8c90165..9bbb3ef 100644
--- a/services/api/current.txt
+++ b/services/api/current.txt
@@ -3,9 +3,9 @@
public interface RuntimePermissionsPersistence {
method @NonNull public static com.android.permission.persistence.RuntimePermissionsPersistence createInstance();
- method public void deleteAsUser(@NonNull android.os.UserHandle);
- method @Nullable public com.android.permission.persistence.RuntimePermissionsState readAsUser(@NonNull android.os.UserHandle);
- method public void writeAsUser(@NonNull com.android.permission.persistence.RuntimePermissionsState, @NonNull android.os.UserHandle);
+ method public void deleteForUser(@NonNull android.os.UserHandle);
+ method @Nullable public com.android.permission.persistence.RuntimePermissionsState readForUser(@NonNull android.os.UserHandle);
+ method public void writeForUser(@NonNull com.android.permission.persistence.RuntimePermissionsState, @NonNull android.os.UserHandle);
}
public final class RuntimePermissionsState {
@@ -17,7 +17,7 @@
field public static final int NO_VERSION = -1; // 0xffffffff
}
- public static class RuntimePermissionsState.PermissionState {
+ public static final class RuntimePermissionsState.PermissionState {
ctor public RuntimePermissionsState.PermissionState(@NonNull String, boolean, int);
method public int getFlags();
method @NonNull public String getName();
@@ -30,9 +30,9 @@
public interface RolesPersistence {
method @NonNull public static com.android.role.persistence.RolesPersistence createInstance();
- method public void deleteAsUser(@NonNull android.os.UserHandle);
- method @Nullable public com.android.role.persistence.RolesState readAsUser(@NonNull android.os.UserHandle);
- method public void writeAsUser(@NonNull com.android.role.persistence.RolesState, @NonNull android.os.UserHandle);
+ method public void deleteForUser(@NonNull android.os.UserHandle);
+ method @Nullable public com.android.role.persistence.RolesState readForUser(@NonNull android.os.UserHandle);
+ method public void writeForUser(@NonNull com.android.role.persistence.RolesState, @NonNull android.os.UserHandle);
}
public final class RolesState {
diff --git a/services/autofill/java/com/android/server/autofill/InlineSuggestionSession.java b/services/autofill/java/com/android/server/autofill/InlineSuggestionSession.java
index 7fe086d..5de8171 100644
--- a/services/autofill/java/com/android/server/autofill/InlineSuggestionSession.java
+++ b/services/autofill/java/com/android/server/autofill/InlineSuggestionSession.java
@@ -23,6 +23,7 @@
import android.annotation.Nullable;
import android.content.ComponentName;
import android.os.Bundle;
+import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.util.Slog;
@@ -38,11 +39,8 @@
import java.util.Collections;
import java.util.Optional;
-import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
/**
* Maintains an autofill inline suggestion session that communicates with the IME.
@@ -64,12 +62,12 @@
* side flow.
*
* <p>
- * This class is thread safe.
+ * This class should hold the same lock as {@link Session} as they call into each other.
*/
final class InlineSuggestionSession {
private static final String TAG = "AfInlineSuggestionSession";
- private static final int INLINE_REQUEST_TIMEOUT_MS = 1000;
+ private static final int INLINE_REQUEST_TIMEOUT_MS = 200;
@NonNull
private final InputMethodManagerInternal mInputMethodManagerInternal;
@@ -80,6 +78,8 @@
private final Object mLock;
@NonNull
private final ImeStatusListener mImeStatusListener;
+ @NonNull
+ private final Handler mHandler;
/**
* To avoid the race condition, one should not access {@code mPendingImeResponse} without
@@ -105,11 +105,12 @@
private boolean mImeInputViewStarted = false;
InlineSuggestionSession(InputMethodManagerInternal inputMethodManagerInternal,
- int userId, ComponentName componentName) {
+ int userId, ComponentName componentName, Handler handler, Object lock) {
mInputMethodManagerInternal = inputMethodManagerInternal;
mUserId = userId;
mComponentName = componentName;
- mLock = new Object();
+ mHandler = handler;
+ mLock = lock;
mImeStatusListener = new ImeStatusListener() {
@Override
public void onInputMethodStartInputView(AutofillId imeFieldId) {
@@ -137,7 +138,8 @@
};
}
- public void onCreateInlineSuggestionsRequest(@NonNull AutofillId autofillId) {
+ public void onCreateInlineSuggestionsRequest(@NonNull AutofillId autofillId,
+ @NonNull Consumer<InlineSuggestionsRequest> requestConsumer) {
if (sDebug) Log.d(TAG, "onCreateInlineSuggestionsRequest called for " + autofillId);
synchronized (mLock) {
@@ -154,26 +156,16 @@
mUserId,
new InlineSuggestionsRequestInfo(mComponentName, autofillId, new Bundle()),
new InlineSuggestionsRequestCallbackImpl(mPendingImeResponse,
- mImeStatusListener));
+ mImeStatusListener, requestConsumer, mHandler, mLock));
}
}
- public Optional<InlineSuggestionsRequest> waitAndGetInlineSuggestionsRequest() {
+ public Optional<InlineSuggestionsRequest> getInlineSuggestionsRequest() {
final CompletableFuture<ImeResponse> pendingImeResponse = getPendingImeResponse();
- if (pendingImeResponse == null) {
+ if (pendingImeResponse == null || !pendingImeResponse.isDone()) {
return Optional.empty();
}
- try {
- return Optional.ofNullable(pendingImeResponse.get(INLINE_REQUEST_TIMEOUT_MS,
- TimeUnit.MILLISECONDS)).map(ImeResponse::getRequest);
- } catch (TimeoutException e) {
- Log.w(TAG, "Exception getting inline suggestions request in time: " + e);
- } catch (CancellationException e) {
- Log.w(TAG, "Inline suggestions request cancelled");
- } catch (InterruptedException | ExecutionException e) {
- throw new RuntimeException(e);
- }
- return Optional.empty();
+ return Optional.ofNullable(pendingImeResponse.getNow(null)).map(ImeResponse::getRequest);
}
public boolean hideInlineSuggestionsUi(@NonNull AutofillId autofillId) {
@@ -200,8 +192,7 @@
if (sDebug) Log.d(TAG, "onInlineSuggestionsResponseLocked without IMS request");
return false;
}
- // There is no need to wait on the CompletableFuture since it should have been completed
- // when {@link #waitAndGetInlineSuggestionsRequest()} was called.
+ // There is no need to wait on the CompletableFuture since it should have been completed.
ImeResponse imeResponse = completedImsResponse.getNow(null);
if (imeResponse == null) {
if (sDebug) Log.d(TAG, "onInlineSuggestionsResponseLocked with pending IMS response");
@@ -249,20 +240,48 @@
private static final class InlineSuggestionsRequestCallbackImpl
extends IInlineSuggestionsRequestCallback.Stub {
+ private final Object mLock;
+ @GuardedBy("mLock")
private final CompletableFuture<ImeResponse> mResponse;
+ @GuardedBy("mLock")
+ private final Consumer<InlineSuggestionsRequest> mRequestConsumer;
private final ImeStatusListener mImeStatusListener;
+ private final Handler mHandler;
+ private final Runnable mTimeoutCallback;
private InlineSuggestionsRequestCallbackImpl(CompletableFuture<ImeResponse> response,
- ImeStatusListener imeStatusListener) {
+ ImeStatusListener imeStatusListener,
+ Consumer<InlineSuggestionsRequest> requestConsumer,
+ Handler handler, Object lock) {
mResponse = response;
mImeStatusListener = imeStatusListener;
+ mRequestConsumer = requestConsumer;
+ mLock = lock;
+
+ mHandler = handler;
+ mTimeoutCallback = () -> {
+ Log.w(TAG, "Timed out waiting for IME callback InlineSuggestionsRequest.");
+ completeIfNot(null);
+ };
+ mHandler.postDelayed(mTimeoutCallback, INLINE_REQUEST_TIMEOUT_MS);
+ }
+
+ private void completeIfNot(@Nullable ImeResponse response) {
+ synchronized (mLock) {
+ if (mResponse.isDone()) {
+ return;
+ }
+ mResponse.complete(response);
+ mRequestConsumer.accept(response == null ? null : response.mRequest);
+ mHandler.removeCallbacks(mTimeoutCallback);
+ }
}
@BinderThread
@Override
public void onInlineSuggestionsUnsupported() throws RemoteException {
if (sDebug) Log.d(TAG, "onInlineSuggestionsUnsupported() called.");
- mResponse.complete(null);
+ completeIfNot(null);
}
@BinderThread
@@ -281,9 +300,9 @@
mImeStatusListener.onInputMethodFinishInputView(imeFieldId);
}
if (request != null && callback != null) {
- mResponse.complete(new ImeResponse(request, callback));
+ completeIfNot(new ImeResponse(request, callback));
} else {
- mResponse.complete(null);
+ completeIfNot(null);
}
}
diff --git a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
index 2420e69..53afa6e 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
@@ -37,7 +37,7 @@
import android.os.RemoteException;
import android.os.SystemClock;
import android.service.autofill.Dataset;
-import android.service.autofill.InlinePresentation;
+import android.service.autofill.InlineAction;
import android.service.autofill.augmented.AugmentedAutofillService;
import android.service.autofill.augmented.IAugmentedAutofillService;
import android.service.autofill.augmented.IFillCallback;
@@ -57,6 +57,7 @@
import com.android.internal.os.IResultReceiver;
import com.android.server.autofill.ui.InlineSuggestionFactory;
+import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
@@ -167,7 +168,7 @@
new IFillCallback.Stub() {
@Override
public void onSuccess(@Nullable List<Dataset> inlineSuggestionsData,
- @Nullable List<InlinePresentation> inlineActions) {
+ @Nullable List<InlineAction> inlineActions) {
mCallbacks.resetLastResponse();
maybeRequestShowInlineSuggestions(sessionId,
inlineSuggestionsRequest, inlineSuggestionsData,
@@ -237,7 +238,7 @@
private void maybeRequestShowInlineSuggestions(int sessionId,
@Nullable InlineSuggestionsRequest request,
@Nullable List<Dataset> inlineSuggestionsData,
- @Nullable List<InlinePresentation> inlineActions, @NonNull AutofillId focusedId,
+ @Nullable List<InlineAction> inlineActions, @NonNull AutofillId focusedId,
@Nullable Function<InlineSuggestionsResponse, Boolean> inlineSuggestionsCallback,
@NonNull IAutoFillManagerClient client, @NonNull Runnable onErrorCallback,
@Nullable RemoteInlineSuggestionRenderService remoteRenderService) {
@@ -250,13 +251,17 @@
final InlineSuggestionsResponse inlineSuggestionsResponse =
InlineSuggestionFactory.createAugmentedInlineSuggestionsResponse(
- request, inlineSuggestionsData, inlineActions, focusedId, mContext,
+ request, inlineSuggestionsData, inlineActions, focusedId,
dataset -> {
mCallbacks.logAugmentedAutofillSelected(sessionId,
dataset.getId());
try {
- client.autofill(sessionId, dataset.getFieldIds(),
- dataset.getFieldValues());
+ final ArrayList<AutofillId> fieldIds = dataset.getFieldIds();
+ final int size = fieldIds.size();
+ final boolean hideHighlight = size == 1
+ && fieldIds.get(0).equals(focusedId);
+ client.autofill(sessionId, fieldIds, dataset.getFieldValues(),
+ hideHighlight);
} catch (RemoteException e) {
Slog.w(TAG, "Encounter exception autofilling the values");
}
diff --git a/services/autofill/java/com/android/server/autofill/Session.java b/services/autofill/java/com/android/server/autofill/Session.java
index f14a7e9..de31118 100644
--- a/services/autofill/java/com/android/server/autofill/Session.java
+++ b/services/autofill/java/com/android/server/autofill/Session.java
@@ -18,6 +18,7 @@
import static android.service.autofill.AutofillFieldClassificationService.EXTRA_SCORES;
import static android.service.autofill.FillRequest.FLAG_MANUAL_REQUEST;
+import static android.service.autofill.FillRequest.FLAG_PASSWORD_INPUT_TYPE;
import static android.service.autofill.FillRequest.INVALID_REQUEST_ID;
import static android.view.autofill.AutofillManager.ACTION_RESPONSE_EXPIRED;
import static android.view.autofill.AutofillManager.ACTION_START_SESSION;
@@ -113,7 +114,9 @@
import java.util.List;
import java.util.Objects;
import java.util.Optional;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
/**
* A session for a given activity.
@@ -137,7 +140,6 @@
private final Handler mHandler;
private final Object mLock;
private final AutoFillUI mUi;
- private final Context mContext;
private final MetricsLogger mMetricsLogger = new MetricsLogger();
@@ -307,7 +309,47 @@
/**
* Receiver of assist data from the app's {@link Activity}.
*/
- private final IAssistDataReceiver mAssistReceiver = new IAssistDataReceiver.Stub() {
+ private final AssistDataReceiverImpl mAssistReceiver = new AssistDataReceiverImpl();
+
+ private final class AssistDataReceiverImpl extends IAssistDataReceiver.Stub {
+
+ @GuardedBy("mLock")
+ private InlineSuggestionsRequest mPendingInlineSuggestionsRequest;
+ @GuardedBy("mLock")
+ private FillRequest mPendingFillRequest;
+ @GuardedBy("mLock")
+ private CountDownLatch mCountDownLatch;
+
+ @Nullable Consumer<InlineSuggestionsRequest> newAutofillRequestLocked(
+ boolean isInlineRequest) {
+ mCountDownLatch = new CountDownLatch(isInlineRequest ? 2 : 1);
+ mPendingFillRequest = null;
+ mPendingInlineSuggestionsRequest = null;
+ return isInlineRequest ? (inlineSuggestionsRequest) -> {
+ synchronized (mLock) {
+ mPendingInlineSuggestionsRequest = inlineSuggestionsRequest;
+ mCountDownLatch.countDown();
+ maybeRequestFillLocked();
+ }
+ } : null;
+ }
+
+ void maybeRequestFillLocked() {
+ if (mCountDownLatch == null || mCountDownLatch.getCount() > 0
+ || mPendingFillRequest == null) {
+ return;
+ }
+ if (mPendingInlineSuggestionsRequest != null) {
+ mPendingFillRequest = new FillRequest(mPendingFillRequest.getId(),
+ mPendingFillRequest.getFillContexts(), mPendingFillRequest.getClientState(),
+ mPendingFillRequest.getFlags(), mPendingInlineSuggestionsRequest);
+ }
+ mRemoteFillService.onFillRequest(mPendingFillRequest);
+ mPendingInlineSuggestionsRequest = null;
+ mPendingFillRequest = null;
+ mCountDownLatch = null;
+ }
+
@Override
public void onHandleAssistData(Bundle resultData) throws RemoteException {
if (mRemoteFillService == null) {
@@ -402,17 +444,17 @@
final ArrayList<FillContext> contexts =
mergePreviousSessionLocked(/* forSave= */ false);
-
- final Optional<InlineSuggestionsRequest> inlineSuggestionsRequest =
- mInlineSuggestionSession.waitAndGetInlineSuggestionsRequest();
request = new FillRequest(requestId, contexts, mClientState, flags,
- inlineSuggestionsRequest.orElse(null));
+ /*inlineSuggestionsRequest=*/null);
+
+ mPendingFillRequest = request;
+ mCountDownLatch.countDown();
+ maybeRequestFillLocked();
}
if (mActivityToken != null) {
mService.sendActivityAssistDataToContentCapture(mActivityToken, resultData);
}
- mRemoteFillService.onFillRequest(request);
}
@Override
@@ -605,9 +647,15 @@
private void maybeRequestInlineSuggestionsRequestThenFillLocked(@NonNull ViewState viewState,
int newState, int flags) {
if (isInlineSuggestionsEnabledLocked()) {
- mInlineSuggestionSession.onCreateInlineSuggestionsRequest(mCurrentViewId);
+ Consumer<InlineSuggestionsRequest> inlineSuggestionsRequestConsumer =
+ mAssistReceiver.newAutofillRequestLocked(/*isInlineRequest=*/ true);
+ if (inlineSuggestionsRequestConsumer != null) {
+ mInlineSuggestionSession.onCreateInlineSuggestionsRequest(mCurrentViewId,
+ inlineSuggestionsRequestConsumer);
+ }
+ } else {
+ mAssistReceiver.newAutofillRequestLocked(/*isInlineRequest=*/ false);
}
-
requestNewFillResponseLocked(viewState, newState, flags);
}
@@ -625,7 +673,7 @@
+ ", flags=" + flags + ")");
}
mForAugmentedAutofillOnly = true;
- triggerAugmentedAutofillLocked();
+ triggerAugmentedAutofillLocked(flags);
return;
}
@@ -695,7 +743,6 @@
mLock = lock;
mUi = ui;
mHandler = handler;
- mContext = context;
mRemoteFillService = serviceComponentName == null ? null
: new RemoteFillService(context, serviceComponentName, userId, this,
bindInstantServiceAllowed);
@@ -709,7 +756,7 @@
setClientLocked(client);
mInlineSuggestionSession = new InlineSuggestionSession(inputMethodManagerInternal, userId,
- componentName);
+ componentName, handler, mLock);
mMetricsLogger.write(newLogMaker(MetricsEvent.AUTOFILL_SESSION_STARTED)
.addTaggedData(MetricsEvent.FIELD_AUTOFILL_FLAGS, flags));
@@ -836,7 +883,7 @@
}
// Although "standard" autofill is disabled, it might still trigger augmented autofill
- if (triggerAugmentedAutofillLocked() != null) {
+ if (triggerAugmentedAutofillLocked(requestFlags) != null) {
mForAugmentedAutofillOnly = true;
if (sDebug) {
Slog.d(TAG, "Service disabled autofill for " + mComponentName
@@ -2467,7 +2514,7 @@
// triggered augmented autofill
if (!isSameViewEntered) {
if (sDebug) Slog.d(TAG, "trigger augmented autofill.");
- triggerAugmentedAutofillLocked();
+ triggerAugmentedAutofillLocked(flags);
} else {
if (sDebug) Slog.d(TAG, "skip augmented autofill for same view.");
}
@@ -2664,7 +2711,7 @@
private boolean requestShowInlineSuggestionsLocked(@NonNull FillResponse response,
@Nullable String filterText) {
final Optional<InlineSuggestionsRequest> inlineSuggestionsRequest =
- mInlineSuggestionSession.waitAndGetInlineSuggestionsRequest();
+ mInlineSuggestionSession.getInlineSuggestionsRequest();
if (!inlineSuggestionsRequest.isPresent()) {
Log.w(TAG, "InlineSuggestionsRequest unavailable");
return false;
@@ -2680,10 +2727,10 @@
InlineSuggestionsResponse inlineSuggestionsResponse =
InlineSuggestionFactory.createInlineSuggestionsResponse(
inlineSuggestionsRequest.get(),
- response, filterText, response.getInlineActions(), mCurrentViewId, mContext,
+ response, filterText, response.getInlineActions(), mCurrentViewId,
this, () -> {
synchronized (mLock) {
- requestHideFillUi(mCurrentViewId);
+ mInlineSuggestionSession.hideInlineSuggestionsUi(mCurrentViewId);
}
}, remoteRenderService);
if (inlineSuggestionsResponse == null) {
@@ -2865,8 +2912,8 @@
// The default autofill service cannot fullfill the request, let's check if the augmented
// autofill service can.
- mAugmentedAutofillDestroyer = triggerAugmentedAutofillLocked();
- if (mAugmentedAutofillDestroyer == null) {
+ mAugmentedAutofillDestroyer = triggerAugmentedAutofillLocked(flags);
+ if (mAugmentedAutofillDestroyer == null && ((flags & FLAG_PASSWORD_INPUT_TYPE) == 0)) {
if (sVerbose) {
Slog.v(TAG, "canceling session " + id + " when service returned null and it cannot "
+ "be augmented. AutofillableIds: " + autofillableIds);
@@ -2876,8 +2923,14 @@
removeSelf();
} else {
if (sVerbose) {
- Slog.v(TAG, "keeping session " + id + " when service returned null but "
- + "it can be augmented. AutofillableIds: " + autofillableIds);
+ if ((flags & FLAG_PASSWORD_INPUT_TYPE) != 0) {
+ Slog.v(TAG, "keeping session " + id + " when service returned null and "
+ + "augmented service is disabled for password fields. "
+ + "AutofillableIds: " + autofillableIds);
+ } else {
+ Slog.v(TAG, "keeping session " + id + " when service returned null but "
+ + "it can be augmented. AutofillableIds: " + autofillableIds);
+ }
}
mAugmentedAutofillableIds = autofillableIds;
try {
@@ -2891,12 +2944,20 @@
/**
* Tries to trigger Augmented Autofill when the standard service could not fulfill a request.
*
+ * <p> The request may not have been sent when this method returns as it may be waiting for
+ * the inline suggestion request asynchronously.
+ *
* @return callback to destroy the autofill UI, or {@code null} if not supported.
*/
// TODO(b/123099468): might need to call it in other places, like when the service returns a
// non-null response but without datasets (for example, just SaveInfo)
@GuardedBy("mLock")
- private Runnable triggerAugmentedAutofillLocked() {
+ private Runnable triggerAugmentedAutofillLocked(int flags) {
+ // (TODO: b/141703197) Fix later by passing info to service.
+ if ((flags & FLAG_PASSWORD_INPUT_TYPE) != 0) {
+ return null;
+ }
+
// Check if Smart Suggestions is supported...
final @SmartSuggestionMode int supportedModes = mService
.getSupportedSmartSuggestionModesLocked();
@@ -2968,6 +3029,21 @@
final AutofillId focusedId = AutofillId.withoutSession(mCurrentViewId);
+ final Consumer<InlineSuggestionsRequest> requestAugmentedAutofill =
+ (inlineSuggestionsRequest) -> {
+ remoteService.onRequestAutofillLocked(id, mClient, taskId, mComponentName,
+ focusedId,
+ currentValue, inlineSuggestionsRequest,
+ /*inlineSuggestionsCallback=*/
+ response -> mInlineSuggestionSession.onInlineSuggestionsResponse(
+ mCurrentViewId, response),
+ /*onErrorCallback=*/ () -> {
+ synchronized (mLock) {
+ cancelAugmentedAutofillLocked();
+ }
+ }, mService.getRemoteInlineSuggestionRenderServiceLocked());
+ };
+
// There are 3 cases when augmented autofill should ask IME for a new request:
// 1. standard autofill provider is None
// 2. standard autofill provider doesn't support inline (and returns null response)
@@ -2975,21 +3051,12 @@
// doesn't want autofill
if (mForAugmentedAutofillOnly || !isInlineSuggestionsEnabledLocked()) {
if (sDebug) Slog.d(TAG, "Create inline request for augmented autofill");
- mInlineSuggestionSession.onCreateInlineSuggestionsRequest(mCurrentViewId);
+ mInlineSuggestionSession.onCreateInlineSuggestionsRequest(mCurrentViewId,
+ /*requestConsumer=*/ requestAugmentedAutofill);
+ } else {
+ requestAugmentedAutofill.accept(
+ mInlineSuggestionSession.getInlineSuggestionsRequest().orElse(null));
}
-
- Optional<InlineSuggestionsRequest> inlineSuggestionsRequest =
- mInlineSuggestionSession.waitAndGetInlineSuggestionsRequest();
- remoteService.onRequestAutofillLocked(id, mClient, taskId, mComponentName, focusedId,
- currentValue, inlineSuggestionsRequest.orElse(null),
- response -> mInlineSuggestionSession.onInlineSuggestionsResponse(
- mCurrentViewId, response),
- () -> {
- synchronized (mLock) {
- cancelAugmentedAutofillLocked();
- }
- }, mService.getRemoteInlineSuggestionRenderServiceLocked());
-
if (mAugmentedAutofillDestroyer == null) {
mAugmentedAutofillDestroyer = () -> remoteService.onDestroyAutofillWindowsRequest();
}
@@ -3372,6 +3439,8 @@
final List<AutofillId> ids = new ArrayList<>(entryCount);
final List<AutofillValue> values = new ArrayList<>(entryCount);
boolean waitingDatasetAuth = false;
+ boolean hideHighlight = (entryCount == 1
+ && dataset.getFieldIds().get(0).equals(mCurrentViewId));
for (int i = 0; i < entryCount; i++) {
if (dataset.getFieldValues().get(i) == null) {
continue;
@@ -3395,7 +3464,7 @@
}
if (sDebug) Slog.d(TAG, "autoFillApp(): the buck is on the app: " + dataset);
- mClient.autofill(id, ids, values);
+ mClient.autofill(id, ids, values, hideHighlight);
if (dataset.getId() != null) {
if (mSelectedDatasetIds == null) {
mSelectedDatasetIds = new ArrayList<>();
diff --git a/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java b/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java
index 4cf4463..0ca9dd9 100644
--- a/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java
+++ b/services/autofill/java/com/android/server/autofill/ui/InlineSuggestionFactory.java
@@ -21,12 +21,13 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.content.Context;
+import android.content.IntentSender;
import android.os.IBinder;
import android.os.RemoteException;
import android.service.autofill.Dataset;
import android.service.autofill.FillResponse;
import android.service.autofill.IInlineSuggestionUiCallback;
+import android.service.autofill.InlineAction;
import android.service.autofill.InlinePresentation;
import android.text.TextUtils;
import android.util.Slog;
@@ -39,7 +40,6 @@
import android.view.inputmethod.InlineSuggestionInfo;
import android.view.inputmethod.InlineSuggestionsRequest;
import android.view.inputmethod.InlineSuggestionsResponse;
-import android.widget.Toast;
import com.android.internal.view.inline.IInlineContentCallback;
import com.android.internal.view.inline.IInlineContentProvider;
@@ -73,8 +73,8 @@
@Nullable
public static InlineSuggestionsResponse createInlineSuggestionsResponse(
@NonNull InlineSuggestionsRequest request, @NonNull FillResponse response,
- @Nullable String filterText, @Nullable List<InlinePresentation> inlineActions,
- @NonNull AutofillId autofillId, @NonNull Context context,
+ @Nullable String filterText, @Nullable List<InlineAction> inlineActions,
+ @NonNull AutofillId autofillId,
@NonNull AutoFillUI.AutoFillUiCallback client, @NonNull Runnable onErrorCallback,
@Nullable RemoteInlineSuggestionRenderService remoteRenderService) {
if (sDebug) Slog.d(TAG, "createInlineSuggestionsResponse called");
@@ -97,7 +97,7 @@
response.getAuthentication() == null ? null : response.getInlinePresentation();
return createInlineSuggestionsResponseInternal(/* isAugmented= */ false, request,
response.getDatasets(), filterText, inlineAuthentication, inlineActions, autofillId,
- context, onErrorCallback, onClickFactory, remoteRenderService);
+ onErrorCallback, onClickFactory, remoteRenderService);
}
/**
@@ -107,15 +107,14 @@
@Nullable
public static InlineSuggestionsResponse createAugmentedInlineSuggestionsResponse(
@NonNull InlineSuggestionsRequest request, @NonNull List<Dataset> datasets,
- @Nullable List<InlinePresentation> inlineActions,
- @NonNull AutofillId autofillId, @NonNull Context context,
+ @Nullable List<InlineAction> inlineActions, @NonNull AutofillId autofillId,
@NonNull InlineSuggestionUiCallback inlineSuggestionUiCallback,
@NonNull Runnable onErrorCallback,
@Nullable RemoteInlineSuggestionRenderService remoteRenderService) {
if (sDebug) Slog.d(TAG, "createAugmentedInlineSuggestionsResponse called");
return createInlineSuggestionsResponseInternal(/* isAugmented= */ true, request,
datasets, /* filterText= */ null, /* inlineAuthentication= */ null,
- inlineActions, autofillId, context, onErrorCallback,
+ inlineActions, autofillId, onErrorCallback,
(dataset, datasetIndex) ->
inlineSuggestionUiCallback.autofill(dataset), remoteRenderService);
}
@@ -125,9 +124,8 @@
boolean isAugmented, @NonNull InlineSuggestionsRequest request,
@Nullable List<Dataset> datasets, @Nullable String filterText,
@Nullable InlinePresentation inlineAuthentication,
- @Nullable List<InlinePresentation> inlineActions, @NonNull AutofillId autofillId,
- @NonNull Context context, @NonNull Runnable onErrorCallback,
- @NonNull BiConsumer<Dataset, Integer> onClickFactory,
+ @Nullable List<InlineAction> inlineActions, @NonNull AutofillId autofillId,
+ @NonNull Runnable onErrorCallback, @NonNull BiConsumer<Dataset, Integer> onClickFactory,
@Nullable RemoteInlineSuggestionRenderService remoteRenderService) {
final ArrayList<InlineSuggestion> inlineSuggestions = new ArrayList<>();
@@ -169,14 +167,14 @@
inlineSuggestions.add(inlineSuggestion);
}
- // We should only add inline actions if there is at least one suggestion.
- if (!inlineSuggestions.isEmpty() && inlineActions != null) {
- for (InlinePresentation inlinePresentation : inlineActions) {
- final InlineSuggestion inlineAction = createInlineAction(isAugmented, context,
- mergedInlinePresentation(request, 0, inlinePresentation),
+ if (inlineActions != null) {
+ for (InlineAction inlineAction : inlineActions) {
+ final InlineSuggestion inlineActionSuggestion = createInlineAction(isAugmented,
+ mergedInlinePresentation(request, 0, inlineAction.getInlinePresentation()),
+ inlineAction.getAction(),
remoteRenderService, onErrorCallback, request.getHostInputToken(),
request.getHostDisplayId());
- inlineSuggestions.add(inlineAction);
+ inlineSuggestions.add(inlineActionSuggestion);
}
}
return new InlineSuggestionsResponse(inlineSuggestions);
@@ -215,22 +213,30 @@
private static InlineSuggestion createInlineAction(boolean isAugmented,
- @NonNull Context context,
- @NonNull InlinePresentation inlinePresentation,
+ @NonNull InlinePresentation presentation,
+ @NonNull IntentSender action,
@Nullable RemoteInlineSuggestionRenderService remoteRenderService,
@NonNull Runnable onErrorCallback, @Nullable IBinder hostInputToken,
int displayId) {
final InlineSuggestionInfo inlineSuggestionInfo = new InlineSuggestionInfo(
- inlinePresentation.getInlinePresentationSpec(),
+ presentation.getInlinePresentationSpec(),
isAugmented ? InlineSuggestionInfo.SOURCE_PLATFORM
: InlineSuggestionInfo.SOURCE_AUTOFILL,
- inlinePresentation.getAutofillHints(),
- InlineSuggestionInfo.TYPE_ACTION, inlinePresentation.isPinned());
+ presentation.getAutofillHints(), InlineSuggestionInfo.TYPE_ACTION,
+ presentation.isPinned());
final Runnable onClickAction = () -> {
- Toast.makeText(context, "icon clicked", Toast.LENGTH_SHORT).show();
+ try {
+ // TODO(b/150499490): route the intent to the client app to have it fired there,
+ // so that it will appear as a part of the same task as the client app (similar
+ // to the authentication flow).
+ action.sendIntent(null, 0, null, null, null);
+ } catch (IntentSender.SendIntentException e) {
+ onErrorCallback.run();
+ Slog.w(TAG, "Error sending inline action intent");
+ }
};
return new InlineSuggestion(inlineSuggestionInfo,
- createInlineContentProvider(inlinePresentation, onClickAction, onErrorCallback,
+ createInlineContentProvider(presentation, onClickAction, onErrorCallback,
remoteRenderService, hostInputToken, displayId));
}
@@ -323,8 +329,14 @@
@NonNull Runnable onErrorCallback) {
return new IInlineSuggestionUiCallback.Stub() {
@Override
- public void onAutofill() throws RemoteException {
+ public void onClick() throws RemoteException {
onAutofillCallback.run();
+ callback.onClick();
+ }
+
+ @Override
+ public void onLongClick() throws RemoteException {
+ callback.onLongClick();
}
@Override
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 84ce34b..9e19ad2 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -94,12 +94,13 @@
"services-stubs",
"services.net",
"android.hardware.light-V2.0-java",
+ "android.hardware.power-java",
"android.hardware.power-V1.0-java",
"android.hardware.tv.cec-V1.0-java",
"android.hardware.vibrator-java",
+ "android.net.ipsec.ike.stubs.module_libs_api",
"app-compat-annotations",
- "framework-tethering-stubs",
- "ike-stubs",
+ "framework-tethering-stubs-module_libs_api",
],
required: [
@@ -127,7 +128,6 @@
"android.hidl.manager-V1.2-java",
"dnsresolver_aidl_interface-V2-java",
"netd_event_listener_interface-java",
- "ike-stubs",
"overlayable_policy_aidl-java",
],
diff --git a/services/core/java/android/content/pm/PackageManagerInternal.java b/services/core/java/android/content/pm/PackageManagerInternal.java
index dadcd4e..9fddafb 100644
--- a/services/core/java/android/content/pm/PackageManagerInternal.java
+++ b/services/core/java/android/content/pm/PackageManagerInternal.java
@@ -991,4 +991,9 @@
* @param enabled true if visibility blocks should be logged
*/
public abstract void setVisibilityLogging(String packageName, boolean enabled);
+
+ /**
+ * Returns if a package name is a valid system package.
+ */
+ public abstract boolean isSystemPackage(@NonNull String packageName);
}
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 7840b19..9b04e79 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -1672,7 +1672,7 @@
| Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
| Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
- intent.putExtra("time-zone", zone.getID());
+ intent.putExtra(Intent.EXTRA_TIMEZONE, zone.getID());
getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
}
}
diff --git a/services/core/java/com/android/server/BluetoothManagerService.java b/services/core/java/com/android/server/BluetoothManagerService.java
index a4a42bc..03ca1c6 100644
--- a/services/core/java/com/android/server/BluetoothManagerService.java
+++ b/services/core/java/com/android/server/BluetoothManagerService.java
@@ -85,6 +85,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -272,6 +273,46 @@
}
};
+ public boolean onFactoryReset() {
+ // Wait for stable state if bluetooth is temporary state.
+ int state = getState();
+ if (state == BluetoothAdapter.STATE_BLE_TURNING_ON
+ || state == BluetoothAdapter.STATE_TURNING_ON
+ || state == BluetoothAdapter.STATE_TURNING_OFF) {
+ if (!waitForState(Set.of(BluetoothAdapter.STATE_BLE_ON, BluetoothAdapter.STATE_ON))) {
+ return false;
+ }
+ }
+
+ // Clear registered LE apps to force shut-off Bluetooth
+ clearBleApps();
+ state = getState();
+ try {
+ mBluetoothLock.readLock().lock();
+ if (mBluetooth == null) {
+ return false;
+ }
+ if (state == BluetoothAdapter.STATE_BLE_ON) {
+ addActiveLog(
+ BluetoothProtoEnums.ENABLE_DISABLE_REASON_FACTORY_RESET,
+ mContext.getPackageName(), false);
+ mBluetooth.onBrEdrDown();
+ return true;
+ } else if (state == BluetoothAdapter.STATE_ON) {
+ addActiveLog(
+ BluetoothProtoEnums.ENABLE_DISABLE_REASON_FACTORY_RESET,
+ mContext.getPackageName(), false);
+ mBluetooth.disable();
+ return true;
+ }
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Unable to shutdown Bluetooth", e);
+ } finally {
+ mBluetoothLock.readLock().unlock();
+ }
+ return false;
+ }
+
public void onAirplaneModeChanged() {
synchronized (this) {
if (isBluetoothPersistedStateOn()) {
@@ -1670,7 +1711,8 @@
// the previous Bluetooth process has exited. The
// waiting period has three components:
// (a) Wait until the local state is STATE_OFF. This
- // is accomplished by "waitForOnOff(false, true)".
+ // is accomplished by
+ // "waitForState(Set.of(BluetoothAdapter.STATE_OFF))".
// (b) Wait until the STATE_OFF state is updated to
// all components.
// (c) Wait until the Bluetooth process exits, and
@@ -1680,7 +1722,7 @@
// message. The delay time is backed off if Bluetooth
// continuously failed to turn on itself.
//
- waitForOnOff(false, true);
+ waitForState(Set.of(BluetoothAdapter.STATE_OFF));
Message restartMsg =
mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
mHandler.sendMessageDelayed(restartMsg, getServiceRestartMs());
@@ -1693,10 +1735,15 @@
}
mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
if (mEnable && mBluetooth != null) {
- waitForOnOff(true, false);
+ waitForState(Set.of(BluetoothAdapter.STATE_ON));
mEnable = false;
handleDisable();
- waitForOnOff(false, false);
+ waitForState(Set.of(BluetoothAdapter.STATE_OFF,
+ BluetoothAdapter.STATE_TURNING_ON,
+ BluetoothAdapter.STATE_TURNING_OFF,
+ BluetoothAdapter.STATE_BLE_TURNING_ON,
+ BluetoothAdapter.STATE_BLE_ON,
+ BluetoothAdapter.STATE_BLE_TURNING_OFF));
} else {
mEnable = false;
handleDisable();
@@ -1819,9 +1866,14 @@
}
if (!mEnable) {
- waitForOnOff(true, false);
+ waitForState(Set.of(BluetoothAdapter.STATE_ON));
handleDisable();
- waitForOnOff(false, false);
+ waitForState(Set.of(BluetoothAdapter.STATE_OFF,
+ BluetoothAdapter.STATE_TURNING_ON,
+ BluetoothAdapter.STATE_TURNING_OFF,
+ BluetoothAdapter.STATE_BLE_TURNING_ON,
+ BluetoothAdapter.STATE_BLE_ON,
+ BluetoothAdapter.STATE_BLE_TURNING_OFF));
}
break;
}
@@ -1853,7 +1905,7 @@
== BluetoothAdapter.STATE_OFF)) {
if (mEnable) {
Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
- waitForOnOff(false, true);
+ waitForState(Set.of(BluetoothAdapter.STATE_OFF));
Message restartMsg =
mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
mHandler.sendMessageDelayed(restartMsg, getServiceRestartMs());
@@ -1982,7 +2034,7 @@
mState = BluetoothAdapter.STATE_TURNING_ON;
}
- waitForOnOff(true, false);
+ waitForState(Set.of(BluetoothAdapter.STATE_ON));
if (mState == BluetoothAdapter.STATE_TURNING_ON) {
bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
@@ -1997,7 +2049,8 @@
bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
BluetoothAdapter.STATE_TURNING_OFF);
- boolean didDisableTimeout = !waitForOnOff(false, true);
+ boolean didDisableTimeout =
+ !waitForState(Set.of(BluetoothAdapter.STATE_OFF));
bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
BluetoothAdapter.STATE_OFF);
@@ -2243,12 +2296,7 @@
}
}
- /**
- * if on is true, wait for state become ON
- * if off is true, wait for state become OFF
- * if both on and off are false, wait for state not ON
- */
- private boolean waitForOnOff(boolean on, boolean off) {
+ private boolean waitForState(Set<Integer> states) {
int i = 0;
while (i < 10) {
try {
@@ -2256,18 +2304,8 @@
if (mBluetooth == null) {
break;
}
- if (on) {
- if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) {
- return true;
- }
- } else if (off) {
- if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) {
- return true;
- }
- } else {
- if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) {
- return true;
- }
+ if (states.contains(mBluetooth.getState())) {
+ return true;
}
} catch (RemoteException e) {
Slog.e(TAG, "getState()", e);
@@ -2275,14 +2313,10 @@
} finally {
mBluetoothLock.readLock().unlock();
}
- if (on || off) {
- SystemClock.sleep(300);
- } else {
- SystemClock.sleep(50);
- }
+ SystemClock.sleep(300);
i++;
}
- Slog.e(TAG, "waitForOnOff time out");
+ Slog.e(TAG, "waitForState " + states + " time out");
return false;
}
@@ -2343,7 +2377,7 @@
mContext.getPackageName(), false);
handleDisable();
- waitForOnOff(false, true);
+ waitForState(Set.of(BluetoothAdapter.STATE_OFF));
sendBluetoothServiceDownCallback();
@@ -2533,6 +2567,8 @@
return "USER_SWITCH";
case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING:
return "RESTORE_USER_SETTING";
+ case BluetoothProtoEnums.ENABLE_DISABLE_REASON_FACTORY_RESET:
+ return "FACTORY_RESET";
case BluetoothProtoEnums.ENABLE_DISABLE_REASON_UNSPECIFIED:
default: return "UNKNOWN[" + reason + "]";
}
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 16dd3ad..3a3358c 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -101,7 +101,6 @@
import android.net.NetworkProvider;
import android.net.NetworkQuotaInfo;
import android.net.NetworkRequest;
-import android.net.NetworkScore;
import android.net.NetworkSpecifier;
import android.net.NetworkStack;
import android.net.NetworkStackClient;
@@ -274,9 +273,6 @@
// connect anyway?" dialog after the user selects a network that doesn't validate.
private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
- // How long to dismiss network notification.
- private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
-
// Default to 30s linger time-out. Modifiable only for testing.
private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
@@ -524,18 +520,13 @@
private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
/**
- * This event can handle dismissing notification by given network id.
- */
- private static final int EVENT_TIMEOUT_NOTIFICATION = 44;
-
- /**
* Used to specify whether a network should be used even if connectivity is partial.
* arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
* false)
* arg2 = whether to remember this choice in the future (1 for true or 0 for false)
* obj = network
*/
- private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
+ private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
/**
* Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
@@ -544,7 +535,7 @@
* arg1 = A bitmask to describe which probes are completed.
* arg2 = A bitmask to describe which probes are successful.
*/
- public static final int EVENT_PROBE_STATUS_CHANGED = 46;
+ public static final int EVENT_PROBE_STATUS_CHANGED = 45;
/**
* Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
@@ -552,7 +543,7 @@
* arg2 = netId
* obj = captive portal data
*/
- private static final int EVENT_CAPPORT_DATA_CHANGED = 47;
+ private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
/**
* Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
@@ -2092,9 +2083,9 @@
}
private void enforceNetworkFactoryPermission() {
- mContext.enforceCallingOrSelfPermission(
+ enforceAnyPermissionOf(
android.Manifest.permission.NETWORK_FACTORY,
- "ConnectivityService");
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
}
private boolean checkSettingsPermission() {
@@ -2731,8 +2722,7 @@
break;
}
case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
- final NetworkScore ns = (NetworkScore) msg.obj;
- updateNetworkScore(nai, ns);
+ updateNetworkScore(nai, msg.arg1);
break;
}
case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
@@ -2879,13 +2869,6 @@
final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
final boolean wasValidated = nai.lastValidated;
final boolean wasDefault = isDefaultNetwork(nai);
- // Only show a connected notification if the network is pending validation
- // after the captive portal app was open, and it has now validated.
- if (nai.captivePortalValidationPending && valid) {
- // User is now logged in, network validated.
- nai.captivePortalValidationPending = false;
- showNetworkNotification(nai, NotificationType.LOGGED_IN);
- }
if (DBG) {
final String logMsg = !TextUtils.isEmpty(redirectUrl)
@@ -3766,12 +3749,6 @@
new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
- // This runs on a random binder thread, but getNetworkAgentInfoForNetwork is thread-safe,
- // and captivePortalValidationPending is volatile.
- final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
- if (nai != null) {
- nai.captivePortalValidationPending = true;
- }
Binder.withCleanCallingIdentity(() ->
mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
}
@@ -3890,14 +3867,6 @@
final String action;
final boolean highPriority;
switch (type) {
- case LOGGED_IN:
- action = Settings.ACTION_WIFI_SETTINGS;
- mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
- mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
- nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
- // High priority because it is a direct result of the user logging in to a portal.
- highPriority = true;
- break;
case NO_INTERNET:
action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
// High priority because it is only displayed for explicitly selected networks.
@@ -3925,7 +3894,7 @@
}
Intent intent = new Intent(action);
- if (type != NotificationType.LOGGED_IN && type != NotificationType.PRIVATE_DNS_BROKEN) {
+ if (type != NotificationType.PRIVATE_DNS_BROKEN) {
intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.android.settings",
@@ -4141,9 +4110,6 @@
case EVENT_DATA_SAVER_CHANGED:
handleRestrictBackgroundChanged(toBool(msg.arg1));
break;
- case EVENT_TIMEOUT_NOTIFICATION:
- mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
- break;
}
}
}
@@ -5819,12 +5785,10 @@
// TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
// satisfies mDefaultRequest.
final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
- final NetworkScore ns = new NetworkScore();
- ns.putIntExtension(NetworkScore.LEGACY_SCORE, currentScore);
final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
- ns, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig), this,
- mNetd, mDnsResolver, mNMS, providerId);
+ currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
+ this, mNetd, mDnsResolver, mNMS, providerId);
// Make sure the network capabilities reflect what the agent info says.
nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
final String extraInfo = networkInfo.getExtraInfo();
@@ -7082,9 +7046,9 @@
}
}
- private void updateNetworkScore(NetworkAgentInfo nai, NetworkScore ns) {
- if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + ns);
- nai.setNetworkScore(ns);
+ private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final int score) {
+ if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
+ nai.setScore(score);
rematchAllNetworksAndRequests();
sendUpdatedScoreToFactories(nai);
}
@@ -7839,12 +7803,15 @@
private void handleNetworkTestedWithExtras(
@NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
final NetworkAgentInfo nai = reportEvent.mNai;
+ final NetworkCapabilities networkCapabilities =
+ new NetworkCapabilities(nai.networkCapabilities);
+ clearNetworkCapabilitiesUids(networkCapabilities);
final ConnectivityReport report =
new ConnectivityReport(
reportEvent.mNai.network,
reportEvent.mTimestampMillis,
nai.linkProperties,
- nai.networkCapabilities,
+ networkCapabilities,
extras);
final List<IConnectivityDiagnosticsCallback> results =
getMatchingPermissionedCallbacks(nai);
@@ -7860,13 +7827,16 @@
private void handleDataStallSuspected(
@NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
@NonNull PersistableBundle extras) {
+ final NetworkCapabilities networkCapabilities =
+ new NetworkCapabilities(nai.networkCapabilities);
+ clearNetworkCapabilitiesUids(networkCapabilities);
final DataStallReport report =
new DataStallReport(
nai.network,
timestampMillis,
detectionMethod,
nai.linkProperties,
- nai.networkCapabilities,
+ networkCapabilities,
extras);
final List<IConnectivityDiagnosticsCallback> results =
getMatchingPermissionedCallbacks(nai);
@@ -7892,6 +7862,12 @@
}
}
+ private void clearNetworkCapabilitiesUids(@NonNull NetworkCapabilities nc) {
+ nc.setUids(null);
+ nc.setAdministratorUids(Collections.EMPTY_LIST);
+ nc.setOwnerUid(Process.INVALID_UID);
+ }
+
private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
@NonNull NetworkAgentInfo nai) {
final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
diff --git a/services/core/java/com/android/server/DynamicSystemService.java b/services/core/java/com/android/server/DynamicSystemService.java
index 318a030..191a9bc 100644
--- a/services/core/java/com/android/server/DynamicSystemService.java
+++ b/services/core/java/com/android/server/DynamicSystemService.java
@@ -22,13 +22,9 @@
import android.gsi.GsiProgress;
import android.gsi.IGsiService;
import android.gsi.IGsiServiceCallback;
-import android.gsi.IGsid;
import android.os.Environment;
-import android.os.IBinder;
-import android.os.IBinder.DeathRecipient;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
-import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.image.IDynamicSystemService;
@@ -42,9 +38,8 @@
* DynamicSystemService implements IDynamicSystemService. It provides permission check before
* passing requests to gsid
*/
-public class DynamicSystemService extends IDynamicSystemService.Stub implements DeathRecipient {
+public class DynamicSystemService extends IDynamicSystemService.Stub {
private static final String TAG = "DynamicSystemService";
- private static final String NO_SERVICE_ERROR = "no gsiservice";
private static final int GSID_ROUGH_TIMEOUT_MS = 8192;
private static final String PATH_DEFAULT = "/data/gsi/";
private Context mContext;
@@ -55,57 +50,12 @@
mContext = context;
}
- private static IGsiService connect(DeathRecipient recipient) throws RemoteException {
- IBinder binder = ServiceManager.getService("gsiservice");
- if (binder == null) {
- return null;
- }
- /**
- * The init will restart gsiservice if it crashed and the proxy object will need to be
- * re-initialized in this case.
- */
- binder.linkToDeath(recipient, 0);
-
- IGsid gsid = IGsid.Stub.asInterface(binder);
- return gsid.getClient();
- }
-
- /** implements DeathRecipient */
- @Override
- public void binderDied() {
- Slog.w(TAG, "gsiservice died; reconnecting");
- synchronized (this) {
- mGsiService = null;
- }
- }
-
private IGsiService getGsiService() throws RemoteException {
checkPermission();
-
- if (!"running".equals(SystemProperties.get("init.svc.gsid"))) {
- SystemProperties.set("ctl.start", "gsid");
+ if (mGsiService != null) {
+ return mGsiService;
}
-
- for (int sleepMs = 64; sleepMs <= (GSID_ROUGH_TIMEOUT_MS << 1); sleepMs <<= 1) {
- synchronized (this) {
- if (mGsiService == null) {
- mGsiService = connect(this);
- }
- if (mGsiService != null) {
- return mGsiService;
- }
- }
-
- try {
- Slog.d(TAG, "GsiService is not ready, wait for " + sleepMs + "ms");
- Thread.sleep(sleepMs);
- } catch (InterruptedException e) {
- Slog.e(TAG, "Interrupted when waiting for GSID");
- return null;
- }
- }
-
- throw new RemoteException(NO_SERVICE_ERROR);
+ return IGsiService.Stub.asInterface(waitForService("gsiservice"));
}
private void checkPermission() {
@@ -133,6 +83,7 @@
@Override
public boolean startInstallation(String dsuSlot) throws RemoteException {
IGsiService service = getGsiService();
+ mGsiService = service;
// priority from high to low: sysprop -> sdcard -> /data
String path = SystemProperties.get("os.aot.path");
if (path.isEmpty()) {
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index acd4039..d814b9c 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -200,7 +200,7 @@
// time
private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
- private static final String FEATURE_ID = "LocationService";
+ private static final String ATTRIBUTION_TAG = "LocationService";
private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
@@ -246,7 +246,7 @@
private int mBatterySaverMode;
private LocationManagerService(Context context) {
- mContext = context.createFeatureContext(FEATURE_ID);
+ mContext = context.createAttributionContext(ATTRIBUTION_TAG);
mHandler = FgThread.getHandler();
mLocalService = new LocalService();
diff --git a/services/core/java/com/android/server/PackageWatchdog.java b/services/core/java/com/android/server/PackageWatchdog.java
index b464422..52a1b5a 100644
--- a/services/core/java/com/android/server/PackageWatchdog.java
+++ b/services/core/java/com/android/server/PackageWatchdog.java
@@ -354,6 +354,10 @@
*/
public void onPackageFailure(List<VersionedPackage> packages,
@FailureReasons int failureReason) {
+ if (packages == null) {
+ Slog.w(TAG, "Could not resolve a list of failing packages");
+ return;
+ }
mLongTaskHandler.post(() -> {
synchronized (mLock) {
if (mAllObservers.isEmpty()) {
diff --git a/services/core/java/com/android/server/RescueParty.java b/services/core/java/com/android/server/RescueParty.java
index 80036bb..808d322 100644
--- a/services/core/java/com/android/server/RescueParty.java
+++ b/services/core/java/com/android/server/RescueParty.java
@@ -99,6 +99,8 @@
private static final String PROP_DISABLE_RESCUE = "persist.sys.disable_rescue";
private static final String PROP_VIRTUAL_DEVICE = "ro.hardware.virtual_device";
+ private static final String DEVICE_CONFIG_DISABLE_FLAG = "disable_rescue_party";
+
private static final int PERSISTENT_MASK = ApplicationInfo.FLAG_PERSISTENT
| ApplicationInfo.FLAG_SYSTEM;
@@ -114,6 +116,14 @@
return false;
}
+ // We're disabled if the DeviceConfig disable flag is set to true.
+ // This is in case that an emergency rollback of the feature is needed.
+ if (DeviceConfig.getBoolean(
+ DeviceConfig.NAMESPACE_CONFIGURATION, DEVICE_CONFIG_DISABLE_FLAG, false)) {
+ Slog.v(TAG, "Disabled because of DeviceConfig flag");
+ return true;
+ }
+
// We're disabled on all engineering devices
if (Build.IS_ENG) {
Slog.v(TAG, "Disabled because of eng build");
diff --git a/services/core/java/com/android/server/SensorNotificationService.java b/services/core/java/com/android/server/SensorNotificationService.java
index 9082dca..db3db0c 100644
--- a/services/core/java/com/android/server/SensorNotificationService.java
+++ b/services/core/java/com/android/server/SensorNotificationService.java
@@ -48,7 +48,7 @@
private static final long MILLIS_2010_1_1 = 1262358000000l;
- private static final String FEATURE_ID = "SensorNotificationService";
+ private static final String ATTRIBUTION_TAG = "SensorNotificationService";
private Context mContext;
private SensorManager mSensorManager;
@@ -59,7 +59,7 @@
private long mLocalGeomagneticFieldUpdateTime = -LOCATION_MIN_TIME;
public SensorNotificationService(Context context) {
- super(context.createFeatureContext(FEATURE_ID));
+ super(context.createAttributionContext(ATTRIBUTION_TAG));
mContext = getContext();
}
diff --git a/services/core/java/com/android/server/ServiceWatcher.java b/services/core/java/com/android/server/ServiceWatcher.java
index b43ae36..cfb79aa 100644
--- a/services/core/java/com/android/server/ServiceWatcher.java
+++ b/services/core/java/com/android/server/ServiceWatcher.java
@@ -100,7 +100,7 @@
@Nullable public final ComponentName component;
@UserIdInt public final int userId;
- private ServiceInfo(ResolveInfo resolveInfo, int currentUserId) {
+ ServiceInfo(ResolveInfo resolveInfo, int currentUserId) {
Preconditions.checkArgument(resolveInfo.serviceInfo.getComponentName() != null);
Bundle metadata = resolveInfo.serviceInfo.metaData;
@@ -316,6 +316,7 @@
}
mContext.unbindService(this);
+ onServiceDisconnected(mServiceInfo.component);
mServiceInfo = ServiceInfo.NONE;
}
@@ -339,15 +340,13 @@
@Override
public final void onServiceConnected(ComponentName component, IBinder binder) {
Preconditions.checkState(Looper.myLooper() == mHandler.getLooper());
+ Preconditions.checkState(mBinder == null);
if (D) {
Log.i(TAG, getLogPrefix() + " connected to " + component.toShortString());
}
mBinder = binder;
-
- // we always run the on bind callback even if we know that the binder is dead already so
- // that there are always balance pairs of bind/unbind callbacks
if (mOnBind != null) {
try {
mOnBind.run(binder);
@@ -357,19 +356,16 @@
Log.e(TAG, getLogPrefix() + " exception running on " + mServiceInfo, e);
}
}
-
- try {
- // setting the binder to null lets us skip queued transactions
- binder.linkToDeath(() -> mBinder = null, 0);
- } catch (RemoteException e) {
- mBinder = null;
- }
}
@Override
public final void onServiceDisconnected(ComponentName component) {
Preconditions.checkState(Looper.myLooper() == mHandler.getLooper());
+ if (mBinder == null) {
+ return;
+ }
+
if (D) {
Log.i(TAG, getLogPrefix() + " disconnected from " + component.toShortString());
}
@@ -391,18 +387,18 @@
onBestServiceChanged(true);
}
- private void onUserSwitched(@UserIdInt int userId) {
+ void onUserSwitched(@UserIdInt int userId) {
mCurrentUserId = userId;
onBestServiceChanged(false);
}
- private void onUserUnlocked(@UserIdInt int userId) {
+ void onUserUnlocked(@UserIdInt int userId) {
if (userId == mCurrentUserId) {
onBestServiceChanged(false);
}
}
- private void onPackageChanged(String packageName) {
+ void onPackageChanged(String packageName) {
// force a rebind if the changed package was the currently connected package
String currentPackageName =
mServiceInfo.component != null ? mServiceInfo.component.getPackageName() : null;
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index b7d050a..2c220d3 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -154,7 +154,6 @@
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;
import com.android.internal.widget.LockPatternUtils;
-import com.android.server.SystemService.TargetUser;
import com.android.server.pm.Installer;
import com.android.server.storage.AppFuseBridge;
import com.android.server.storage.StorageSessionController;
@@ -233,6 +232,8 @@
private static final String FUSE_ENABLED = "fuse_enabled";
private static final boolean DEFAULT_FUSE_ENABLED = true;
+ private final Set<Integer> mFuseMountedUser = new ArraySet<>();
+
public static class Lifecycle extends SystemService {
private StorageManagerService mStorageManagerService;
@@ -1497,6 +1498,9 @@
@GuardedBy("mLock")
private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
+ if (vol.type == VolumeInfo.TYPE_EMULATED && newState != VolumeInfo.STATE_MOUNTED) {
+ mFuseMountedUser.remove(vol.getMountUserId());
+ }
// Remember that we saw this volume so we're ready to accept user
// metadata, or so we can annoy them when a private volume is ejected
if (!TextUtils.isEmpty(vol.fsUuid)) {
@@ -2075,39 +2079,86 @@
mount(vol);
}
+ private void remountAppStorageDirs(Map<Integer, String> pidPkgMap, int userId) {
+ for (Entry<Integer, String> entry : pidPkgMap.entrySet()) {
+ final int pid = entry.getKey();
+ final String packageName = entry.getValue();
+ Slog.i(TAG, "Remounting storage for pid: " + pid);
+ final String[] sharedPackages =
+ mPmInternal.getSharedUserPackagesForPackage(packageName, userId);
+ final int uid = mPmInternal.getPackageUidInternal(packageName, 0, userId);
+ final String[] packages =
+ sharedPackages.length != 0 ? sharedPackages : new String[]{packageName};
+ try {
+ mVold.remountAppStorageDirs(uid, pid, packages);
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+ }
+
private void mount(VolumeInfo vol) {
try {
// TODO(b/135341433): Remove paranoid logging when FUSE is stable
Slog.i(TAG, "Mounting volume " + vol);
mVold.mount(vol.id, vol.mountFlags, vol.mountUserId, new IVoldMountCallback.Stub() {
- @Override
- public boolean onVolumeChecking(FileDescriptor fd, String path,
- String internalPath) {
- vol.path = path;
- vol.internalPath = internalPath;
- ParcelFileDescriptor pfd = new ParcelFileDescriptor(fd);
- try {
- mStorageSessionController.onVolumeMount(pfd, vol);
- return true;
- } catch (ExternalStorageServiceException e) {
- Slog.e(TAG, "Failed to mount volume " + vol, e);
+ @Override
+ public boolean onVolumeChecking(FileDescriptor fd, String path,
+ String internalPath) {
+ vol.path = path;
+ vol.internalPath = internalPath;
+ ParcelFileDescriptor pfd = new ParcelFileDescriptor(fd);
+ try {
+ mStorageSessionController.onVolumeMount(pfd, vol);
+ return true;
+ } catch (ExternalStorageServiceException e) {
+ Slog.e(TAG, "Failed to mount volume " + vol, e);
- int nextResetSeconds = REMOTE_TIMEOUT_SECONDS * 2;
- Slog.i(TAG, "Scheduling reset in " + nextResetSeconds + "s");
- mHandler.removeMessages(H_RESET);
- mHandler.sendMessageDelayed(mHandler.obtainMessage(H_RESET),
- TimeUnit.SECONDS.toMillis(nextResetSeconds));
- return false;
- } finally {
- try {
- pfd.close();
- } catch (Exception e) {
- Slog.e(TAG, "Failed to close FUSE device fd", e);
- }
+ int nextResetSeconds = REMOTE_TIMEOUT_SECONDS * 2;
+ Slog.i(TAG, "Scheduling reset in " + nextResetSeconds + "s");
+ mHandler.removeMessages(H_RESET);
+ mHandler.sendMessageDelayed(mHandler.obtainMessage(H_RESET),
+ TimeUnit.SECONDS.toMillis(nextResetSeconds));
+ return false;
+ } finally {
+ try {
+ pfd.close();
+ } catch (Exception e) {
+ Slog.e(TAG, "Failed to close FUSE device fd", e);
}
}
- });
+ }
+ });
Slog.i(TAG, "Mounted volume " + vol);
+ if (vol.type == VolumeInfo.TYPE_EMULATED) {
+ final int userId = vol.getMountUserId();
+ mFuseMountedUser.add(userId);
+ // Async remount app storage so it won't block the main thread.
+ new Thread(() -> {
+ Map<Integer, String> pidPkgMap = null;
+ // getProcessesWithPendingBindMounts() could fail when a new app process is
+ // starting and it's not planning to mount storage dirs in zygote, but it's
+ // rare, so we retry 5 times and hope we can get the result successfully.
+ for (int i = 0; i < 5; i++) {
+ try {
+ pidPkgMap = LocalServices.getService(ActivityManagerInternal.class)
+ .getProcessesWithPendingBindMounts(vol.getMountUserId());
+ break;
+ } catch (IllegalStateException e) {
+ Slog.i(TAG, "Some processes are starting, retry");
+ // Wait 100ms and retry so hope the pending process is started.
+ SystemClock.sleep(100);
+ }
+ }
+ if (pidPkgMap != null) {
+ remountAppStorageDirs(pidPkgMap, userId);
+ } else {
+ Slog.wtf(TAG, "Not able to getStorageNotOptimizedProcesses() after"
+ + " 5 retries");
+ }
+
+ }).start();
+ }
} catch (Exception e) {
Slog.wtf(TAG, e);
}
@@ -4309,7 +4360,8 @@
pw.println();
pw.println("mObbPathToStateMap:");
pw.increaseIndent();
- final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
+ final Iterator<Entry<String, ObbState>> maps =
+ mObbPathToStateMap.entrySet().iterator();
while (maps.hasNext()) {
final Entry<String, ObbState> e = maps.next();
pw.print(e.getKey());
@@ -4350,45 +4402,41 @@
}
/**
- * Check if fuse is running in target user, if it's running then setup its obb directories.
- * TODO: System server should store a list of active pids that obb is not mounted and use it.
+ * Check if fuse is running in target user, if it's running then setup its storage dirs.
+ * Return true if storage dirs are mounted.
*/
@Override
- public void prepareObbDirs(int userId, Set<String> packageList, String processName) {
- String fuseRunningUsersList = SystemProperties.get("vold.fuse_running_users", "");
- String[] fuseRunningUsers = fuseRunningUsersList.split(",");
- boolean fuseReady = false;
- String targetUserId = String.valueOf(userId);
- for (String user : fuseRunningUsers) {
- if (targetUserId.equals(user)) {
- fuseReady = true;
- }
+ public boolean prepareStorageDirs(int userId, Set<String> packageList,
+ String processName) {
+ if (!mFuseMountedUser.contains(userId)) {
+ Slog.w(TAG, "User " + userId + " is not unlocked yet so skip mounting obb");
+ return false;
}
- if (fuseReady) {
- try {
- final IVold vold = IVold.Stub.asInterface(
- ServiceManager.getServiceOrThrow("vold"));
- for (String pkg : packageList) {
- final String packageObbDir =
- String.format("/storage/emulated/%d/Android/obb/%s/", userId, pkg);
- final String packageDataDir =
- String.format("/storage/emulated/%d/Android/data/%s/",
- userId, pkg);
+ try {
+ final IVold vold = IVold.Stub.asInterface(
+ ServiceManager.getServiceOrThrow("vold"));
+ for (String pkg : packageList) {
+ final String packageObbDir =
+ String.format("/storage/emulated/%d/Android/obb/%s/", userId, pkg);
+ final String packageDataDir =
+ String.format("/storage/emulated/%d/Android/data/%s/",
+ userId, pkg);
- // Create package obb and data dir if it doesn't exist.
- File file = new File(packageObbDir);
- if (!file.exists()) {
- vold.setupAppDir(packageObbDir, mPmInternal.getPackage(pkg).getUid());
- }
- file = new File(packageDataDir);
- if (!file.exists()) {
- vold.setupAppDir(packageDataDir, mPmInternal.getPackage(pkg).getUid());
- }
+ // Create package obb and data dir if it doesn't exist.
+ File file = new File(packageObbDir);
+ if (!file.exists()) {
+ vold.setupAppDir(packageObbDir, mPmInternal.getPackage(pkg).getUid());
}
- } catch (ServiceManager.ServiceNotFoundException | RemoteException e) {
- Slog.e(TAG, "Unable to create obb and data directories for " + processName, e);
+ file = new File(packageDataDir);
+ if (!file.exists()) {
+ vold.setupAppDir(packageDataDir, mPmInternal.getPackage(pkg).getUid());
+ }
}
+ } catch (ServiceManager.ServiceNotFoundException | RemoteException e) {
+ Slog.e(TAG, "Unable to create obb and data directories for " + processName,e);
+ return false;
}
+ return true;
}
@Override
diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java
index 1415433..7dedad7 100644
--- a/services/core/java/com/android/server/TelephonyRegistry.java
+++ b/services/core/java/com/android/server/TelephonyRegistry.java
@@ -167,14 +167,13 @@
@Override
public String toString() {
- return "{callingPackage=" + callingPackage + " binder=" + binder
- + " callback=" + callback
+ return "{callingPackage=" + pii(callingPackage) + " callerUid=" + callerUid + " binder="
+ + binder + " callback=" + callback
+ " onSubscriptionsChangedListenererCallback="
+ onSubscriptionsChangedListenerCallback
+ " onOpportunisticSubscriptionsChangedListenererCallback="
- + onOpportunisticSubscriptionsChangedListenerCallback
- + " callerUid=" + callerUid + " subId=" + subId + " phoneId=" + phoneId
- + " events=" + Integer.toHexString(events) + "}";
+ + onOpportunisticSubscriptionsChangedListenerCallback + " subId=" + subId
+ + " phoneId=" + phoneId + " events=" + Integer.toHexString(events) + "}";
}
}
@@ -598,9 +597,9 @@
int callerUserId = UserHandle.getCallingUserId();
mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
if (VDBG) {
- log("listen oscl: E pkg=" + callingPackage + " myUserId=" + UserHandle.myUserId()
- + " callerUserId=" + callerUserId + " callback=" + callback
- + " callback.asBinder=" + callback.asBinder());
+ log("listen oscl: E pkg=" + pii(callingPackage) + " uid=" + Binder.getCallingUid()
+ + " myUserId=" + UserHandle.myUserId() + " callerUserId=" + callerUserId
+ + " callback=" + callback + " callback.asBinder=" + callback.asBinder());
}
synchronized (mRecords) {
@@ -652,9 +651,9 @@
int callerUserId = UserHandle.getCallingUserId();
mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
if (VDBG) {
- log("listen ooscl: E pkg=" + callingPackage + " myUserId=" + UserHandle.myUserId()
- + " callerUserId=" + callerUserId + " callback=" + callback
- + " callback.asBinder=" + callback.asBinder());
+ log("listen ooscl: E pkg=" + pii(callingPackage) + " uid=" + Binder.getCallingUid()
+ + " myUserId=" + UserHandle.myUserId() + " callerUserId=" + callerUserId
+ + " callback=" + callback + " callback.asBinder=" + callback.asBinder());
}
synchronized (mRecords) {
@@ -769,9 +768,9 @@
IPhoneStateListener callback, int events, boolean notifyNow, int subId) {
int callerUserId = UserHandle.getCallingUserId();
mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
- String str = "listen: E pkg=" + callingPackage + " events=0x" + Integer.toHexString(events)
- + " notifyNow=" + notifyNow + " subId=" + subId + " myUserId="
- + UserHandle.myUserId() + " callerUserId=" + callerUserId;
+ String str = "listen: E pkg=" + pii(callingPackage) + " uid=" + Binder.getCallingUid()
+ + " events=0x" + Integer.toHexString(events) + " notifyNow=" + notifyNow + " subId="
+ + subId + " myUserId=" + UserHandle.myUserId() + " callerUserId=" + callerUserId;
mListenLog.log(str);
if (VDBG) {
log(str);
@@ -2957,4 +2956,14 @@
if (info == null) return INVALID_SIM_SLOT_INDEX;
return info.getSimSlotIndex();
}
+
+ /**
+ * On certain build types, we should redact information by default. UID information will be
+ * preserved in the same log line, so no debugging capability is lost in full bug reports.
+ * However, privacy-constrained bug report types (e.g. connectivity) cannot display raw
+ * package names on user builds as it's considered an information leak.
+ */
+ private static String pii(String packageName) {
+ return Build.IS_DEBUGGABLE ? packageName : "***";
+ }
}
diff --git a/services/core/java/com/android/server/UiModeManagerService.java b/services/core/java/com/android/server/UiModeManagerService.java
index 88b517c..12a1a95 100644
--- a/services/core/java/com/android/server/UiModeManagerService.java
+++ b/services/core/java/com/android/server/UiModeManagerService.java
@@ -75,7 +75,9 @@
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
+import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -293,7 +295,7 @@
public void onChange(boolean selfChange, Uri uri) {
synchronized (mLock) {
// setup wizard is done now so we can unblock
- if (setupWizardCompleteForCurrentUser()) {
+ if (setupWizardCompleteForCurrentUser() && !selfChange) {
mSetupWizardComplete = true;
getContext().getContentResolver()
.unregisterContentObserver(mSetupWizardObserver);
@@ -348,6 +350,9 @@
IntentFilter batteryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
context.registerReceiver(mBatteryReceiver, batteryFilter);
+ context.registerReceiver(mSettingsRestored,
+ new IntentFilter(Intent.ACTION_SETTING_RESTORED), null, mHandler);
+
mLocalPowerManager =
LocalServices.getService(PowerManagerInternal.class);
initPowerSave();
@@ -395,6 +400,22 @@
mHandler.post(() -> updateSystemProperties());
}
+ private final BroadcastReceiver mSettingsRestored = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ List<String> settings = Arrays.asList(
+ Secure.UI_NIGHT_MODE, Secure.DARK_THEME_CUSTOM_START_TIME,
+ Secure.DARK_THEME_CUSTOM_END_TIME);
+ if (settings.contains(intent.getExtras().getCharSequence(Intent.EXTRA_SETTING_NAME))) {
+ synchronized (mLock) {
+ updateNightModeFromSettingsLocked(context, context.getResources(),
+ UserHandle.getCallingUserId());
+ updateConfigurationLocked();
+ }
+ }
+ }
+ };
+
private void initPowerSave() {
mPowerSave =
mLocalPowerManager.getLowPowerState(ServiceType.NIGHT_MODE)
@@ -467,9 +488,9 @@
mNightMode = Secure.getIntForUser(context.getContentResolver(),
Secure.UI_NIGHT_MODE, defaultNightMode, userId);
mOverrideNightModeOn = Secure.getIntForUser(context.getContentResolver(),
- Secure.UI_NIGHT_MODE_OVERRIDE_ON, defaultNightMode, userId) != 0;
+ Secure.UI_NIGHT_MODE_OVERRIDE_ON, 0, userId) != 0;
mOverrideNightModeOff = Secure.getIntForUser(context.getContentResolver(),
- Secure.UI_NIGHT_MODE_OVERRIDE_OFF, defaultNightMode, userId) != 0;
+ Secure.UI_NIGHT_MODE_OVERRIDE_OFF, 0, userId) != 0;
mCustomAutoNightModeStartMilliseconds = LocalTime.ofNanoOfDay(
Secure.getLongForUser(context.getContentResolver(),
Secure.DARK_THEME_CUSTOM_START_TIME,
@@ -1045,7 +1066,6 @@
final TwilightState lastState = mTwilightManager.getLastTwilightState();
activateNightMode = lastState == null ? mComputedNightMode : lastState.isNight();
}
-
updateComputedNightModeLocked(activateNightMode);
} else {
if (mTwilightManager != null) {
@@ -1298,9 +1318,9 @@
if (Sandman.shouldStartDockApp(getContext(), homeIntent)) {
try {
int result = ActivityTaskManager.getService().startActivityWithConfig(
- null, getContext().getBasePackageName(), getContext().getFeatureId(),
- homeIntent, null, null, null, 0, 0, mConfiguration, null,
- UserHandle.USER_CURRENT);
+ null, getContext().getBasePackageName(),
+ getContext().getAttributionTag(), homeIntent, null, null, null, 0, 0,
+ mConfiguration, null, UserHandle.USER_CURRENT);
if (ActivityManager.isStartResultSuccessful(result)) {
dockAppStarted = true;
} else if (result != ActivityManager.START_INTENT_NOT_RESOLVED) {
@@ -1375,6 +1395,9 @@
private void updateComputedNightModeLocked(boolean activate) {
mComputedNightMode = activate;
+ if (mNightMode == MODE_NIGHT_YES || mNightMode == UiModeManager.MODE_NIGHT_NO) {
+ return;
+ }
if (mOverrideNightModeOn && !mComputedNightMode) {
mComputedNightMode = true;
return;
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index cfc8b45..0ebb5bb 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -137,6 +137,10 @@
private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
+ //TODO: remove this when development is done.
+ private static final int DEBUG_FGS_ALLOW_WHILE_IN_USE = 0;
+ private static final int DEBUG_FGS_ENFORCE_TYPE = 1;
+
// How long we wait for a service to finish executing.
static final int SERVICE_TIMEOUT = 20*1000;
@@ -1701,7 +1705,7 @@
if (acceptances > 0 || rejections > 0) {
FrameworkStatsLog.write(
FrameworkStatsLog.FOREGROUND_SERVICE_APP_OP_SESSION_ENDED,
- mProcessRecord.uid, opToEnum(op),
+ mProcessRecord.uid, AppOpsManager.opToLoggingId(op),
modeToEnum(mAppOpModes.get(op)),
acceptances, rejections
);
@@ -1725,22 +1729,6 @@
}
}
- /** Maps AppOp op value to atoms.proto enum. */
- private static int opToEnum(int op) {
- switch (op) {
- case AppOpsManager.OP_COARSE_LOCATION: return FrameworkStatsLog
- .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_NAME__OP_COARSE_LOCATION;
- case AppOpsManager.OP_FINE_LOCATION: return FrameworkStatsLog
- .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_NAME__OP_FINE_LOCATION;
- case AppOpsManager.OP_CAMERA: return FrameworkStatsLog
- .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_NAME__OP_CAMERA;
- case AppOpsManager.OP_RECORD_AUDIO: return FrameworkStatsLog
- .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_NAME__OP_RECORD_AUDIO;
- default: return FrameworkStatsLog
- .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_NAME__OP_NONE;
- }
- }
-
private void cancelForegroundNotificationLocked(ServiceRecord r) {
if (r.foregroundId != 0) {
// First check to see if this app has any other active foreground services
@@ -4931,10 +4919,20 @@
if (!r.isForeground) {
continue;
}
- if (!r.mAllowWhileInUsePermissionInFgs
- && r.mInfoDenyWhileInUsePermissionInFgs != null) {
- final String msg = r.mInfoDenyWhileInUsePermissionInFgs
- + " affected while-in-use permission:"
+ if (mode == DEBUG_FGS_ALLOW_WHILE_IN_USE) {
+ if (!r.mAllowWhileInUsePermissionInFgs
+ && r.mInfoDenyWhileInUsePermissionInFgs != null) {
+ final String msg = r.mInfoDenyWhileInUsePermissionInFgs
+ + " affected while-in-use permission:"
+ + AppOpsManager.opToPublicName(op);
+ Slog.wtf(TAG, msg);
+ }
+ } else if (mode == DEBUG_FGS_ENFORCE_TYPE) {
+ final String msg =
+ "FGS Missing foregroundServiceType in manifest file [callingPackage: "
+ + r.mRecentCallingPackage
+ + "; intent:" + r.intent.getIntent()
+ + "] affected while-in-use permission:"
+ AppOpsManager.opToPublicName(op);
Slog.wtf(TAG, msg);
}
diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java
index 8fbe923..6b917bc 100644
--- a/services/core/java/com/android/server/am/ActivityManagerConstants.java
+++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java
@@ -19,16 +19,12 @@
import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER_QUICK;
import android.app.ActivityThread;
-import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
-import android.content.pm.UserInfo;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
-import android.os.UserHandle;
-import android.os.UserManager;
import android.provider.DeviceConfig;
import android.provider.DeviceConfig.OnPropertiesChangedListener;
import android.provider.DeviceConfig.Properties;
@@ -37,7 +33,6 @@
import android.util.ArraySet;
import android.util.KeyValueListParser;
import android.util.Slog;
-import android.util.SparseArray;
import java.io.PrintWriter;
import java.util.Arrays;
@@ -294,12 +289,6 @@
// started, the restriction is on while-in-use permissions.)
volatile boolean mFlagBackgroundFgsStartRestrictionEnabled = true;
- /**
- * UserId to Assistant ComponentName mapping.
- * Per user Assistant ComponentName is from {@link android.provider.Settings.Secure#ASSISTANT}
- */
- SparseArray<ComponentName> mAssistants = new SparseArray<>();
-
private final ActivityManagerService mService;
private ContentResolver mResolver;
private final KeyValueListParser mParser = new KeyValueListParser(',');
@@ -375,8 +364,6 @@
Settings.Global.getUriFor(
Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED);
- private static final Uri ASSISTANT_URI = Settings.Secure.getUriFor(Settings.Secure.ASSISTANT);
-
private static final Uri ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI =
Settings.Global.getUriFor(Settings.Global.ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS);
@@ -443,8 +430,6 @@
mResolver.registerContentObserver(ACTIVITY_STARTS_LOGGING_ENABLED_URI, false, this);
mResolver.registerContentObserver(FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED_URI,
false, this);
- mResolver.registerContentObserver(ASSISTANT_URI, false, this,
- UserHandle.USER_ALL);
if (mSystemServerAutomaticHeapDumpEnabled) {
mResolver.registerContentObserver(ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI,
false, this);
@@ -460,7 +445,6 @@
// The following read from Settings.
updateActivityStartsLoggingEnabled();
updateForegroundServiceStartsLoggingEnabled();
- updateAssistant();
}
private void loadDeviceConfigConstants() {
@@ -492,8 +476,6 @@
updateForegroundServiceStartsLoggingEnabled();
} else if (ENABLE_AUTOMATIC_SYSTEM_SERVER_HEAP_DUMPS_URI.equals(uri)) {
updateEnableAutomaticSystemServerHeapDumps();
- } else if (ASSISTANT_URI.equals(uri)) {
- updateAssistant();
}
}
@@ -590,32 +572,6 @@
mFlagForegroundServiceStartsLoggingEnabled = Settings.Global.getInt(mResolver,
Settings.Global.FOREGROUND_SERVICE_STARTS_LOGGING_ENABLED, 1) == 1;
}
-
- private void updateAssistant() {
- final List<UserInfo> users =
- mService.mContext.getSystemService(UserManager.class).getUsers();
- SparseArray<ComponentName> componentNames = new SparseArray<>();
- for (int i = 0; i < users.size(); i++) {
- final int userId = users.get(i).id;
- final String str = Settings.Secure.getStringForUser(mResolver,
- Settings.Secure.ASSISTANT, userId);
- if (!TextUtils.isEmpty(str)) {
- componentNames.put(userId, ComponentName.unflattenFromString(str));
- }
- }
- synchronized (mService) {
- for (int i = 0; i < mAssistants.size(); i++) {
- mService.mServices.mWhiteListAllowWhileInUsePermissionInFgs.remove(
- mAssistants.valueAt(i).getPackageName());
- }
- mAssistants = componentNames;
- for (int i = 0; i < mAssistants.size(); i++) {
- mService.mServices.mWhiteListAllowWhileInUsePermissionInFgs.add(
- mAssistants.valueAt(i).getPackageName());
- }
- }
- }
-
private void updateBackgroundFgsStartsRestriction() {
mFlagBackgroundFgsStartRestrictionEnabled = DeviceConfig.getBoolean(
DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 9058ac4..4485af1 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -4766,7 +4766,8 @@
packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED
: ApplicationExitInfo.REASON_USER_REQUESTED,
ApplicationExitInfo.SUBREASON_UNKNOWN,
- packageName == null ? ("stop user " + userId) : ("stop " + packageName));
+ (packageName == null ? ("stop user " + userId) : ("stop " + packageName))
+ + " due to " + reason);
didSomething |=
mAtmInternal.onForceStopPackage(packageName, doit, evenPersistent, userId);
@@ -17066,6 +17067,7 @@
proc.lastCachedPss = pss;
proc.lastCachedSwapPss = swapPss;
}
+ proc.mLastRss = rss;
final SparseArray<Pair<Long, String>> watchUids
= mMemWatchProcesses.getMap().get(proc.processName);
@@ -17536,8 +17538,11 @@
final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) {
if (proc.thread != null && proc.baseProcessTracker != null) {
- proc.baseProcessTracker.setState(
- proc.getReportedProcState(), memFactor, now, proc.pkgList.mPkgList);
+ final int procState = proc.getReportedProcState();
+ if (procState != PROCESS_STATE_NONEXISTENT) {
+ proc.baseProcessTracker.setState(
+ procState, memFactor, now, proc.pkgList.mPkgList);
+ }
}
}
@@ -18712,6 +18717,11 @@
}
@Override
+ public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) {
+ return mProcessList.getProcessesWithPendingBindMounts(userId);
+ }
+
+ @Override
public boolean isSystemReady() {
// no need to synchronize(this) just to read & return the value
return mSystemReady;
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 59f64ac..8f5fbf7 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -2931,25 +2931,35 @@
final PlatformCompat platformCompat = (PlatformCompat)
ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);
String toggleValue = getNextArgRequired();
- if (toggleValue.equals("reset-all")) {
- final String packageName = getNextArgRequired();
- pw.println("Reset all changes for " + packageName + " to default value.");
- platformCompat.clearOverrides(packageName);
- return 0;
- }
- long changeId;
- String changeIdString = getNextArgRequired();
- try {
- changeId = Long.parseLong(changeIdString);
- } catch (NumberFormatException e) {
- changeId = platformCompat.lookupChangeId(changeIdString);
- }
- if (changeId == -1) {
- pw.println("Unknown or invalid change: '" + changeIdString + "'.");
- return -1;
+ boolean toggleAll = false;
+ int targetSdkVersion = -1;
+ long changeId = -1;
+
+ if (toggleValue.endsWith("-all")) {
+ toggleValue = toggleValue.substring(0, toggleValue.lastIndexOf("-all"));
+ toggleAll = true;
+ if (!toggleValue.equals("reset")) {
+ try {
+ targetSdkVersion = Integer.parseInt(getNextArgRequired());
+ } catch (NumberFormatException e) {
+ pw.println("Invalid targetSdkVersion!");
+ return -1;
+ }
+ }
+ } else {
+ String changeIdString = getNextArgRequired();
+ try {
+ changeId = Long.parseLong(changeIdString);
+ } catch (NumberFormatException e) {
+ changeId = platformCompat.lookupChangeId(changeIdString);
+ }
+ if (changeId == -1) {
+ pw.println("Unknown or invalid change: '" + changeIdString + "'.");
+ return -1;
+ }
}
String packageName = getNextArgRequired();
- if (!platformCompat.isKnownChangeId(changeId)) {
+ if (!toggleAll && !platformCompat.isKnownChangeId(changeId)) {
pw.println("Warning! Change " + changeId + " is not known yet. Enabling/disabling it"
+ " could have no effect.");
}
@@ -2958,22 +2968,49 @@
try {
switch (toggleValue) {
case "enable":
- enabled.add(changeId);
- CompatibilityChangeConfig overrides =
- new CompatibilityChangeConfig(
- new Compatibility.ChangeConfig(enabled, disabled));
- platformCompat.setOverrides(overrides, packageName);
- pw.println("Enabled change " + changeId + " for " + packageName + ".");
+ if (toggleAll) {
+ int numChanges = platformCompat.enableTargetSdkChanges(packageName,
+ targetSdkVersion);
+ if (numChanges == 0) {
+ pw.println("No changes were enabled.");
+ return -1;
+ }
+ pw.println("Enabled " + numChanges + " changes gated by targetSdkVersion "
+ + targetSdkVersion + " for " + packageName + ".");
+ } else {
+ enabled.add(changeId);
+ CompatibilityChangeConfig overrides =
+ new CompatibilityChangeConfig(
+ new Compatibility.ChangeConfig(enabled, disabled));
+ platformCompat.setOverrides(overrides, packageName);
+ pw.println("Enabled change " + changeId + " for " + packageName + ".");
+ }
return 0;
case "disable":
- disabled.add(changeId);
- overrides =
- new CompatibilityChangeConfig(
- new Compatibility.ChangeConfig(enabled, disabled));
- platformCompat.setOverrides(overrides, packageName);
- pw.println("Disabled change " + changeId + " for " + packageName + ".");
+ if (toggleAll) {
+ int numChanges = platformCompat.disableTargetSdkChanges(packageName,
+ targetSdkVersion);
+ if (numChanges == 0) {
+ pw.println("No changes were disabled.");
+ return -1;
+ }
+ pw.println("Disabled " + numChanges + " changes gated by targetSdkVersion "
+ + targetSdkVersion + " for " + packageName + ".");
+ } else {
+ disabled.add(changeId);
+ CompatibilityChangeConfig overrides =
+ new CompatibilityChangeConfig(
+ new Compatibility.ChangeConfig(enabled, disabled));
+ platformCompat.setOverrides(overrides, packageName);
+ pw.println("Disabled change " + changeId + " for " + packageName + ".");
+ }
return 0;
case "reset":
+ if (toggleAll) {
+ platformCompat.clearOverrides(packageName);
+ pw.println("Reset all changes for " + packageName + " to default value.");
+ return 0;
+ }
if (platformCompat.clearOverride(changeId, packageName)) {
pw.println("Reset change " + changeId + " for " + packageName
+ " to default value.");
@@ -3304,6 +3341,8 @@
pw.println(" enable|disable|reset <CHANGE_ID|CHANGE_NAME> <PACKAGE_NAME>");
pw.println(" Toggles a change either by id or by name for <PACKAGE_NAME>.");
pw.println(" It kills <PACKAGE_NAME> (to allow the toggle to take effect).");
+ pw.println(" enable-all|disable-all <targetSdkVersion> <PACKAGE_NAME");
+ pw.println(" Toggles all changes that are gated by <targetSdkVersion>.");
pw.println(" reset-all <PACKAGE_NAME>");
pw.println(" Removes all existing overrides for all changes for ");
pw.println(" <PACKAGE_NAME> (back to default behaviour).");
diff --git a/services/core/java/com/android/server/am/AppExitInfoTracker.java b/services/core/java/com/android/server/am/AppExitInfoTracker.java
index a09aa64..028a059 100644
--- a/services/core/java/com/android/server/am/AppExitInfoTracker.java
+++ b/services/core/java/com/android/server/am/AppExitInfoTracker.java
@@ -129,7 +129,7 @@
private final ProcessMap<AppExitInfoContainer> mData;
/** A pool of raw {@link android.app.ApplicationExitInfo} records. */
- @GuardedBy("mService")
+ @GuardedBy("mLock")
private final SynchronizedPool<ApplicationExitInfo> mRawRecordsPool;
/**
@@ -204,8 +204,7 @@
});
}
- @GuardedBy("mService")
- void scheduleNoteProcessDiedLocked(final ProcessRecord app) {
+ void scheduleNoteProcessDied(final ProcessRecord app) {
if (app == null || app.info == null) {
return;
}
@@ -214,11 +213,9 @@
if (!mAppExitInfoLoaded) {
return;
}
+ mKillHandler.obtainMessage(KillHandler.MSG_PROC_DIED, obtainRawRecordLocked(app))
+ .sendToTarget();
}
- // The current thread is holding the global lock, let's extract the info from it
- // and schedule the info note task in the kill handler.
- mKillHandler.obtainMessage(KillHandler.MSG_PROC_DIED, obtainRawRecordLocked(app))
- .sendToTarget();
}
void scheduleNoteAppKill(final ProcessRecord app, final @Reason int reason,
@@ -227,8 +224,6 @@
if (!mAppExitInfoLoaded) {
return;
}
- }
- synchronized (mService) {
if (app == null || app.info == null) {
return;
}
@@ -247,8 +242,6 @@
if (!mAppExitInfoLoaded) {
return;
}
- }
- synchronized (mService) {
ProcessRecord app;
synchronized (mService.mPidsSelfLocked) {
app = mService.mPidsSelfLocked.get(pid);
@@ -512,9 +505,13 @@
@VisibleForTesting
void onPackageRemoved(String packageName, int uid, boolean allUsers) {
if (packageName != null) {
- mAppExitInfoSourceZygote.removeByUid(uid, allUsers);
- mAppExitInfoSourceLmkd.removeByUid(uid, allUsers);
- mIsolatedUidRecords.removeAppUid(uid, allUsers);
+ final boolean removeUid = TextUtils.isEmpty(
+ mService.mPackageManagerInt.getNameForUid(uid));
+ if (removeUid) {
+ mAppExitInfoSourceZygote.removeByUid(uid, allUsers);
+ mAppExitInfoSourceLmkd.removeByUid(uid, allUsers);
+ mIsolatedUidRecords.removeAppUid(uid, allUsers);
+ }
removePackage(packageName, allUsers ? UserHandle.USER_ALL : UserHandle.getUserId(uid));
schedulePersistProcessExitInfo(true);
}
@@ -540,6 +537,11 @@
mService.mContext.registerReceiverForAllUsers(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
+ boolean replacing = intent.getBooleanExtra(
+ Intent.EXTRA_REPLACING, false);
+ if (replacing) {
+ return;
+ }
int uid = intent.getIntExtra(Intent.EXTRA_UID, UserHandle.USER_NULL);
boolean allUsers = intent.getBooleanExtra(
Intent.EXTRA_REMOVED_FOR_ALL_USERS, false);
@@ -823,7 +825,7 @@
}
@VisibleForTesting
- @GuardedBy("mService")
+ @GuardedBy("mLock")
ApplicationExitInfo obtainRawRecordLocked(ProcessRecord app) {
ApplicationExitInfo info = mRawRecordsPool.acquire();
if (info == null) {
@@ -842,15 +844,15 @@
info.setReason(ApplicationExitInfo.REASON_UNKNOWN);
info.setStatus(0);
info.setImportance(procStateToImportance(app.setProcState));
- info.setPss(app.lastMemInfo == null ? 0 : app.lastMemInfo.getTotalPss());
- info.setRss(app.lastMemInfo == null ? 0 : app.lastMemInfo.getTotalRss());
+ info.setPss(app.lastPss);
+ info.setRss(app.mLastRss);
info.setTimestamp(System.currentTimeMillis());
return info;
}
@VisibleForTesting
- @GuardedBy("mService")
+ @GuardedBy("mLock")
void recycleRawRecordLocked(ApplicationExitInfo info) {
info.setProcessName(null);
info.setDescription(null);
@@ -1135,8 +1137,6 @@
ApplicationExitInfo raw = (ApplicationExitInfo) msg.obj;
synchronized (mLock) {
handleNoteProcessDiedLocked(raw);
- }
- synchronized (mService) {
recycleRawRecordLocked(raw);
}
}
@@ -1145,8 +1145,6 @@
ApplicationExitInfo raw = (ApplicationExitInfo) msg.obj;
synchronized (mLock) {
handleNoteAppKillLocked(raw);
- }
- synchronized (mService) {
recycleRawRecordLocked(raw);
}
}
diff --git a/services/core/java/com/android/server/am/CachedAppOptimizer.java b/services/core/java/com/android/server/am/CachedAppOptimizer.java
index be48374..86d9028 100644
--- a/services/core/java/com/android/server/am/CachedAppOptimizer.java
+++ b/services/core/java/com/android/server/am/CachedAppOptimizer.java
@@ -121,12 +121,13 @@
static final int COMPACT_PROCESS_MSG = 1;
static final int COMPACT_SYSTEM_MSG = 2;
static final int SET_FROZEN_PROCESS_MSG = 3;
+ static final int REPORT_UNFREEZE_MSG = 4;
//TODO:change this static definition into a configurable flag.
static final int FREEZE_TIMEOUT_MS = 500;
static final int DO_FREEZE = 1;
- static final int DO_UNFREEZE = 2;
+ static final int REPORT_UNFREEZE = 2;
/**
* This thread must be moved to the system background cpuset.
@@ -614,11 +615,41 @@
}
@GuardedBy("mAm")
- void unfreezeAppAsync(ProcessRecord app) {
+ void unfreezeAppLocked(ProcessRecord app) {
mFreezeHandler.removeMessages(SET_FROZEN_PROCESS_MSG, app);
- mFreezeHandler.sendMessage(
- mFreezeHandler.obtainMessage(SET_FROZEN_PROCESS_MSG, DO_UNFREEZE, 0, app));
+ if (!app.frozen) {
+ if (DEBUG_FREEZER) {
+ Slog.d(TAG_AM,
+ "Skipping unfreeze for process " + app.pid + " "
+ + app.processName + " (not frozen)");
+ }
+ return;
+ }
+
+ long freezeTime = app.freezeUnfreezeTime;
+
+ try {
+ Process.setProcessFrozen(app.pid, app.uid, false);
+
+ app.freezeUnfreezeTime = SystemClock.uptimeMillis();
+ app.frozen = false;
+ } catch (Exception e) {
+ Slog.e(TAG_AM, "Unable to unfreeze " + app.pid + " " + app.processName
+ + ". Any related user experience might be hanged.");
+ }
+
+ if (!app.frozen) {
+ if (DEBUG_FREEZER) {
+ Slog.d(TAG_AM, "sync unfroze " + app.pid + " " + app.processName);
+ }
+
+ mFreezeHandler.sendMessage(
+ mFreezeHandler.obtainMessage(REPORT_UNFREEZE_MSG,
+ app.pid,
+ (int) Math.min(app.freezeUnfreezeTime - freezeTime, Integer.MAX_VALUE),
+ app.processName));
+ }
}
private static final class LastCompactionStats {
@@ -890,14 +921,19 @@
@Override
public void handleMessage(Message msg) {
- if (msg.what != SET_FROZEN_PROCESS_MSG) {
- return;
- }
+ switch (msg.what) {
+ case SET_FROZEN_PROCESS_MSG:
+ freezeProcess((ProcessRecord) msg.obj);
+ break;
+ case REPORT_UNFREEZE_MSG:
+ int pid = msg.arg1;
+ int frozenDuration = msg.arg2;
+ String processName = (String) msg.obj;
- if (msg.arg1 == DO_FREEZE) {
- freezeProcess((ProcessRecord) msg.obj);
- } else if (msg.arg1 == DO_UNFREEZE) {
- unfreezeProcess((ProcessRecord) msg.obj);
+ reportUnfreeze(pid, frozenDuration, processName);
+ break;
+ default:
+ return;
}
}
@@ -960,61 +996,18 @@
}
}
- private void unfreezeProcess(ProcessRecord proc) {
- final int pid;
- final String name;
- final long frozenDuration;
- final boolean frozen;
+ private void reportUnfreeze(int pid, int frozenDuration, String processName) {
- synchronized (mAm) {
- pid = proc.pid;
- name = proc.processName;
+ EventLog.writeEvent(EventLogTags.AM_UNFREEZE, pid, processName);
- if (!proc.frozen) {
- if (DEBUG_FREEZER) {
- Slog.d(TAG_AM,
- "Skipping unfreeze for process " + pid + " "
- + name + " (not frozen)");
- }
- return;
- }
-
- if (pid == 0) {
- // Not a real process, either being launched or killed
- return;
- }
-
- long freezeTime = proc.freezeUnfreezeTime;
-
- try {
- Process.setProcessFrozen(proc.pid, proc.uid, false);
-
- proc.freezeUnfreezeTime = SystemClock.uptimeMillis();
- proc.frozen = false;
- } catch (Exception e) {
- Slog.w(TAG_AM, "Unable to unfreeze " + pid + " " + name);
- }
-
- frozenDuration = proc.freezeUnfreezeTime - freezeTime;
- frozen = proc.frozen;
- }
-
- if (!frozen) {
- if (DEBUG_FREEZER) {
- Slog.d(TAG_AM, "unfroze " + pid + " " + name);
- }
-
- EventLog.writeEvent(EventLogTags.AM_UNFREEZE, pid, name);
-
- // See above for why we're not taking mPhenotypeFlagLock here
- if (mRandom.nextFloat() < mFreezerStatsdSampleRate) {
- FrameworkStatsLog.write(
- FrameworkStatsLog.APP_FREEZE_CHANGED,
- FrameworkStatsLog.APP_FREEZE_CHANGED__ACTION__UNFREEZE_APP,
- pid,
- name,
- frozenDuration);
- }
+ // See above for why we're not taking mPhenotypeFlagLock here
+ if (mRandom.nextFloat() < mFreezerStatsdSampleRate) {
+ FrameworkStatsLog.write(
+ FrameworkStatsLog.APP_FREEZE_CHANGED,
+ FrameworkStatsLog.APP_FREEZE_CHANGED__ACTION__UNFREEZE_APP,
+ pid,
+ processName,
+ frozenDuration);
}
}
}
diff --git a/services/core/java/com/android/server/am/CoreSettingsObserver.java b/services/core/java/com/android/server/am/CoreSettingsObserver.java
index 48ceba9..8527ae9 100644
--- a/services/core/java/com/android/server/am/CoreSettingsObserver.java
+++ b/services/core/java/com/android/server/am/CoreSettingsObserver.java
@@ -115,6 +115,10 @@
DeviceConfig.NAMESPACE_WIDGET, WidgetFlags.ENABLE_CURSOR_DRAG_FROM_ANYWHERE,
WidgetFlags.KEY_ENABLE_CURSOR_DRAG_FROM_ANYWHERE, boolean.class,
WidgetFlags.ENABLE_CURSOR_DRAG_FROM_ANYWHERE_DEFAULT));
+ sDeviceConfigEntries.add(new DeviceConfigEntry<Integer>(
+ DeviceConfig.NAMESPACE_WIDGET, WidgetFlags.FINGER_TO_CURSOR_DISTANCE,
+ WidgetFlags.KEY_FINGER_TO_CURSOR_DISTANCE, int.class,
+ WidgetFlags.FINGER_TO_CURSOR_DISTANCE_DEFAULT));
sDeviceConfigEntries.add(new DeviceConfigEntry<Boolean>(
DeviceConfig.NAMESPACE_WIDGET, WidgetFlags.ENABLE_INSERTION_HANDLE_GESTURES,
WidgetFlags.KEY_ENABLE_INSERTION_HANDLE_GESTURES, boolean.class,
diff --git a/services/core/java/com/android/server/am/OWNERS b/services/core/java/com/android/server/am/OWNERS
index 7cc2e8e..1f826b5 100644
--- a/services/core/java/com/android/server/am/OWNERS
+++ b/services/core/java/com/android/server/am/OWNERS
@@ -16,12 +16,6 @@
# Windows & Activities
ogunwale@google.com
-jjaggi@google.com
-racarr@google.com
-chaviw@google.com
-vishnun@google.com
-akulian@google.com
-roosa@google.com
# Permissions & Packages
svetoslavganov@google.com
diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java
index aa37b4a..2b1534b 100644
--- a/services/core/java/com/android/server/am/OomAdjuster.java
+++ b/services/core/java/com/android/server/am/OomAdjuster.java
@@ -75,7 +75,6 @@
import android.app.ApplicationExitInfo;
import android.app.usage.UsageEvents;
import android.compat.annotation.ChangeId;
-import android.compat.annotation.Disabled;
import android.compat.annotation.EnabledAfter;
import android.content.Context;
import android.content.pm.ServiceInfo;
@@ -149,12 +148,13 @@
* capabilities.
*/
@ChangeId
- //TODO: change to @EnabledAfter when enforcing the feature.
- @Disabled
+ @EnabledAfter(targetSdkVersion=android.os.Build.VERSION_CODES.Q)
static final long CAMERA_MICROPHONE_CAPABILITY_CHANGE_ID = 136219221L;
//TODO: remove this when development is done.
private static final int TEMP_PROCESS_CAPABILITY_FOREGROUND_LOCATION = 1 << 31;
+ private static final int TEMP_PROCESS_CAPABILITY_FOREGROUND_CAMERA = 1 << 30;
+ private static final int TEMP_PROCESS_CAPABILITY_FOREGROUND_MICROPHONE = 1 << 29;
/**
* For some direct access we need to power manager.
@@ -1513,10 +1513,12 @@
if (enabled) {
capabilityFromFGS |=
(fgsType & FOREGROUND_SERVICE_TYPE_CAMERA)
- != 0 ? PROCESS_CAPABILITY_FOREGROUND_CAMERA : 0;
+ != 0 ? PROCESS_CAPABILITY_FOREGROUND_CAMERA
+ : TEMP_PROCESS_CAPABILITY_FOREGROUND_CAMERA;
capabilityFromFGS |=
(fgsType & FOREGROUND_SERVICE_TYPE_MICROPHONE)
- != 0 ? PROCESS_CAPABILITY_FOREGROUND_MICROPHONE : 0;
+ != 0 ? PROCESS_CAPABILITY_FOREGROUND_MICROPHONE
+ : TEMP_PROCESS_CAPABILITY_FOREGROUND_MICROPHONE;
} else {
capabilityFromFGS |= PROCESS_CAPABILITY_FOREGROUND_CAMERA
| PROCESS_CAPABILITY_FOREGROUND_MICROPHONE;
@@ -1708,11 +1710,6 @@
// TOP process passes all capabilities to the service.
capability |= PROCESS_CAPABILITY_ALL;
}
- } else if (clientProcState
- <= PROCESS_STATE_FOREGROUND_SERVICE) {
- if (cr.notHasFlag(Context.BIND_INCLUDE_CAPABILITIES)) {
- clientProcState = PROCESS_STATE_FOREGROUND_SERVICE;
- }
}
} else if ((cr.flags & Context.BIND_IMPORTANT_BACKGROUND) == 0) {
if (clientProcState <
@@ -2036,7 +2033,7 @@
case PROCESS_STATE_TOP:
return PROCESS_CAPABILITY_ALL;
case PROCESS_STATE_BOUND_TOP:
- return PROCESS_CAPABILITY_ALL_IMPLICIT;
+ return PROCESS_CAPABILITY_NONE;
case PROCESS_STATE_FOREGROUND_SERVICE:
if (app.hasForegroundServices()) {
// Capability from FGS are conditional depending on foreground service type in
@@ -2044,10 +2041,12 @@
return PROCESS_CAPABILITY_NONE;
} else {
// process has no FGS, the PROCESS_STATE_FOREGROUND_SERVICE is from client.
+ // the implicit capability could be removed in the future, client should use
+ // BIND_INCLUDE_CAPABILITY flag.
return PROCESS_CAPABILITY_ALL_IMPLICIT;
}
case PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
- return PROCESS_CAPABILITY_ALL_IMPLICIT;
+ return PROCESS_CAPABILITY_NONE;
default:
return PROCESS_CAPABILITY_NONE;
}
@@ -2588,11 +2587,16 @@
return;
}
+ // if an app is already frozen and shouldNotFreeze becomes true, immediately unfreeze
+ if (app.frozen && app.shouldNotFreeze) {
+ mCachedAppOptimizer.unfreezeAppLocked(app);
+ }
+
// Use current adjustment when freezing, set adjustment when unfreezing.
- if (app.curAdj >= ProcessList.CACHED_APP_MIN_ADJ && !app.frozen) {
+ if (app.curAdj >= ProcessList.CACHED_APP_MIN_ADJ && !app.frozen && !app.shouldNotFreeze) {
mCachedAppOptimizer.freezeAppAsync(app);
} else if (app.setAdj < ProcessList.CACHED_APP_MIN_ADJ && app.frozen) {
- mCachedAppOptimizer.unfreezeAppAsync(app);
+ mCachedAppOptimizer.unfreezeAppLocked(app);
}
}
}
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index a9d18e0..57bd42b 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -61,6 +61,7 @@
import android.app.IApplicationThread;
import android.app.IUidObserver;
import android.compat.annotation.ChangeId;
+import android.compat.annotation.Disabled;
import android.compat.annotation.EnabledAfter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -70,6 +71,7 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManagerInternal;
+import android.content.pm.ProcessInfo;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.LocalSocket;
@@ -97,6 +99,7 @@
import android.system.Os;
import android.text.TextUtils;
import android.util.ArrayMap;
+import android.util.ArraySet;
import android.util.EventLog;
import android.util.LongSparseArray;
import android.util.Pair;
@@ -134,8 +137,11 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Activity manager code dealing with processes.
@@ -152,7 +158,8 @@
"persist.sys.vold_app_data_isolation_enabled";
// A device config to control the minimum target SDK to enable app data isolation
- static final String ANDROID_APP_DATA_ISOLATION_MIN_SDK = "android_app_data_isolation_min_sdk";
+ static final String ANDROID_APP_DATA_ISOLATION_MIN_SDK =
+ "android_app_data_isolation_min_sdk";
// The minimum time we allow between crashes, for us to consider this
// application to be bad and stop and its services and reject broadcasts.
@@ -345,6 +352,14 @@
private static final long NATIVE_HEAP_POINTER_TAGGING = 135754954; // This is a bug id.
/**
+ * Enable sampled memory bug detection in the app.
+ * @see <a href="https://source.android.com/devices/tech/debug/gwp-asan">GWP-ASan</a>.
+ */
+ @ChangeId
+ @Disabled
+ private static final long GWP_ASAN = 135634846; // This is a bug id.
+
+ /**
* Apps have no access to the private data directories of any other app, even if the other
* app has made them world-readable.
*/
@@ -789,6 +804,31 @@
}
}
+ /**
+ * Get a map of pid and package name that process of that pid Android/data and Android/obb
+ * directory is not mounted to lowerfs to speed up access.
+ */
+ Map<Integer, String> getProcessesWithPendingBindMounts(int userId) {
+ final Map<Integer, String> pidPackageMap = new HashMap<>();
+ synchronized (mService) {
+ for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
+ final ProcessRecord record = mLruProcesses.get(i);
+ if (record.userId != userId || !record.bindMountPending) {
+ continue;
+ }
+ final int pid = record.pid;
+ // It can happen when app process is starting, but zygote work is not done yet so
+ // system does not this pid record yet.
+ if (pid == 0) {
+ throw new IllegalStateException("Pending process is not started yet,"
+ + "retry later");
+ }
+ pidPackageMap.put(pid, record.info.packageName);
+ }
+ return pidPackageMap;
+ }
+ }
+
private void updateOomLevels(int displayWidth, int displayHeight, boolean write) {
// Scale buckets from avail memory: at 300MB we use the lowest values to
// 700MB or more for the top values.
@@ -1634,6 +1674,28 @@
return gidArray;
}
+ private int decideGwpAsanLevel(ProcessRecord app) {
+ // Look at the process attribute first.
+ if (app.processInfo != null && app.processInfo.enableGwpAsan != null) {
+ return app.processInfo.enableGwpAsan ? Zygote.GWP_ASAN_LEVEL_ALWAYS
+ : Zygote.GWP_ASAN_LEVEL_NEVER;
+ }
+ // Then at the applicaton attribute.
+ if (app.info.isGwpAsanEnabled() != null) {
+ return app.info.isGwpAsanEnabled() ? Zygote.GWP_ASAN_LEVEL_ALWAYS
+ : Zygote.GWP_ASAN_LEVEL_NEVER;
+ }
+ // If the app does not specify enableGwpAsan, the default behavior is lottery among the
+ // system apps, and disabled for user apps, unless overwritten by the compat feature.
+ if (mPlatformCompat.isChangeEnabled(GWP_ASAN, app.info)) {
+ return Zygote.GWP_ASAN_LEVEL_ALWAYS;
+ }
+ if ((app.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
+ return Zygote.GWP_ASAN_LEVEL_LOTTERY;
+ }
+ return Zygote.GWP_ASAN_LEVEL_NEVER;
+ }
+
/**
* @return {@code true} if process start is successful, false otherwise.
*/
@@ -1648,6 +1710,7 @@
if (app.pid > 0 && app.pid != ActivityManagerService.MY_PID) {
checkSlow(startTime, "startProcess: removing from pids map");
mService.removePidLocked(app);
+ app.bindMountPending = false;
mService.mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
checkSlow(startTime, "startProcess: done removing from pids map");
app.setPid(0);
@@ -1803,6 +1866,8 @@
runtimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
}
+ runtimeFlags |= decideGwpAsanLevel(app);
+
String invokeWith = null;
if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// Debuggable apps may include a wrapper script with their library directory.
@@ -2128,8 +2193,10 @@
}
final Map<String, Pair<String, Long>> pkgDataInfoMap;
+ boolean bindMountAppStorageDirs = false;
if (shouldIsolateAppData(app)) {
+ bindMountAppStorageDirs = mVoldAppDataIsolationEnabled;
// Get all packages belongs to the same shared uid. sharedPackages is empty array
// if it doesn't have shared uid.
final PackageManagerInternal pmInt = mService.getPackageManagerInternalLocked();
@@ -2138,11 +2205,17 @@
pkgDataInfoMap = getPackageAppDataInfoMap(pmInt, sharedPackages.length == 0
? new String[]{app.info.packageName} : sharedPackages, uid);
+ int userId = UserHandle.getUserId(uid);
if (mVoldAppDataIsolationEnabled) {
StorageManagerInternal storageManagerInternal = LocalServices.getService(
- StorageManagerInternal.class);
- storageManagerInternal.prepareObbDirs(UserHandle.getUserId(uid),
- pkgDataInfoMap.keySet(), app.processName);
+ StorageManagerInternal.class);
+ if (!storageManagerInternal.prepareStorageDirs(userId, pkgDataInfoMap.keySet(),
+ app.processName)) {
+ // Cannot prepare Android/app and Android/obb directory,
+ // so we won't mount it in zygote.
+ app.bindMountPending = true;
+ bindMountAppStorageDirs = false;
+ }
}
} else {
pkgDataInfoMap = null;
@@ -2163,7 +2236,7 @@
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, null, app.info.packageName,
/*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,
- app.mDisabledCompatChanges, pkgDataInfoMap,
+ app.mDisabledCompatChanges, pkgDataInfoMap, bindMountAppStorageDirs,
new String[]{PROC_START_SEQ_IDENT + app.startSeq});
} else {
startResult = Process.start(entryPoint,
@@ -2171,6 +2244,7 @@
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags,
isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap,
+ bindMountAppStorageDirs,
new String[]{PROC_START_SEQ_IDENT + app.startSeq});
}
checkSlow(startTime, "startProcess: returned from zygote!");
@@ -2629,6 +2703,7 @@
int pid = app.pid;
if (pid > 0) {
mService.removePidLocked(app);
+ app.bindMountPending = false;
mService.mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
mService.mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
if (app.isolated) {
@@ -3773,7 +3848,7 @@
}
Watchdog.getInstance().processDied(app.processName, app.pid);
- mAppExitInfoTracker.scheduleNoteProcessDiedLocked(app);
+ mAppExitInfoTracker.scheduleNoteProcessDied(app);
}
/**
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index f2ca1da..e7f66bb 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -251,6 +251,7 @@
int adjSourceProcState; // Debugging: proc state of adjSource's process.
Object adjTarget; // Debugging: target component impacting oom_adj.
Runnable crashHandler; // Optional local handler to be invoked in the process crash.
+ boolean bindMountPending; // True if Android/obb and Android/data need to be bind mount .
// Cache of last retrieve memory info and uptime, to throttle how frequently
// apps can requyest it.
@@ -323,6 +324,8 @@
// set of disabled compat changes for the process (all others are enabled)
long[] mDisabledCompatChanges;
+ long mLastRss; // Last computed memory rss.
+
// The precede instance of the process, which would exist when the previous process is killed
// but not fully dead yet; in this case, the new instance of the process should be held until
// this precede instance is fully dead.
@@ -382,6 +385,9 @@
pw.println(processInfo.deniedPermissions.valueAt(i));
}
}
+ if (processInfo.enableGwpAsan != null) {
+ pw.print(prefix); pw.println(" enableGwpAsan=" + processInfo.enableGwpAsan);
+ }
}
pw.print(prefix); pw.print("mRequiredAbi="); pw.print(mRequiredAbi);
pw.print(" instructionSet="); pw.println(instructionSet);
@@ -431,6 +437,7 @@
pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, lastSwapPss*1024);
pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, lastCachedPss*1024);
pw.print(" lastCachedSwapPss="); DebugUtils.printSizeValue(pw, lastCachedSwapPss*1024);
+ pw.print(" lastRss="); DebugUtils.printSizeValue(pw, mLastRss * 1024);
pw.println();
pw.print(prefix); pw.print("procStateMemTracker: ");
procStateMemTracker.dumpLine(pw);
diff --git a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
index 0a8e70c..bac7565 100644
--- a/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
+++ b/services/core/java/com/android/server/am/SettingsToPropertiesMapper.java
@@ -80,6 +80,7 @@
@VisibleForTesting
static final String[] sDeviceConfigScopes = new String[] {
DeviceConfig.NAMESPACE_ACTIVITY_MANAGER_NATIVE_BOOT,
+ DeviceConfig.NAMESPACE_CONFIGURATION,
DeviceConfig.NAMESPACE_INPUT_NATIVE_BOOT,
DeviceConfig.NAMESPACE_INTELLIGENCE_CONTENT_SUGGESTIONS,
DeviceConfig.NAMESPACE_MEDIA_NATIVE,
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index 45c3aeb..2e2241f 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -19,8 +19,8 @@
import static android.app.ActivityManager.PROCESS_CAPABILITY_FOREGROUND_CAMERA;
import static android.app.ActivityManager.PROCESS_CAPABILITY_FOREGROUND_LOCATION;
import static android.app.ActivityManager.PROCESS_CAPABILITY_FOREGROUND_MICROPHONE;
-import static android.app.AppOpsManager.CALL_BACK_ON_CHANGED_LISTENER_WITH_SWITCHED_OP_CHANGE;
-import static android.app.AppOpsManager.FILTER_BY_FEATURE_ID;
+import static android.app.AppOpsManager.CALL_BACK_ON_SWITCHED_OP;
+import static android.app.AppOpsManager.FILTER_BY_ATTRIBUTION_TAG;
import static android.app.AppOpsManager.FILTER_BY_OP_NAMES;
import static android.app.AppOpsManager.FILTER_BY_PACKAGE_NAME;
import static android.app.AppOpsManager.FILTER_BY_UID;
@@ -40,6 +40,8 @@
import static android.app.AppOpsManager.OP_PLAY_AUDIO;
import static android.app.AppOpsManager.OP_RECORD_AUDIO;
import static android.app.AppOpsManager.OpEventProxyInfo;
+import static android.app.AppOpsManager.RestrictionBypass;
+import static android.app.AppOpsManager.SAMPLING_STRATEGY_BOOT_TIME_SAMPLING;
import static android.app.AppOpsManager.SAMPLING_STRATEGY_RARELY_USED;
import static android.app.AppOpsManager.SAMPLING_STRATEGY_UNIFORM;
import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
@@ -55,6 +57,7 @@
import static android.app.AppOpsManager.extractUidStateFromKey;
import static android.app.AppOpsManager.makeKey;
import static android.app.AppOpsManager.modeToName;
+import static android.app.AppOpsManager.opAllowSystemBypassRestriction;
import static android.app.AppOpsManager.opToName;
import static android.app.AppOpsManager.opToPublicName;
import static android.app.AppOpsManager.resolveFirstUnrestrictedUidState;
@@ -73,33 +76,29 @@
import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.ActivityManagerInternal;
-import android.app.ActivityThread;
import android.app.AppGlobals;
import android.app.AppOpsManager;
+import android.app.AppOpsManager.AttributedOpEntry;
import android.app.AppOpsManager.HistoricalOps;
import android.app.AppOpsManager.Mode;
import android.app.AppOpsManager.OpEntry;
-import android.app.AppOpsManager.OpFeatureEntry;
import android.app.AppOpsManager.OpFlags;
import android.app.AppOpsManagerInternal;
import android.app.AppOpsManagerInternal.CheckOpsDelegate;
import android.app.AsyncNotedAppOp;
import android.app.RuntimeAppOpAccessMessage;
import android.app.SyncNotedAppOp;
-import android.compat.Compatibility;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.IPackageManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManagerInternal;
import android.content.pm.PermissionInfo;
import android.content.pm.UserInfo;
-import android.content.pm.parsing.component.ParsedFeature;
+import android.content.pm.parsing.component.ParsedAttribution;
import android.database.ContentObserver;
import android.hardware.camera2.CameraDevice.CAMERA_AUDIO_RESTRICTION;
import android.net.Uri;
@@ -138,6 +137,7 @@
import android.util.Xml;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.annotations.Immutable;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.IAppOpsActiveCallback;
import com.android.internal.app.IAppOpsAsyncNotedCallback;
@@ -155,11 +155,14 @@
import com.android.server.LocalServices;
import com.android.server.LockGuard;
import com.android.server.SystemServerInitThreadPool;
+import com.android.server.SystemServiceManager;
import com.android.server.pm.PackageList;
import com.android.server.pm.parsing.pkg.AndroidPackage;
import libcore.util.EmptyArray;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
@@ -169,6 +172,7 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
@@ -184,6 +188,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
@@ -191,6 +196,11 @@
static final String TAG = "AppOps";
static final boolean DEBUG = false;
+ /**
+ * Used for data access validation collection, we wish to only log a specific access once
+ */
+ private final ArraySet<NoteOpTrace> mNoteOpCallerStacktraces = new ArraySet<>();
+
private static final int NO_VERSION = -1;
/** Increment by one every time and add the corresponding upgrade logic in
* {@link #upgradeLocked(int)} below. The first version was 1 */
@@ -235,12 +245,19 @@
private static final int MAX_UNFORWARED_OPS = 10;
private static final int MAX_UNUSED_POOLED_OBJECTS = 3;
+ private static final int RARELY_USED_PACKAGES_INITIALIZATION_DELAY_MILLIS = 300000;
//TODO: remove this when development is done.
private static final int TEMP_PROCESS_CAPABILITY_FOREGROUND_LOCATION = 1 << 31;
+ private static final int TEMP_PROCESS_CAPABILITY_FOREGROUND_CAMERA = 1 << 30;
+ private static final int TEMP_PROCESS_CAPABILITY_FOREGROUND_MICROPHONE = 1 << 29;
+ private static final int DEBUG_FGS_ALLOW_WHILE_IN_USE = 0;
+ private static final int DEBUG_FGS_ENFORCE_TYPE = 1;
+
final Context mContext;
final AtomicFile mFile;
+ private final @Nullable File mNoteOpCallerStacktracesFile;
final Handler mHandler;
/** Pool for {@link OpEventProxyInfoPool} to avoid to constantly reallocate new objects */
@@ -278,6 +295,8 @@
private final ArrayMap<Pair<String, Integer>, ArrayList<AsyncNotedAppOp>>
mUnforwardedAsyncNotedOps = new ArrayMap<>();
+ boolean mWriteNoteOpsScheduled;
+
boolean mWriteScheduled;
boolean mFastWriteScheduled;
final Runnable mWriteRunner = new Runnable() {
@@ -359,14 +378,14 @@
}
OpEventProxyInfo acquire(@IntRange(from = 0) int uid, @Nullable String packageName,
- @Nullable String featureId) {
+ @Nullable String attributionTag) {
OpEventProxyInfo recycled = acquire();
if (recycled != null) {
- recycled.reinit(uid, packageName, featureId);
+ recycled.reinit(uid, packageName, attributionTag);
return recycled;
}
- return new OpEventProxyInfo(uid, packageName, featureId);
+ return new OpEventProxyInfo(uid, packageName, attributionTag);
}
}
@@ -537,7 +556,7 @@
// The FGS has the location capability, but due to FGS BG start
// restriction it lost the capability, use temp location capability
// to mark this case.
- maybeShowWhileInUseDebugToast(op, mode);
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ALLOW_WHILE_IN_USE);
return MODE_IGNORED;
} else {
return MODE_IGNORED;
@@ -545,15 +564,25 @@
case OP_CAMERA:
if ((capability & PROCESS_CAPABILITY_FOREGROUND_CAMERA) != 0) {
return MODE_ALLOWED;
+ } else if ((capability & TEMP_PROCESS_CAPABILITY_FOREGROUND_CAMERA)
+ != 0) {
+ // CHANGE TO MODE_IGNORED when enforce this feature.
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ENFORCE_TYPE);
+ return MODE_ALLOWED;
} else {
- maybeShowWhileInUseDebugToast(op, mode);
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ALLOW_WHILE_IN_USE);
return MODE_IGNORED;
}
case OP_RECORD_AUDIO:
if ((capability & PROCESS_CAPABILITY_FOREGROUND_MICROPHONE) != 0) {
return MODE_ALLOWED;
+ } else if ((capability & TEMP_PROCESS_CAPABILITY_FOREGROUND_MICROPHONE)
+ != 0) {
+ // CHANGE TO MODE_IGNORED when enforce this feature.
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ENFORCE_TYPE);
+ return MODE_ALLOWED;
} else {
- maybeShowWhileInUseDebugToast(op, mode);
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ALLOW_WHILE_IN_USE);
return MODE_IGNORED;
}
default:
@@ -568,15 +597,24 @@
case OP_CAMERA:
if ((capability & PROCESS_CAPABILITY_FOREGROUND_CAMERA) != 0) {
return MODE_ALLOWED;
+ } else if ((capability & TEMP_PROCESS_CAPABILITY_FOREGROUND_CAMERA) != 0) {
+ // CHANGE TO MODE_IGNORED when enforce this feature.
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ENFORCE_TYPE);
+ return MODE_ALLOWED;
} else {
- maybeShowWhileInUseDebugToast(op, mode);
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ALLOW_WHILE_IN_USE);
return MODE_IGNORED;
}
case OP_RECORD_AUDIO:
if ((capability & PROCESS_CAPABILITY_FOREGROUND_MICROPHONE) != 0) {
return MODE_ALLOWED;
+ } else if ((capability & TEMP_PROCESS_CAPABILITY_FOREGROUND_MICROPHONE)
+ != 0) {
+ // CHANGE TO MODE_IGNORED when enforce this feature.
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ENFORCE_TYPE);
+ return MODE_ALLOWED;
} else {
- maybeShowWhileInUseDebugToast(op, mode);
+ maybeShowWhileInUseDebugToast(op, DEBUG_FGS_ALLOW_WHILE_IN_USE);
return MODE_IGNORED;
}
default:
@@ -652,15 +690,19 @@
final static class Ops extends SparseArray<Op> {
final String packageName;
final UidState uidState;
- final boolean isPrivileged;
- /** Lazily populated cache of featureIds of this package */
- final @NonNull ArraySet<String> knownFeatureIds = new ArraySet<>();
+ /**
+ * The restriction properties of the package. If {@code null} it could not have been read
+ * yet and has to be refreshed.
+ */
+ @Nullable RestrictionBypass bypass;
- Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
+ /** Lazily populated cache of attributionTags of this package */
+ final @NonNull ArraySet<String> knownAttributionTags = new ArraySet<>();
+
+ Ops(String _packageName, UidState _uidState) {
packageName = _packageName;
uidState = _uidState;
- isPrivileged = _isPrivileged;
}
}
@@ -760,8 +802,8 @@
}
}
- private final class FeatureOp {
- public final @Nullable String featureId;
+ private final class AttributedOp {
+ public final @Nullable String tag;
public final @NonNull Op parent;
/**
@@ -788,8 +830,8 @@
@GuardedBy("AppOpsService.this")
private @Nullable ArrayMap<IBinder, InProgressStartOpEvent> mInProgressEvents;
- FeatureOp(@Nullable String featureId, @NonNull Op parent) {
- this.featureId = featureId;
+ AttributedOp(@Nullable String tag, @NonNull Op parent) {
+ this.tag = tag;
this.parent = parent;
}
@@ -798,18 +840,18 @@
*
* @param proxyUid The uid of the proxy
* @param proxyPackageName The package name of the proxy
- * @param proxyFeatureId the featureId in the proxies package
+ * @param proxyAttributionTag the attributionTag in the proxies package
* @param uidState UID state of the app noteOp/startOp was called for
* @param flags OpFlags of the call
*/
public void accessed(int proxyUid, @Nullable String proxyPackageName,
- @Nullable String proxyFeatureId, @AppOpsManager.UidState int uidState,
+ @Nullable String proxyAttributionTag, @AppOpsManager.UidState int uidState,
@OpFlags int flags) {
accessed(System.currentTimeMillis(), -1, proxyUid, proxyPackageName,
- proxyFeatureId, uidState, flags);
+ proxyAttributionTag, uidState, flags);
mHistoricalRegistry.incrementOpAccessedCount(parent.op, parent.uid, parent.packageName,
- featureId, uidState, flags);
+ tag, uidState, flags);
}
/**
@@ -819,12 +861,12 @@
* @param duration The duration of the event
* @param proxyUid The uid of the proxy
* @param proxyPackageName The package name of the proxy
- * @param proxyFeatureId the featureId in the proxies package
+ * @param proxyAttributionTag the attributionTag in the proxies package
* @param uidState UID state of the app noteOp/startOp was called for
* @param flags OpFlags of the call
*/
public void accessed(long noteTime, long duration, int proxyUid,
- @Nullable String proxyPackageName, @Nullable String proxyFeatureId,
+ @Nullable String proxyPackageName, @Nullable String proxyAttributionTag,
@AppOpsManager.UidState int uidState, @OpFlags int flags) {
long key = makeKey(uidState, flags);
@@ -835,7 +877,7 @@
OpEventProxyInfo proxyInfo = null;
if (proxyUid != Process.INVALID_UID) {
proxyInfo = mOpEventProxyInfoPool.acquire(proxyUid, proxyPackageName,
- proxyFeatureId);
+ proxyAttributionTag);
}
NoteOpEvent existingEvent = mAccessEvents.get(key);
@@ -856,7 +898,7 @@
rejected(System.currentTimeMillis(), uidState, flags);
mHistoricalRegistry.incrementOpRejected(parent.op, parent.uid, parent.packageName,
- featureId, uidState, flags);
+ tag, uidState, flags);
}
/**
@@ -922,7 +964,7 @@
// startOp events don't support proxy, hence use flags==SELF
mHistoricalRegistry.incrementOpAccessedCount(parent.op, parent.uid, parent.packageName,
- featureId, uidState, OP_FLAG_SELF);
+ tag, uidState, OP_FLAG_SELF);
}
/**
@@ -962,7 +1004,7 @@
mAccessEvents.put(makeKey(event.getUidState(), OP_FLAG_SELF), finishedEvent);
mHistoricalRegistry.increaseOpAccessDuration(parent.op, parent.uid,
- parent.packageName, featureId, event.getUidState(),
+ parent.packageName, tag, event.getUidState(),
AppOpsManager.OP_FLAG_SELF, finishedEvent.getDuration());
mInProgressStartOpEventPool.release(event);
@@ -970,7 +1012,7 @@
if (mInProgressEvents.isEmpty()) {
mInProgressEvents = null;
- // TODO moltmann: Also callback for single feature activity changes
+ // TODO moltmann: Also callback for single attribution tag activity changes
if (triggerCallbackIfNeeded && !parent.isRunning()) {
scheduleOpActiveChangedIfNeededLocked(parent.op, parent.uid,
parent.packageName, false);
@@ -1061,14 +1103,14 @@
}
/**
- * Add all data from the {@code featureToAdd} to this op.
+ * Add all data from the {@code opToAdd} to this op.
*
* <p>If there is an event for the same key in both the later event is retained.
* <p>{@code opToAdd} should not be used after this method is called.
*
* @param opToAdd The op to add
*/
- public void add(@NonNull FeatureOp opToAdd) {
+ public void add(@NonNull AttributedOp opToAdd) {
if (opToAdd.mInProgressEvents != null) {
Slog.w(TAG, "Ignoring " + opToAdd.mInProgressEvents.size() + " running app-ops");
@@ -1112,7 +1154,7 @@
return clone;
}
- @NonNull OpFeatureEntry createFeatureEntryLocked() {
+ @NonNull AttributedOpEntry createAttributedOpEntryLocked() {
LongSparseArray<NoteOpEvent> accessEvents = deepClone(mAccessEvents);
// Add in progress events as access events
@@ -1136,7 +1178,7 @@
LongSparseArray<NoteOpEvent> rejectEvents = deepClone(mRejectEvents);
- return new OpFeatureEntry(parent.op, isRunning(), accessEvents, rejectEvents);
+ return new AttributedOpEntry(parent.op, isRunning(), accessEvents, rejectEvents);
}
}
@@ -1148,8 +1190,8 @@
private @Mode int mode;
- /** featureId -> FeatureOp */
- final ArrayMap<String, FeatureOp> mFeatures = new ArrayMap<>(1);
+ /** attributionTag -> AttributedOp */
+ final ArrayMap<String, AttributedOp> mAttributions = new ArrayMap<>(1);
Op(UidState uidState, String packageName, int op, int uid) {
this.op = op;
@@ -1167,58 +1209,59 @@
return uidState.evalMode(op, mode);
}
- void removeFeaturesWithNoTime() {
- for (int i = mFeatures.size() - 1; i >= 0; i--) {
- if (!mFeatures.valueAt(i).hasAnyTime()) {
- mFeatures.removeAt(i);
+ void removeAttributionsWithNoTime() {
+ for (int i = mAttributions.size() - 1; i >= 0; i--) {
+ if (!mAttributions.valueAt(i).hasAnyTime()) {
+ mAttributions.removeAt(i);
}
}
}
- private @NonNull FeatureOp getOrCreateFeature(@NonNull Op parent,
- @Nullable String featureId) {
- FeatureOp featureOp;
+ private @NonNull AttributedOp getOrCreateAttribution(@NonNull Op parent,
+ @Nullable String attributionTag) {
+ AttributedOp attributedOp;
- featureOp = mFeatures.get(featureId);
- if (featureOp == null) {
- featureOp = new FeatureOp(featureId, parent);
- mFeatures.put(featureId, featureOp);
+ attributedOp = mAttributions.get(attributionTag);
+ if (attributedOp == null) {
+ attributedOp = new AttributedOp(attributionTag, parent);
+ mAttributions.put(attributionTag, attributedOp);
}
- return featureOp;
+ return attributedOp;
}
@NonNull OpEntry createEntryLocked() {
- final int numFeatures = mFeatures.size();
+ final int numAttributions = mAttributions.size();
- final ArrayMap<String, OpFeatureEntry> featureEntries = new ArrayMap<>(numFeatures);
- for (int i = 0; i < numFeatures; i++) {
- featureEntries.put(mFeatures.keyAt(i),
- mFeatures.valueAt(i).createFeatureEntryLocked());
+ final ArrayMap<String, AppOpsManager.AttributedOpEntry> attributionEntries =
+ new ArrayMap<>(numAttributions);
+ for (int i = 0; i < numAttributions; i++) {
+ attributionEntries.put(mAttributions.keyAt(i),
+ mAttributions.valueAt(i).createAttributedOpEntryLocked());
}
- return new OpEntry(op, mode, featureEntries);
+ return new OpEntry(op, mode, attributionEntries);
}
- @NonNull OpEntry createSingleFeatureEntryLocked(@Nullable String featureId) {
- final int numFeatures = mFeatures.size();
+ @NonNull OpEntry createSingleAttributionEntryLocked(@Nullable String attributionTag) {
+ final int numAttributions = mAttributions.size();
- final ArrayMap<String, OpFeatureEntry> featureEntries = new ArrayMap<>(1);
- for (int i = 0; i < numFeatures; i++) {
- if (Objects.equals(mFeatures.keyAt(i), featureId)) {
- featureEntries.put(mFeatures.keyAt(i),
- mFeatures.valueAt(i).createFeatureEntryLocked());
+ final ArrayMap<String, AttributedOpEntry> attributionEntries = new ArrayMap<>(1);
+ for (int i = 0; i < numAttributions; i++) {
+ if (Objects.equals(mAttributions.keyAt(i), attributionTag)) {
+ attributionEntries.put(mAttributions.keyAt(i),
+ mAttributions.valueAt(i).createAttributedOpEntryLocked());
break;
}
}
- return new OpEntry(op, mode, featureEntries);
+ return new OpEntry(op, mode, attributionEntries);
}
boolean isRunning() {
- final int numFeatures = mFeatures.size();
- for (int i = 0; i < numFeatures; i++) {
- if (mFeatures.valueAt(i).isRunning()) {
+ final int numAttributions = mAttributions.size();
+ for (int i = 0; i < numAttributions; i++) {
+ if (mAttributions.valueAt(i).isRunning()) {
return true;
}
}
@@ -1391,10 +1434,35 @@
}
/**
- * Call {@link FeatureOp#onClientDeath featureOp.onClientDeath(clientId)}.
+ * Call {@link AttributedOp#onClientDeath attributedOp.onClientDeath(clientId)}.
*/
- private static void onClientDeath(@NonNull FeatureOp featureOp, @NonNull IBinder clientId) {
- featureOp.onClientDeath(clientId);
+ private static void onClientDeath(@NonNull AttributedOp attributedOp,
+ @NonNull IBinder clientId) {
+ attributedOp.onClientDeath(clientId);
+ }
+
+
+ /**
+ * Loads the OpsValidation file results into a hashmap {@link #mNoteOpCallerStacktraces}
+ * so that we do not log the same operation twice between instances
+ */
+ private void readNoteOpCallerStackTraces() {
+ try {
+ if (!mNoteOpCallerStacktracesFile.exists()) {
+ mNoteOpCallerStacktracesFile.createNewFile();
+ return;
+ }
+
+ try (Scanner read = new Scanner(mNoteOpCallerStacktracesFile)) {
+ read.useDelimiter("\\},");
+ while (read.hasNext()) {
+ String jsonOps = read.next();
+ mNoteOpCallerStacktraces.add(NoteOpTrace.fromJson(jsonOps));
+ }
+ }
+ } catch (Exception e) {
+ Slog.e(TAG, "Cannot parse traces noteOps", e);
+ }
}
public AppOpsService(File storagePath, Handler handler, Context context) {
@@ -1402,6 +1470,13 @@
LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
mFile = new AtomicFile(storagePath, "appops");
+ if (AppOpsManager.NOTE_OP_COLLECTION_ENABLED) {
+ mNoteOpCallerStacktracesFile = new File(SystemServiceManager.ensureSystemDir(),
+ "noteOpStackTraces.json");
+ readNoteOpCallerStackTraces();
+ } else {
+ mNoteOpCallerStacktracesFile = null;
+ }
mHandler = handler;
mConstants = new Constants(mHandler);
readState();
@@ -1445,20 +1520,21 @@
return;
}
- ArrayMap<String, String> dstFeatureIds = new ArrayMap<>();
- ArraySet<String> featureIds = new ArraySet<>();
- featureIds.add(null);
- if (pkg.getFeatures() != null) {
- int numFeatures = pkg.getFeatures().size();
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- ParsedFeature feature = pkg.getFeatures().get(featureNum);
- featureIds.add(feature.id);
+ ArrayMap<String, String> dstAttributionTags = new ArrayMap<>();
+ ArraySet<String> attributionTags = new ArraySet<>();
+ attributionTags.add(null);
+ if (pkg.getAttributions() != null) {
+ int numAttributions = pkg.getAttributions().size();
+ for (int attributionNum = 0; attributionNum < numAttributions;
+ attributionNum++) {
+ ParsedAttribution attribution = pkg.getAttributions().get(attributionNum);
+ attributionTags.add(attribution.tag);
- int numInheritFrom = feature.inheritFrom.size();
+ int numInheritFrom = attribution.inheritFrom.size();
for (int inheritFromNum = 0; inheritFromNum < numInheritFrom;
inheritFromNum++) {
- dstFeatureIds.put(feature.inheritFrom.get(inheritFromNum),
- feature.id);
+ dstAttributionTags.put(attribution.inheritFrom.get(inheritFromNum),
+ attribution.tag);
}
}
}
@@ -1474,25 +1550,32 @@
return;
}
- ops.knownFeatureIds.clear();
+ // Reset cached package properties to re-initialize when needed
+ ops.bypass = null;
+ ops.knownAttributionTags.clear();
+
+ // Merge data collected for removed attributions into their successor
+ // attributions
int numOps = ops.size();
for (int opNum = 0; opNum < numOps; opNum++) {
Op op = ops.valueAt(opNum);
- int numFeatures = op.mFeatures.size();
- for (int featureNum = numFeatures - 1; featureNum >= 0; featureNum--) {
- String featureId = op.mFeatures.keyAt(featureNum);
+ int numAttributions = op.mAttributions.size();
+ for (int attributionNum = numAttributions - 1; attributionNum >= 0;
+ attributionNum--) {
+ String attributionTag = op.mAttributions.keyAt(attributionNum);
- if (featureIds.contains(featureId)) {
- // feature still exist after upgrade
+ if (attributionTags.contains(attributionTag)) {
+ // attribution still exist after upgrade
continue;
}
- String newFeatureId = dstFeatureIds.get(featureId);
+ String newAttributionTag = dstAttributionTags.get(attributionTag);
- FeatureOp newFeatureOp = op.getOrCreateFeature(op, newFeatureId);
- newFeatureOp.add(op.mFeatures.valueAt(featureNum));
- op.mFeatures.removeAt(featureNum);
+ AttributedOp newAttributedOp = op.getOrCreateAttribution(op,
+ newAttributionTag);
+ newAttributedOp.add(op.mAttributions.valueAt(attributionNum));
+ op.mAttributions.removeAt(attributionNum);
scheduleFastWriteLocked();
}
@@ -1600,17 +1683,14 @@
}
}, packageAddedFilter);
- List<String> packageNames = getPackageNamesForSampling();
- synchronized (this) {
- resamplePackageAndAppOpLocked(packageNames);
- }
-
- AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
+ mHandler.postDelayed(new Runnable() {
@Override
public void run() {
+ List<String> packageNames = getPackageNamesForSampling();
+ resamplePackageAndAppOpLocked(packageNames);
initializeRarelyUsedPackagesList(new ArraySet<>(packageNames));
}
- });
+ }, RARELY_USED_PACKAGES_INITIALIZATION_DELAY_MILLIS);
PackageManagerInternal packageManagerInternal = LocalServices.getService(
PackageManagerInternal.class);
@@ -1692,12 +1772,13 @@
for (int opNum = 0; opNum < numOps; opNum++) {
final Op op = ops.valueAt(opNum);
- final int numFeatures = op.mFeatures.size();
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- FeatureOp featureOp = op.mFeatures.valueAt(featureNum);
+ final int numAttributions = op.mAttributions.size();
+ for (int attributionNum = 0; attributionNum < numAttributions;
+ attributionNum++) {
+ AttributedOp attributedOp = op.mAttributions.valueAt(attributionNum);
- while (featureOp.mInProgressEvents != null) {
- featureOp.finished(featureOp.mInProgressEvents.keyAt(0));
+ while (attributedOp.mInProgressEvents != null) {
+ attributedOp.finished(attributedOp.mInProgressEvents.keyAt(0));
}
}
}
@@ -1777,11 +1858,13 @@
for (int opNum = 0; opNum < numOps; opNum++) {
Op op = ops.valueAt(opNum);
- int numFeatures = op.mFeatures.size();
- for (int featureNum = 0; featureNum < numFeatures; featureNum++) {
- FeatureOp featureOp = op.mFeatures.valueAt(featureNum);
+ int numAttributions = op.mAttributions.size();
+ for (int attributionNum = 0; attributionNum < numAttributions;
+ attributionNum++) {
+ AttributedOp attributedOp = op.mAttributions.valueAt(
+ attributionNum);
- featureOp.onUidStateChanged(newState);
+ attributedOp.onUidStateChanged(newState);
}
}
}
@@ -1802,6 +1885,9 @@
if (doWrite) {
writeState();
}
+ if (AppOpsManager.NOTE_OP_COLLECTION_ENABLED && mWriteNoteOpsScheduled) {
+ writeNoteOps();
+ }
}
private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
@@ -1905,8 +1991,7 @@
return Collections.emptyList();
}
synchronized (this) {
- Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, null, false /* isPrivileged */,
- false /* edit */);
+ Ops pkgOps = getOpsLocked(uid, resolvedPackageName, null, null, false /* edit */);
if (pkgOps == null) {
return null;
}
@@ -1925,9 +2010,9 @@
/**
* Verify that historical appop request arguments are valid.
*/
- private void ensureHistoricalOpRequestIsValid(int uid, String packageName, String featureId,
- List<String> opNames, int filter, long beginTimeMillis, long endTimeMillis,
- int flags) {
+ private void ensureHistoricalOpRequestIsValid(int uid, String packageName,
+ String attributionTag, List<String> opNames, int filter, long beginTimeMillis,
+ long endTimeMillis, int flags) {
if ((filter & FILTER_BY_UID) != 0) {
Preconditions.checkArgument(uid != Process.INVALID_UID);
} else {
@@ -1940,8 +2025,8 @@
Preconditions.checkArgument(packageName == null);
}
- if ((filter & FILTER_BY_FEATURE_ID) == 0) {
- Preconditions.checkArgument(featureId == null);
+ if ((filter & FILTER_BY_ATTRIBUTION_TAG) == 0) {
+ Preconditions.checkArgument(attributionTag == null);
}
if ((filter & FILTER_BY_OP_NAMES) != 0) {
@@ -1951,17 +2036,18 @@
}
Preconditions.checkFlagsArgument(filter,
- FILTER_BY_UID | FILTER_BY_PACKAGE_NAME | FILTER_BY_FEATURE_ID | FILTER_BY_OP_NAMES);
+ FILTER_BY_UID | FILTER_BY_PACKAGE_NAME | FILTER_BY_ATTRIBUTION_TAG
+ | FILTER_BY_OP_NAMES);
Preconditions.checkArgumentNonnegative(beginTimeMillis);
Preconditions.checkArgument(endTimeMillis > beginTimeMillis);
Preconditions.checkFlagsArgument(flags, OP_FLAGS_ALL);
}
@Override
- public void getHistoricalOps(int uid, String packageName, String featureId,
+ public void getHistoricalOps(int uid, String packageName, String attributionTag,
List<String> opNames, int filter, long beginTimeMillis, long endTimeMillis,
int flags, RemoteCallback callback) {
- ensureHistoricalOpRequestIsValid(uid, packageName, featureId, opNames, filter,
+ ensureHistoricalOpRequestIsValid(uid, packageName, attributionTag, opNames, filter,
beginTimeMillis, endTimeMillis, flags);
Objects.requireNonNull(callback, "callback cannot be null");
@@ -1982,15 +2068,15 @@
// Must not hold the appops lock
mHandler.post(PooledLambda.obtainRunnable(HistoricalRegistry::getHistoricalOps,
- mHistoricalRegistry, uid, packageName, featureId, opNamesArray, filter,
+ mHistoricalRegistry, uid, packageName, attributionTag, opNamesArray, filter,
beginTimeMillis, endTimeMillis, flags, callback).recycleOnUse());
}
@Override
- public void getHistoricalOpsFromDiskRaw(int uid, String packageName, String featureId,
+ public void getHistoricalOpsFromDiskRaw(int uid, String packageName, String attributionTag,
List<String> opNames, int filter, long beginTimeMillis, long endTimeMillis,
int flags, RemoteCallback callback) {
- ensureHistoricalOpRequestIsValid(uid, packageName, featureId, opNames, filter,
+ ensureHistoricalOpRequestIsValid(uid, packageName, attributionTag, opNames, filter,
beginTimeMillis, endTimeMillis, flags);
Objects.requireNonNull(callback, "callback cannot be null");
@@ -2002,7 +2088,7 @@
// Must not hold the appops lock
mHandler.post(PooledLambda.obtainRunnable(HistoricalRegistry::getHistoricalOpsFromDiskRaw,
- mHistoricalRegistry, uid, packageName, featureId, opNamesArray,
+ mHistoricalRegistry, uid, packageName, attributionTag, opNamesArray,
filter, beginTimeMillis, endTimeMillis, flags, callback).recycleOnUse());
}
@@ -2036,11 +2122,10 @@
}
private void pruneOpLocked(Op op, int uid, String packageName) {
- op.removeFeaturesWithNoTime();
+ op.removeAttributionsWithNoTime();
- if (op.mFeatures.size() == 0) {
- Ops ops = getOpsRawLocked(uid, packageName, null, false /* isPrivileged */,
- false /* edit */);
+ if (op.mAttributions.isEmpty()) {
+ Ops ops = getOpsLocked(uid, packageName, null, null, false /* edit */);
if (ops != null) {
ops.remove(op.op);
if (ops.size() <= 0) {
@@ -2342,9 +2427,9 @@
ArraySet<ModeCallback> repCbs = null;
code = AppOpsManager.opToSwitch(code);
- boolean isPrivileged;
+ RestrictionBypass bypass;
try {
- isPrivileged = verifyAndGetIsPrivileged(uid, packageName, null);
+ bypass = verifyAndGetBypass(uid, packageName, null);
} catch (SecurityException e) {
Slog.e(TAG, "Cannot setMode", e);
return;
@@ -2352,7 +2437,7 @@
synchronized (this) {
UidState uidState = getUidStateLocked(uid, false);
- Op op = getOpLocked(code, uid, packageName, null, isPrivileged, true);
+ Op op = getOpLocked(code, uid, packageName, null, bypass, true);
if (op != null) {
if (op.mode != mode) {
op.mode = mode;
@@ -2558,8 +2643,8 @@
callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
mPackageModeWatchers.get(packageName));
- curOp.removeFeaturesWithNoTime();
- if (curOp.mFeatures.size() == 0) {
+ curOp.removeAttributionsWithNoTime();
+ if (curOp.mAttributions.isEmpty()) {
pkgOps.removeAt(j);
}
}
@@ -2626,10 +2711,8 @@
synchronized (this) {
int switchOp = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
- // See CALL_BACK_ON_CHANGED_LISTENER_WITH_SWITCHED_OP_CHANGE
int notifiedOps;
- if (Compatibility.isChangeEnabled(
- CALL_BACK_ON_CHANGED_LISTENER_WITH_SWITCHED_OP_CHANGE)) {
+ if ((flags & CALL_BACK_ON_SWITCHED_OP) == 0) {
if (op == OP_NONE) {
notifiedOps = ALL_OPS;
} else {
@@ -2750,10 +2833,9 @@
*/
private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
boolean raw) {
- boolean isPrivileged;
-
+ RestrictionBypass bypass;
try {
- isPrivileged = verifyAndGetIsPrivileged(uid, packageName, null);
+ bypass = verifyAndGetBypass(uid, packageName, null);
} catch (SecurityException e) {
Slog.e(TAG, "checkOperation", e);
return AppOpsManager.opToDefaultMode(code);
@@ -2763,7 +2845,7 @@
return AppOpsManager.MODE_IGNORED;
}
synchronized (this) {
- if (isOpRestrictedLocked(uid, code, packageName, null, isPrivileged)) {
+ if (isOpRestrictedLocked(uid, code, packageName, bypass)) {
return AppOpsManager.MODE_IGNORED;
}
code = AppOpsManager.opToSwitch(code);
@@ -2773,7 +2855,7 @@
final int rawMode = uidState.opModes.get(code);
return raw ? rawMode : uidState.evalMode(code, rawMode);
}
- Op op = getOpLocked(code, uid, packageName, null, false, false);
+ Op op = getOpLocked(code, uid, packageName, null, bypass, false);
if (op == null) {
return AppOpsManager.opToDefaultMode(code);
}
@@ -2836,7 +2918,7 @@
public int checkPackage(int uid, String packageName) {
Objects.requireNonNull(packageName);
try {
- verifyAndGetIsPrivileged(uid, packageName, null);
+ verifyAndGetBypass(uid, packageName, null);
return AppOpsManager.MODE_ALLOWED;
} catch (SecurityException ignored) {
@@ -2846,8 +2928,8 @@
@Override
public int noteProxyOperation(int code, int proxiedUid, String proxiedPackageName,
- String proxiedFeatureId, int proxyUid, String proxyPackageName,
- String proxyFeatureId, boolean shouldCollectAsyncNotedOp, String message) {
+ String proxiedAttributionTag, int proxyUid, String proxyPackageName,
+ String proxyAttributionTag, boolean shouldCollectAsyncNotedOp, String message) {
verifyIncomingUid(proxyUid);
verifyIncomingOp(code);
@@ -2863,7 +2945,7 @@
final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
: AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
final int proxyMode = noteOperationUnchecked(code, proxyUid, resolveProxyPackageName,
- proxyFeatureId, Process.INVALID_UID, null, null, proxyFlags,
+ proxyAttributionTag, Process.INVALID_UID, null, null, proxyFlags,
!isProxyTrusted, "proxy " + message);
if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
return proxyMode;
@@ -2876,27 +2958,27 @@
final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
: AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
- proxiedFeatureId, proxyUid, resolveProxyPackageName, proxyFeatureId,
+ proxiedAttributionTag, proxyUid, resolveProxyPackageName, proxyAttributionTag,
proxiedFlags, shouldCollectAsyncNotedOp, message);
}
@Override
- public int noteOperation(int code, int uid, String packageName, String featureId,
+ public int noteOperation(int code, int uid, String packageName, String attributionTag,
boolean shouldCollectAsyncNotedOp, String message) {
final CheckOpsDelegate delegate;
synchronized (this) {
delegate = mCheckOpsDelegate;
}
if (delegate == null) {
- return noteOperationImpl(code, uid, packageName, featureId, shouldCollectAsyncNotedOp,
- message);
+ return noteOperationImpl(code, uid, packageName, attributionTag,
+ shouldCollectAsyncNotedOp, message);
}
- return delegate.noteOperation(code, uid, packageName, featureId, shouldCollectAsyncNotedOp,
- message, AppOpsService.this::noteOperationImpl);
+ return delegate.noteOperation(code, uid, packageName, attributionTag,
+ shouldCollectAsyncNotedOp, message, AppOpsService.this::noteOperationImpl);
}
private int noteOperationImpl(int code, int uid, @Nullable String packageName,
- @Nullable String featureId, boolean shouldCollectAsyncNotedOp,
+ @Nullable String attributionTag, boolean shouldCollectAsyncNotedOp,
@Nullable String message) {
verifyIncomingUid(uid);
verifyIncomingOp(code);
@@ -2904,25 +2986,25 @@
if (resolvedPackageName == null) {
return AppOpsManager.MODE_IGNORED;
}
- return noteOperationUnchecked(code, uid, resolvedPackageName, featureId,
+ return noteOperationUnchecked(code, uid, resolvedPackageName, attributionTag,
Process.INVALID_UID, null, null, AppOpsManager.OP_FLAG_SELF,
shouldCollectAsyncNotedOp, message);
}
private int noteOperationUnchecked(int code, int uid, @NonNull String packageName,
- @Nullable String featureId, int proxyUid, String proxyPackageName,
- @Nullable String proxyFeatureId, @OpFlags int flags, boolean shouldCollectAsyncNotedOp,
- @Nullable String message) {
- boolean isPrivileged;
+ @Nullable String attributionTag, int proxyUid, String proxyPackageName,
+ @Nullable String proxyAttributionTag, @OpFlags int flags,
+ boolean shouldCollectAsyncNotedOp, @Nullable String message) {
+ RestrictionBypass bypass;
try {
- isPrivileged = verifyAndGetIsPrivileged(uid, packageName, featureId);
+ bypass = verifyAndGetBypass(uid, packageName, attributionTag);
} catch (SecurityException e) {
Slog.e(TAG, "noteOperation", e);
return AppOpsManager.MODE_ERRORED;
}
synchronized (this) {
- final Ops ops = getOpsRawLocked(uid, packageName, featureId, isPrivileged,
+ final Ops ops = getOpsLocked(uid, packageName, attributionTag, bypass,
true /* edit */);
if (ops == null) {
scheduleOpNotedIfNeededLocked(code, uid, packageName,
@@ -2932,17 +3014,17 @@
return AppOpsManager.MODE_ERRORED;
}
final Op op = getOpLocked(ops, code, uid, true);
- final FeatureOp featureOp = op.getOrCreateFeature(op, featureId);
- if (isOpRestrictedLocked(uid, code, packageName, featureId, isPrivileged)) {
+ final AttributedOp attributedOp = op.getOrCreateAttribution(op, attributionTag);
+ if (isOpRestrictedLocked(uid, code, packageName, bypass)) {
scheduleOpNotedIfNeededLocked(code, uid, packageName,
AppOpsManager.MODE_IGNORED);
return AppOpsManager.MODE_IGNORED;
}
final UidState uidState = ops.uidState;
- if (featureOp.isRunning()) {
+ if (attributedOp.isRunning()) {
Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName + " code "
+ code + " startTime of in progress event="
- + featureOp.mInProgressEvents.valueAt(0).getStartTime());
+ + attributedOp.mInProgressEvents.valueAt(0).getStartTime());
}
final int switchCode = AppOpsManager.opToSwitch(code);
@@ -2954,7 +3036,7 @@
if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
+ switchCode + " (" + code + ") uid " + uid + " package "
+ packageName);
- featureOp.rejected(uidState.state, flags);
+ attributedOp.rejected(uidState.state, flags);
scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
return uidMode;
}
@@ -2966,26 +3048,31 @@
if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
+ switchCode + " (" + code + ") uid " + uid + " package "
+ packageName);
- featureOp.rejected(uidState.state, flags);
+ attributedOp.rejected(uidState.state, flags);
scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
return mode;
}
}
- if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
- + " package " + packageName + (featureId == null ? "" : "." + featureId));
- featureOp.accessed(proxyUid, proxyPackageName, proxyFeatureId, uidState.state, flags);
+ if (DEBUG) {
+ Slog.d(TAG,
+ "noteOperation: allowing code " + code + " uid " + uid + " package "
+ + packageName + (attributionTag == null ? ""
+ : "." + attributionTag));
+ }
+ attributedOp.accessed(proxyUid, proxyPackageName, proxyAttributionTag, uidState.state,
+ flags);
scheduleOpNotedIfNeededLocked(code, uid, packageName,
AppOpsManager.MODE_ALLOWED);
if (shouldCollectAsyncNotedOp) {
- collectAsyncNotedOp(uid, packageName, code, featureId, message);
+ collectAsyncNotedOp(uid, packageName, code, attributionTag, message);
}
return AppOpsManager.MODE_ALLOWED;
}
}
- // TODO moltmann: Allow watching for feature ops
+ // TODO moltmann: Allow watching for attribution ops
@Override
public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
int watchedUid = -1;
@@ -3083,11 +3170,11 @@
* @param uid The uid the op was noted for
* @param packageName The package the op was noted for
* @param opCode The code of the op noted
- * @param featureId The id of the feature to op was noted for
+ * @param attributionTag attribution tag the op was noted for
* @param message The message for the op noting
*/
private void collectAsyncNotedOp(int uid, @NonNull String packageName, int opCode,
- @Nullable String featureId, @NonNull String message) {
+ @Nullable String attributionTag, @NonNull String message) {
Objects.requireNonNull(message);
int callingUid = Binder.getCallingUid();
@@ -3099,10 +3186,10 @@
RemoteCallbackList<IAppOpsAsyncNotedCallback> callbacks = mAsyncOpWatchers.get(key);
AsyncNotedAppOp asyncNotedOp = new AsyncNotedAppOp(opCode, callingUid,
- featureId, message, System.currentTimeMillis());
+ attributionTag, message, System.currentTimeMillis());
final boolean[] wasNoteForwarded = {false};
- reportRuntimeAppOpAccessMessageAsyncLocked(uid, packageName, opCode, featureId,
+ reportRuntimeAppOpAccessMessageAsyncLocked(uid, packageName, opCode, attributionTag,
message);
if (callbacks != null) {
@@ -3113,7 +3200,7 @@
} catch (RemoteException e) {
Slog.e(TAG,
"Could not forward noteOp of " + opCode + " to " + packageName
- + "/" + uid + "(" + featureId + ")", e);
+ + "/" + uid + "(" + attributionTag + ")", e);
}
});
}
@@ -3157,7 +3244,7 @@
int uid = Binder.getCallingUid();
Pair<String, Integer> key = getAsyncNotedOpsKey(packageName, uid);
- verifyAndGetIsPrivileged(uid, packageName, null);
+ verifyAndGetBypass(uid, packageName, null);
synchronized (this) {
RemoteCallbackList<IAppOpsAsyncNotedCallback> callbacks = mAsyncOpWatchers.get(key);
@@ -3187,7 +3274,7 @@
int uid = Binder.getCallingUid();
Pair<String, Integer> key = getAsyncNotedOpsKey(packageName, uid);
- verifyAndGetIsPrivileged(uid, packageName, null);
+ verifyAndGetBypass(uid, packageName, null);
synchronized (this) {
RemoteCallbackList<IAppOpsAsyncNotedCallback> callbacks = mAsyncOpWatchers.get(key);
@@ -3206,7 +3293,7 @@
int uid = Binder.getCallingUid();
- verifyAndGetIsPrivileged(uid, packageName, null);
+ verifyAndGetBypass(uid, packageName, null);
synchronized (this) {
return mUnforwardedAsyncNotedOps.remove(getAsyncNotedOpsKey(packageName, uid));
@@ -3215,7 +3302,7 @@
@Override
public int startOperation(IBinder clientId, int code, int uid, String packageName,
- String featureId, boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp,
+ String attributionTag, boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp,
String message) {
verifyIncomingUid(uid);
verifyIncomingOp(code);
@@ -3224,16 +3311,16 @@
return AppOpsManager.MODE_IGNORED;
}
- boolean isPrivileged;
+ RestrictionBypass bypass;
try {
- isPrivileged = verifyAndGetIsPrivileged(uid, packageName, featureId);
+ bypass = verifyAndGetBypass(uid, packageName, attributionTag);
} catch (SecurityException e) {
Slog.e(TAG, "startOperation", e);
return AppOpsManager.MODE_ERRORED;
}
synchronized (this) {
- final Ops ops = getOpsRawLocked(uid, resolvedPackageName, featureId, isPrivileged,
+ final Ops ops = getOpsLocked(uid, resolvedPackageName, attributionTag, bypass,
true /* edit */);
if (ops == null) {
if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
@@ -3241,10 +3328,10 @@
return AppOpsManager.MODE_ERRORED;
}
final Op op = getOpLocked(ops, code, uid, true);
- if (isOpRestrictedLocked(uid, code, resolvedPackageName, featureId, isPrivileged)) {
+ if (isOpRestrictedLocked(uid, code, resolvedPackageName, bypass)) {
return AppOpsManager.MODE_IGNORED;
}
- final FeatureOp featureOp = op.getOrCreateFeature(op, featureId);
+ final AttributedOp attributedOp = op.getOrCreateAttribution(op, attributionTag);
final int switchCode = AppOpsManager.opToSwitch(code);
final UidState uidState = ops.uidState;
// If there is a non-default per UID policy (we set UID op mode only if
@@ -3257,7 +3344,7 @@
if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
+ switchCode + " (" + code + ") uid " + uid + " package "
+ resolvedPackageName);
- featureOp.rejected(uidState.state, AppOpsManager.OP_FLAG_SELF);
+ attributedOp.rejected(uidState.state, AppOpsManager.OP_FLAG_SELF);
return uidMode;
}
} else {
@@ -3269,21 +3356,21 @@
if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
+ switchCode + " (" + code + ") uid " + uid + " package "
+ resolvedPackageName);
- featureOp.rejected(uidState.state, AppOpsManager.OP_FLAG_SELF);
+ attributedOp.rejected(uidState.state, AppOpsManager.OP_FLAG_SELF);
return mode;
}
}
if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
+ " package " + resolvedPackageName);
try {
- featureOp.started(clientId, uidState.state);
+ attributedOp.started(clientId, uidState.state);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
if (shouldCollectAsyncNotedOp) {
- collectAsyncNotedOp(uid, packageName, code, featureId, message);
+ collectAsyncNotedOp(uid, packageName, code, attributionTag, message);
}
return AppOpsManager.MODE_ALLOWED;
@@ -3291,7 +3378,7 @@
@Override
public void finishOperation(IBinder clientId, int code, int uid, String packageName,
- String featureId) {
+ String attributionTag) {
verifyIncomingUid(uid);
verifyIncomingOp(code);
String resolvedPackageName = resolvePackageName(uid, packageName);
@@ -3299,29 +3386,33 @@
return;
}
- boolean isPrivileged;
+ RestrictionBypass bypass;
try {
- isPrivileged = verifyAndGetIsPrivileged(uid, packageName, featureId);
+ bypass = verifyAndGetBypass(uid, packageName, attributionTag);
} catch (SecurityException e) {
Slog.e(TAG, "Cannot finishOperation", e);
return;
}
synchronized (this) {
- Op op = getOpLocked(code, uid, resolvedPackageName, featureId, isPrivileged, true);
+ Op op = getOpLocked(code, uid, resolvedPackageName, attributionTag, bypass, true);
if (op == null) {
+ Slog.e(TAG, "Operation not found: uid=" + uid + " pkg=" + packageName + "("
+ + attributionTag + ") op=" + AppOpsManager.opToName(code));
return;
}
- final FeatureOp featureOp = op.mFeatures.get(featureId);
- if (featureOp == null) {
+ final AttributedOp attributedOp = op.mAttributions.get(attributionTag);
+ if (attributedOp == null) {
+ Slog.e(TAG, "Attribution not found: uid=" + uid + " pkg=" + packageName + "("
+ + attributionTag + ") op=" + AppOpsManager.opToName(code));
return;
}
- try {
- featureOp.finished(clientId);
- } catch (IllegalStateException e) {
- Slog.e(TAG, "Operation not started: uid=" + uid + " pkg="
- + packageName + " op=" + AppOpsManager.opToName(code), e);
+ if (attributedOp.isRunning()) {
+ attributedOp.finished(clientId);
+ } else {
+ Slog.e(TAG, "Operation not started: uid=" + uid + " pkg=" + packageName + "("
+ + attributionTag + ") op=" + AppOpsManager.opToName(code));
}
}
}
@@ -3569,50 +3660,66 @@
}
/**
- * Verify that package belongs to uid and return whether the package is privileged.
+ * Create a restriction description matching the properties of the package.
+ *
+ * @param context A context to use
+ * @param pkg The package to create the restriction description for
+ *
+ * @return The restriction matching the package
+ */
+ private RestrictionBypass getBypassforPackage(@NonNull AndroidPackage pkg) {
+ return new RestrictionBypass(pkg.isPrivileged(), mContext.checkPermission(
+ android.Manifest.permission.EXEMPT_FROM_AUDIO_RECORD_RESTRICTIONS, -1, pkg.getUid())
+ == PackageManager.PERMISSION_GRANTED);
+ }
+
+ /**
+ * Verify that package belongs to uid and return the {@link RestrictionBypass bypass
+ * description} for the package.
*
* @param uid The uid the package belongs to
* @param packageName The package the might belong to the uid
- * @param featureId The feature in the package or {@code null} if no need to verify
+ * @param attributionTag attribution tag or {@code null} if no need to verify
*
* @return {@code true} iff the package is privileged
*/
- private boolean verifyAndGetIsPrivileged(int uid, String packageName,
- @Nullable String featureId) {
+ private @Nullable RestrictionBypass verifyAndGetBypass(int uid, String packageName,
+ @Nullable String attributionTag) {
if (uid == Process.ROOT_UID) {
// For backwards compatibility, don't check package name for root UID.
- return false;
+ return null;
}
- // Do not check if uid/packageName/featureId is already known
+ // Do not check if uid/packageName/attributionTag is already known
synchronized (this) {
UidState uidState = mUidStates.get(uid);
if (uidState != null && uidState.pkgOps != null) {
Ops ops = uidState.pkgOps.get(packageName);
- if (ops != null && (featureId == null || ops.knownFeatureIds.contains(featureId))) {
- return ops.isPrivileged;
+ if (ops != null && (attributionTag == null || ops.knownAttributionTags.contains(
+ attributionTag)) && ops.bypass != null) {
+ return ops.bypass;
}
}
}
- boolean isPrivileged = false;
+ RestrictionBypass bypass = null;
final long ident = Binder.clearCallingIdentity();
try {
int pkgUid;
AndroidPackage pkg = LocalServices.getService(PackageManagerInternal.class).getPackage(
packageName);
- boolean isFeatureIdValid = false;
+ boolean isAttributionTagValid = false;
if (pkg != null) {
- if (featureId == null) {
- isFeatureIdValid = true;
+ if (attributionTag == null) {
+ isAttributionTagValid = true;
} else {
- if (pkg.getFeatures() != null) {
- int numFeatures = pkg.getFeatures().size();
- for (int i = 0; i < numFeatures; i++) {
- if (pkg.getFeatures().get(i).id.equals(featureId)) {
- isFeatureIdValid = true;
+ if (pkg.getAttributions() != null) {
+ int numAttributions = pkg.getAttributions().size();
+ for (int i = 0; i < numAttributions; i++) {
+ if (pkg.getAttributions().get(i).tag.equals(attributionTag)) {
+ isAttributionTagValid = true;
}
}
}
@@ -3620,14 +3727,14 @@
pkgUid = UserHandle.getUid(
UserHandle.getUserId(uid), UserHandle.getAppId(pkg.getUid()));
- isPrivileged = pkg.isPrivileged();
+ bypass = getBypassforPackage(pkg);
} else {
- // Allow any feature id for resolvable uids
- isFeatureIdValid = true;
+ // Allow any attribution tag for resolvable uids
+ isAttributionTagValid = true;
pkgUid = resolveUid(packageName);
if (pkgUid >= 0) {
- isPrivileged = false;
+ bypass = RestrictionBypass.UNRESTRICTED;
}
}
if (pkgUid != uid) {
@@ -3635,16 +3742,16 @@
+ " but it is really " + pkgUid);
}
- if (!isFeatureIdValid) {
+ if (!isAttributionTagValid) {
// TODO moltmann: Switch from logging to enforcement
- Slog.e(TAG, "featureId " + featureId + " not declared in manifest of "
+ Slog.e(TAG, "attributionTag " + attributionTag + " not declared in manifest of "
+ packageName);
}
} finally {
Binder.restoreCallingIdentity(ident);
}
- return isPrivileged;
+ return bypass;
}
/**
@@ -3652,14 +3759,14 @@
*
* @param uid The uid the package belongs to
* @param packageName The name of the package
- * @param featureId The feature in the package
- * @param isPrivileged If the package is privilidged (ignored if {@code edit} is false)
+ * @param attributionTag attribution tag
+ * @param bypass When to bypass certain op restrictions (can be null if edit == false)
* @param edit If an ops does not exist, create the ops?
- * @return
+ * @return The ops
*/
- private Ops getOpsRawLocked(int uid, String packageName, @Nullable String featureId,
- boolean isPrivileged, boolean edit) {
+ private Ops getOpsLocked(int uid, String packageName, @Nullable String attributionTag,
+ @Nullable RestrictionBypass bypass, boolean edit) {
UidState uidState = getUidStateLocked(uid, edit);
if (uidState == null) {
return null;
@@ -3677,53 +3784,18 @@
if (!edit) {
return null;
}
- ops = new Ops(packageName, uidState, isPrivileged);
- uidState.pkgOps.put(packageName, ops);
- }
- if (edit && featureId != null) {
- ops.knownFeatureIds.add(featureId);
- }
- return ops;
- }
-
- /**
- * Get the state of all ops for a package.
- *
- * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
- *
- * @param uid The uid the of the package
- * @param packageName The package name for which to get the state for
- * @param featureId The feature in the package
- * @param edit Iff {@code true} create the {@link Ops} object if not yet created
- * @param isPrivileged Whether the package is privileged or not
- *
- * @return The {@link Ops state} of all ops for the package
- */
- private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
- @Nullable String featureId, boolean edit, boolean isPrivileged) {
- UidState uidState = getUidStateLocked(uid, edit);
- if (uidState == null) {
- return null;
- }
-
- if (uidState.pkgOps == null) {
- if (!edit) {
- return null;
- }
- uidState.pkgOps = new ArrayMap<>();
- }
-
- Ops ops = uidState.pkgOps.get(packageName);
- if (ops == null) {
- if (!edit) {
- return null;
- }
- ops = new Ops(packageName, uidState, isPrivileged);
+ ops = new Ops(packageName, uidState);
uidState.pkgOps.put(packageName, ops);
}
- if (edit && featureId != null) {
- ops.knownFeatureIds.add(featureId);
+ if (edit) {
+ if (bypass != null) {
+ ops.bypass = bypass;
+ }
+
+ if (attributionTag != null) {
+ ops.knownAttributionTags.add(attributionTag);
+ }
}
return ops;
@@ -3751,16 +3823,15 @@
* @param code The code of the op
* @param uid The uid the of the package
* @param packageName The package name for which to get the state for
- * @param featureId The feature in the package
- * @param isPrivileged Whether the package is privileged or not (only used if {@code edit
- * == true})
+ * @param attributionTag The attribution tag
+ * @param bypass When to bypass certain op restrictions (can be null if edit == false)
* @param edit Iff {@code true} create the {@link Op} object if not yet created
*
* @return The {@link Op state} of the op
*/
private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName,
- @Nullable String featureId, boolean isPrivileged, boolean edit) {
- Ops ops = getOpsRawNoVerifyLocked(uid, packageName, featureId, edit, isPrivileged);
+ @Nullable String attributionTag, @Nullable RestrictionBypass bypass, boolean edit) {
+ Ops ops = getOpsLocked(uid, packageName, attributionTag, bypass, edit);
if (ops == null) {
return null;
}
@@ -3791,7 +3862,7 @@
}
private boolean isOpRestrictedLocked(int uid, int code, String packageName,
- @Nullable String featureId, boolean isPrivileged) {
+ @Nullable RestrictionBypass appBypass) {
int userHandle = UserHandle.getUserId(uid);
final int restrictionSetCount = mOpUserRestrictions.size();
@@ -3800,12 +3871,15 @@
// package is exempt from the restriction.
ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
if (restrictionState.hasRestriction(code, packageName, userHandle)) {
- if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
+ RestrictionBypass opBypass = opAllowSystemBypassRestriction(code);
+ if (opBypass != null) {
// If we are the system, bypass user restrictions for certain codes
synchronized (this) {
- Ops ops = getOpsRawLocked(uid, packageName, featureId, isPrivileged,
- true /* edit */);
- if ((ops != null) && ops.isPrivileged) {
+ if (opBypass.isPrivileged && appBypass != null && appBypass.isPrivileged) {
+ return false;
+ }
+ if (opBypass.isRecordAudioRestrictionExcept && appBypass != null
+ && appBypass.isRecordAudioRestrictionExcept) {
return false;
}
}
@@ -3995,28 +4069,6 @@
throws NumberFormatException, XmlPullParserException, IOException {
int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
final UidState uidState = getUidStateLocked(uid, true);
- String isPrivilegedString = parser.getAttributeValue(null, "p");
- boolean isPrivileged = false;
- if (isPrivilegedString == null) {
- try {
- IPackageManager packageManager = ActivityThread.getPackageManager();
- if (packageManager != null) {
- ApplicationInfo appInfo = ActivityThread.getPackageManager()
- .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
- if (appInfo != null) {
- isPrivileged = (appInfo.privateFlags
- & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
- }
- } else {
- // Could not load data, don't add to cache so it will be loaded later.
- return;
- }
- } catch (RemoteException e) {
- Slog.w(TAG, "Could not contact PackageManager", e);
- }
- } else {
- isPrivileged = Boolean.parseBoolean(isPrivilegedString);
- }
int outerDepth = parser.getDepth();
int type;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
@@ -4026,7 +4078,7 @@
}
String tagName = parser.getName();
if (tagName.equals("op")) {
- readOp(parser, uidState, pkgName, isPrivileged);
+ readOp(parser, uidState, pkgName);
} else {
Slog.w(TAG, "Unknown element under <pkg>: "
+ parser.getName());
@@ -4036,9 +4088,9 @@
uidState.evalForegroundOps(mOpModeWatchers);
}
- private void readFeatureOp(XmlPullParser parser, @NonNull Op parent,
- @Nullable String feature) throws NumberFormatException, IOException {
- final FeatureOp featureOp = parent.getOrCreateFeature(parent, feature);
+ private void readAttributionOp(XmlPullParser parser, @NonNull Op parent,
+ @Nullable String attribution) throws NumberFormatException, IOException {
+ final AttributedOp attributedOp = parent.getOrCreateAttribution(parent, attribution);
final long key = XmlUtils.readLongAttribute(parser, "n");
final int uidState = extractUidStateFromKey(key);
@@ -4049,19 +4101,19 @@
final long accessDuration = XmlUtils.readLongAttribute(parser, "d", -1);
final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", Process.INVALID_UID);
- final String proxyFeatureId = XmlUtils.readStringAttribute(parser, "pc");
+ final String proxyAttributionTag = XmlUtils.readStringAttribute(parser, "pc");
if (accessTime > 0) {
- featureOp.accessed(accessTime, accessDuration, proxyUid, proxyPkg, proxyFeatureId,
- uidState, opFlags);
+ attributedOp.accessed(accessTime, accessDuration, proxyUid, proxyPkg,
+ proxyAttributionTag, uidState, opFlags);
}
if (rejectTime > 0) {
- featureOp.rejected(rejectTime, uidState, opFlags);
+ attributedOp.rejected(rejectTime, uidState, opFlags);
}
}
- private void readOp(XmlPullParser parser, @NonNull UidState uidState,
- @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
+ private void readOp(XmlPullParser parser, @NonNull UidState uidState, @NonNull String pkgName)
+ throws NumberFormatException,
XmlPullParserException, IOException {
int opCode = Integer.parseInt(parser.getAttributeValue(null, "n"));
if (isIgnoredAppOp(opCode)) {
@@ -4082,7 +4134,7 @@
}
String tagName = parser.getName();
if (tagName.equals("st")) {
- readFeatureOp(parser, op, XmlUtils.readStringAttribute(parser, "id"));
+ readAttributionOp(parser, op, XmlUtils.readStringAttribute(parser, "id"));
} else {
Slog.w(TAG, "Unknown element under <op>: "
+ parser.getName());
@@ -4095,7 +4147,7 @@
}
Ops ops = uidState.pkgOps.get(pkgName);
if (ops == null) {
- ops = new Ops(pkgName, uidState, isPrivileged);
+ ops = new Ops(pkgName, uidState);
uidState.pkgOps.put(pkgName, ops);
}
ops.put(op.op, op);
@@ -4187,17 +4239,6 @@
}
out.startTag(null, "uid");
out.attribute(null, "n", Integer.toString(pkg.getUid()));
- synchronized (this) {
- Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(), null,
- false /* isPrivileged */, false /* edit */);
- // Should always be present as the list of PackageOps is generated
- // from Ops.
- if (ops != null) {
- out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
- } else {
- out.attribute(null, "p", Boolean.toString(false));
- }
- }
List<AppOpsManager.OpEntry> ops = pkg.getOps();
for (int j=0; j<ops.size(); j++) {
AppOpsManager.OpEntry op = ops.get(j);
@@ -4207,11 +4248,11 @@
out.attribute(null, "m", Integer.toString(op.getMode()));
}
- for (String featureId : op.getFeatures().keySet()) {
- final OpFeatureEntry feature = op.getFeatures().get(
- featureId);
+ for (String attributionTag : op.getAttributedOpEntries().keySet()) {
+ final AttributedOpEntry attribution =
+ op.getAttributedOpEntries().get(attributionTag);
- final ArraySet<Long> keys = feature.collectKeys();
+ final ArraySet<Long> keys = attribution.collectKeys();
final int keyCount = keys.size();
for (int k = 0; k < keyCount; k++) {
@@ -4220,14 +4261,14 @@
final int uidState = AppOpsManager.extractUidStateFromKey(key);
final int flags = AppOpsManager.extractFlagsFromKey(key);
- final long accessTime = feature.getLastAccessTime(uidState,
+ final long accessTime = attribution.getLastAccessTime(uidState,
uidState, flags);
- final long rejectTime = feature.getLastRejectTime(uidState,
+ final long rejectTime = attribution.getLastRejectTime(uidState,
uidState, flags);
- final long accessDuration = feature.getLastDuration(uidState,
- uidState, flags);
+ final long accessDuration = attribution.getLastDuration(
+ uidState, uidState, flags);
// Proxy information for rejections is not backed up
- final OpEventProxyInfo proxy = feature.getLastProxyInfo(
+ final OpEventProxyInfo proxy = attribution.getLastProxyInfo(
uidState, uidState, flags);
if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
@@ -4236,17 +4277,17 @@
}
String proxyPkg = null;
- String proxyFeatureId = null;
+ String proxyAttributionTag = null;
int proxyUid = Process.INVALID_UID;
if (proxy != null) {
proxyPkg = proxy.getPackageName();
- proxyFeatureId = proxy.getFeatureId();
+ proxyAttributionTag = proxy.getAttributionTag();
proxyUid = proxy.getUid();
}
out.startTag(null, "st");
- if (featureId != null) {
- out.attribute(null, "id", featureId);
+ if (attributionTag != null) {
+ out.attribute(null, "id", attributionTag);
}
out.attribute(null, "n", Long.toString(key));
if (accessTime > 0) {
@@ -4261,8 +4302,8 @@
if (proxyPkg != null) {
out.attribute(null, "pp", proxyPkg);
}
- if (proxyFeatureId != null) {
- out.attribute(null, "pc", proxyFeatureId);
+ if (proxyAttributionTag != null) {
+ out.attribute(null, "pc", proxyAttributionTag);
}
if (proxyUid >= 0) {
out.attribute(null, "pu", Integer.toString(proxyUid));
@@ -4296,7 +4337,7 @@
int userId = UserHandle.USER_SYSTEM;
String packageName;
- String featureId;
+ String attributionTag;
String opStr;
String modeStr;
int op;
@@ -4398,8 +4439,8 @@
userId = UserHandle.parseUserArg(getNextArgRequired());
} else if ("--uid".equals(argument)) {
targetsUid = true;
- } else if ("--feature".equals(argument)) {
- featureId = getNextArgRequired();
+ } else if ("--attribution".equals(argument)) {
+ attributionTag = getNextArgRequired();
} else {
if (packageName == null) {
packageName = argument;
@@ -4494,13 +4535,16 @@
pw.println("AppOps service (appops) commands:");
pw.println(" help");
pw.println(" Print this help text.");
- pw.println(" start [--user <USER_ID>] [--feature <FEATURE_ID>] <PACKAGE | UID> <OP> ");
+ pw.println(" start [--user <USER_ID>] [--attribution <ATTRIBUTION_TAG>] <PACKAGE | UID> "
+ + "<OP> ");
pw.println(" Starts a given operation for a particular application.");
- pw.println(" stop [--user <USER_ID>] [--feature <FEATURE_ID>] <PACKAGE | UID> <OP> ");
+ pw.println(" stop [--user <USER_ID>] [--attribution <ATTRIBUTION_TAG>] <PACKAGE | UID> "
+ + "<OP> ");
pw.println(" Stops a given operation for a particular application.");
pw.println(" set [--user <USER_ID>] <[--uid] PACKAGE | UID> <OP> <MODE>");
pw.println(" Set the mode for a particular application and operation.");
- pw.println(" get [--user <USER_ID>] [--feature <FEATURE_ID>] <PACKAGE | UID> [<OP>]");
+ pw.println(" get [--user <USER_ID>] [--attribution <ATTRIBUTION_TAG>] <PACKAGE | UID> "
+ + "[<OP>]");
pw.println(" Return the mode for a particular application and optional operation.");
pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
pw.println(" Print all packages that currently have the given op in the given mode.");
@@ -4514,8 +4558,8 @@
pw.println(" <PACKAGE> an Android package name or its UID if prefixed by --uid");
pw.println(" <OP> an AppOps operation.");
pw.println(" <MODE> one of allow, ignore, deny, or default");
- pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
- pw.println(" specified, the current user is assumed.");
+ pw.println(" <USER_ID> the user id under which the package is installed. If --user is");
+ pw.println(" not specified, the current user is assumed.");
}
static int onShellCommand(Shell shell, String cmd) {
@@ -4604,7 +4648,7 @@
pw.print(AppOpsManager.opToName(ent.getOp()));
pw.print(": ");
pw.print(AppOpsManager.modeToName(ent.getMode()));
- if (shell.featureId == null) {
+ if (shell.attributionTag == null) {
if (ent.getLastAccessTime(OP_FLAGS_ALL) != -1) {
pw.print("; time=");
TimeUtils.formatDuration(
@@ -4624,29 +4668,30 @@
TimeUtils.formatDuration(ent.getLastDuration(OP_FLAGS_ALL), pw);
}
} else {
- final OpFeatureEntry featureEnt = ent.getFeatures().get(
- shell.featureId);
- if (featureEnt != null) {
- if (featureEnt.getLastAccessTime(OP_FLAGS_ALL) != -1) {
+ final AppOpsManager.AttributedOpEntry attributionEnt =
+ ent.getAttributedOpEntries().get(shell.attributionTag);
+ if (attributionEnt != null) {
+ if (attributionEnt.getLastAccessTime(OP_FLAGS_ALL) != -1) {
pw.print("; time=");
- TimeUtils.formatDuration(now - featureEnt.getLastAccessTime(
- OP_FLAGS_ALL), pw);
+ TimeUtils.formatDuration(
+ now - attributionEnt.getLastAccessTime(
+ OP_FLAGS_ALL), pw);
pw.print(" ago");
}
- if (featureEnt.getLastRejectTime(OP_FLAGS_ALL) != -1) {
+ if (attributionEnt.getLastRejectTime(OP_FLAGS_ALL) != -1) {
pw.print("; rejectTime=");
TimeUtils.formatDuration(
- now - featureEnt.getLastRejectTime(OP_FLAGS_ALL),
- pw);
+ now - attributionEnt.getLastRejectTime(
+ OP_FLAGS_ALL), pw);
pw.print(" ago");
}
- if (featureEnt.isRunning()) {
+ if (attributionEnt.isRunning()) {
pw.print(" (running)");
- } else if (featureEnt.getLastDuration(OP_FLAGS_ALL)
+ } else if (attributionEnt.getLastDuration(OP_FLAGS_ALL)
!= -1) {
pw.print("; duration=");
TimeUtils.formatDuration(
- featureEnt.getLastDuration(OP_FLAGS_ALL), pw);
+ attributionEnt.getLastDuration(OP_FLAGS_ALL), pw);
}
}
}
@@ -4754,7 +4799,7 @@
if (shell.packageName != null) {
shell.mInterface.startOperation(shell.mToken, shell.op, shell.packageUid,
- shell.packageName, shell.featureId, true, true,
+ shell.packageName, shell.attributionTag, true, true,
"appops start shell command");
} else {
return -1;
@@ -4768,8 +4813,8 @@
}
if (shell.packageName != null) {
- shell.mInterface.finishOperation(shell.mToken,
- shell.op, shell.packageUid, shell.packageName, shell.featureId);
+ shell.mInterface.finishOperation(shell.mToken, shell.op, shell.packageUid,
+ shell.packageName, shell.attributionTag);
} else {
return -1;
}
@@ -4794,35 +4839,35 @@
pw.println(" Limit output to data associated with the given app op mode.");
pw.println(" --package [PACKAGE]");
pw.println(" Limit output to data associated with the given package name.");
- pw.println(" --featureId [featureId]");
- pw.println(" Limit output to data associated with the given feature id.");
+ pw.println(" --attributionTag [attributionTag]");
+ pw.println(" Limit output to data associated with the given attribution tag.");
pw.println(" --watchers");
pw.println(" Only output the watcher sections.");
}
- private void dumpStatesLocked(@NonNull PrintWriter pw, @Nullable String filterFeatureId,
+ private void dumpStatesLocked(@NonNull PrintWriter pw, @Nullable String filterAttributionTag,
@HistoricalOpsRequestFilter int filter, long nowElapsed, @NonNull Op op, long now,
@NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
- final int numFeatures = op.mFeatures.size();
- for (int i = 0; i < numFeatures; i++) {
- if ((filter & FILTER_BY_FEATURE_ID) != 0 && !Objects.equals(op.mFeatures.keyAt(i),
- filterFeatureId)) {
+ final int numAttributions = op.mAttributions.size();
+ for (int i = 0; i < numAttributions; i++) {
+ if ((filter & FILTER_BY_ATTRIBUTION_TAG) != 0 && !Objects.equals(
+ op.mAttributions.keyAt(i), filterAttributionTag)) {
continue;
}
- pw.print(prefix + op.mFeatures.keyAt(i) + "=[\n");
- dumpStatesLocked(pw, nowElapsed, op, op.mFeatures.keyAt(i), now, sdf, date,
+ pw.print(prefix + op.mAttributions.keyAt(i) + "=[\n");
+ dumpStatesLocked(pw, nowElapsed, op, op.mAttributions.keyAt(i), now, sdf, date,
prefix + " ");
pw.print(prefix + "]\n");
}
}
private void dumpStatesLocked(@NonNull PrintWriter pw, long nowElapsed, @NonNull Op op,
- @Nullable String featureId, long now, @NonNull SimpleDateFormat sdf,
+ @Nullable String attributionTag, long now, @NonNull SimpleDateFormat sdf,
@NonNull Date date, @NonNull String prefix) {
- final OpFeatureEntry entry = op.createSingleFeatureEntryLocked(
- featureId).getFeatures().get(featureId);
+ final AttributedOpEntry entry = op.createSingleAttributionEntryLocked(
+ attributionTag).getAttributedOpEntries().get(attributionTag);
final ArraySet<Long> keys = entry.collectKeys();
@@ -4839,11 +4884,11 @@
final OpEventProxyInfo proxy = entry.getLastProxyInfo(uidState, uidState, flags);
String proxyPkg = null;
- String proxyFeatureId = null;
+ String proxyAttributionTag = null;
int proxyUid = Process.INVALID_UID;
if (proxy != null) {
proxyPkg = proxy.getPackageName();
- proxyFeatureId = proxy.getFeatureId();
+ proxyAttributionTag = proxy.getAttributionTag();
proxyUid = proxy.getUid();
}
@@ -4867,8 +4912,8 @@
pw.print(proxyUid);
pw.print(", pkg=");
pw.print(proxyPkg);
- pw.print(", feature=");
- pw.print(proxyFeatureId);
+ pw.print(", attributionTag=");
+ pw.print(proxyAttributionTag);
pw.print("]");
}
pw.println();
@@ -4889,21 +4934,21 @@
pw.print(proxyUid);
pw.print(", pkg=");
pw.print(proxyPkg);
- pw.print(", feature=");
- pw.print(proxyFeatureId);
+ pw.print(", attributionTag=");
+ pw.print(proxyAttributionTag);
pw.print("]");
}
pw.println();
}
}
- final FeatureOp featureOp = op.mFeatures.get(featureId);
- if (featureOp.isRunning()) {
+ final AttributedOp attributedOp = op.mAttributions.get(attributionTag);
+ if (attributedOp.isRunning()) {
long earliestElapsedTime = Long.MAX_VALUE;
long maxNumStarts = 0;
- int numInProgressEvents = featureOp.mInProgressEvents.size();
+ int numInProgressEvents = attributedOp.mInProgressEvents.size();
for (int i = 0; i < numInProgressEvents; i++) {
- InProgressStartOpEvent event = featureOp.mInProgressEvents.valueAt(i);
+ InProgressStartOpEvent event = attributedOp.mInProgressEvents.valueAt(i);
earliestElapsedTime = Math.min(earliestElapsedTime, event.getStartElapsedTime());
maxNumStarts = Math.max(maxNumStarts, event.numUnfinishedStarts);
@@ -4926,7 +4971,7 @@
int dumpOp = OP_NONE;
String dumpPackage = null;
- String dumpFeatureId = null;
+ String dumpAttributionTag = null;
int dumpUid = Process.INVALID_UID;
int dumpMode = -1;
boolean dumpWatchers = false;
@@ -4973,14 +5018,14 @@
}
dumpUid = UserHandle.getAppId(dumpUid);
dumpFilter |= FILTER_BY_UID;
- } else if ("--featureId".equals(arg)) {
+ } else if ("--attributionTag".equals(arg)) {
i++;
if (i >= args.length) {
- pw.println("No argument for --featureId option");
+ pw.println("No argument for --attributionTag option");
return;
}
- dumpFeatureId = args[i];
- dumpFilter |= FILTER_BY_FEATURE_ID;
+ dumpAttributionTag = args[i];
+ dumpFilter |= FILTER_BY_ATTRIBUTION_TAG;
} else if ("--mode".equals(arg)) {
i++;
if (i >= args.length) {
@@ -5319,8 +5364,8 @@
pw.print("="); pw.print(AppOpsManager.modeToName(mode));
}
pw.println("): ");
- dumpStatesLocked(pw, dumpFeatureId, dumpFilter, nowElapsed, op, now, sdf,
- date, " ");
+ dumpStatesLocked(pw, dumpAttributionTag, dumpFilter, nowElapsed, op, now,
+ sdf, date, " ");
}
}
}
@@ -5419,7 +5464,7 @@
// Must not hold the appops lock
if (dumpHistory && !dumpWatchers) {
- mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpFeatureId, dumpOp,
+ mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpAttributionTag, dumpOp,
dumpFilter);
}
}
@@ -5524,9 +5569,9 @@
if (resolvedPackageName == null) {
return false;
}
- // TODO moltmann: Allow to check for feature op activeness
+ // TODO moltmann: Allow to check for attribution op activeness
synchronized (AppOpsService.this) {
- Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, null, false, false);
+ Ops pkgOps = getOpsLocked(uid, resolvedPackageName, null, null, false);
if (pkgOps == null) {
return false;
}
@@ -5585,7 +5630,7 @@
* Report runtime access to AppOp together with message (including stack trace)
*
* @param packageName The package which reported the op
- * @param notedAppOp contains code of op and featureId provided by developer
+ * @param notedAppOp contains code of op and attributionTag provided by developer
* @param message Message describing AppOp access (can be stack trace)
*
* @return Config for future sampling to reduce amount of reporting
@@ -5596,7 +5641,7 @@
int uid = Binder.getCallingUid();
Objects.requireNonNull(packageName);
synchronized (this) {
- switchPackageIfRarelyUsedLocked(packageName);
+ switchPackageIfBootTimeOrRarelyUsedLocked(packageName);
if (!packageName.equals(mSampledPackage)) {
return new MessageSamplingConfig(OP_NONE, 0,
Instant.now().plus(1, ChronoUnit.HOURS).toEpochMilli());
@@ -5607,7 +5652,7 @@
reportRuntimeAppOpAccessMessageInternalLocked(uid, packageName,
AppOpsManager.strOpToOp(notedAppOp.getOp()),
- notedAppOp.getFeatureId(), message);
+ notedAppOp.getAttributionTag(), message);
return new MessageSamplingConfig(mSampledAppOpCode, mAcceptableLeftDistance,
Instant.now().plus(1, ChronoUnit.HOURS).toEpochMilli());
@@ -5620,17 +5665,18 @@
* @param uid Uid of the package which reported the op
* @param packageName The package which reported the op
* @param opCode Code of AppOp
- * @param featureId FeautreId of AppOp reported
+ * @param attributionTag FeautreId of AppOp reported
* @param message Message describing AppOp access (can be stack trace)
*/
private void reportRuntimeAppOpAccessMessageAsyncLocked(int uid,
- @NonNull String packageName, int opCode, @Nullable String featureId,
+ @NonNull String packageName, int opCode, @Nullable String attributionTag,
@NonNull String message) {
- switchPackageIfRarelyUsedLocked(packageName);
+ switchPackageIfBootTimeOrRarelyUsedLocked(packageName);
if (!Objects.equals(mSampledPackage, packageName)) {
return;
}
- reportRuntimeAppOpAccessMessageInternalLocked(uid, packageName, opCode, featureId, message);
+ reportRuntimeAppOpAccessMessageInternalLocked(uid, packageName, opCode, attributionTag,
+ message);
}
/**
@@ -5638,7 +5684,7 @@
* reporting uniformly at random across all received messages.
*/
private void reportRuntimeAppOpAccessMessageInternalLocked(int uid,
- @NonNull String packageName, int opCode, @Nullable String featureId,
+ @NonNull String packageName, int opCode, @Nullable String attributionTag,
@NonNull String message) {
int newLeftDistance = AppOpsManager.leftCircularDistance(opCode,
mSampledAppOpCode, _NUM_OP);
@@ -5655,7 +5701,7 @@
mMessagesCollectedCount += 1.0f;
if (ThreadLocalRandom.current().nextFloat() <= 1.0f / mMessagesCollectedCount) {
mCollectedRuntimePermissionMessage = new RuntimeAppOpAccessMessage(uid, opCode,
- packageName, featureId, message, mSamplingStrategy);
+ packageName, attributionTag, message, mSamplingStrategy);
}
return;
}
@@ -5676,11 +5722,16 @@
/**
* Checks if package is in the list of rarely used package and starts watching the new package
- * to collect incoming message.
+ * to collect incoming message or if collection is happening in first minutes since boot.
* @param packageName
*/
- private void switchPackageIfRarelyUsedLocked(@NonNull String packageName) {
- if (mRarelyUsedPackages.contains(packageName)) {
+ private void switchPackageIfBootTimeOrRarelyUsedLocked(@NonNull String packageName) {
+ if (mSampledPackage == null) {
+ if (ThreadLocalRandom.current().nextFloat() < 0.1f) {
+ mSamplingStrategy = SAMPLING_STRATEGY_BOOT_TIME_SAMPLING;
+ resampleAppOpForPackageLocked(packageName);
+ }
+ } else if (mRarelyUsedPackages.contains(packageName)) {
mRarelyUsedPackages.remove(packageName);
if (ThreadLocalRandom.current().nextFloat() < 0.5f) {
mSamplingStrategy = SAMPLING_STRATEGY_RARELY_USED;
@@ -5742,6 +5793,10 @@
}
}
synchronized (this) {
+ int numPkgs = mRarelyUsedPackages.size();
+ for (int i = 0; i < numPkgs; i++) {
+ candidates.add(mRarelyUsedPackages.valueAt(i));
+ }
mRarelyUsedPackages = candidates;
}
}
@@ -6051,4 +6106,142 @@
setMode(code, uid, packageName, mode, callback);
}
}
+
+
+ /**
+ * Async task for writing note op stack trace, op code, package name and version to file
+ * More specifically, writes all the collected ops from {@link #mNoteOpCallerStacktraces}
+ */
+ private void writeNoteOps() {
+ synchronized (this) {
+ mWriteNoteOpsScheduled = false;
+ }
+ synchronized (mNoteOpCallerStacktracesFile) {
+ try (FileWriter writer = new FileWriter(mNoteOpCallerStacktracesFile)) {
+ int numTraces = mNoteOpCallerStacktraces.size();
+ for (int i = 0; i < numTraces; i++) {
+ // Writing json formatted string into file
+ writer.write(mNoteOpCallerStacktraces.valueAt(i).asJson());
+ // Comma separation, so we can wrap the entire log as a JSON object
+ // when all results are collected
+ writer.write(",");
+ }
+ } catch (IOException e) {
+ Slog.w(TAG, "Failed to load opsValidation file for FileWriter", e);
+ }
+ }
+ }
+
+ /**
+ * This class represents a NoteOp Trace object amd contains the necessary fields that will
+ * be written to file to use for permissions data validation in JSON format
+ */
+ @Immutable
+ static class NoteOpTrace {
+ static final String STACKTRACE = "stackTrace";
+ static final String OP = "op";
+ static final String PACKAGENAME = "packageName";
+ static final String VERSION = "version";
+
+ private final @NonNull String mStackTrace;
+ private final int mOp;
+ private final @Nullable String mPackageName;
+ private final long mVersion;
+
+ /**
+ * Initialize a NoteOp object using a JSON object containing the necessary fields
+ *
+ * @param jsonTrace JSON object represented as a string
+ *
+ * @return NoteOpTrace object initialized with JSON fields
+ */
+ static NoteOpTrace fromJson(String jsonTrace) {
+ try {
+ // Re-add closing bracket which acted as a delimiter by the reader
+ JSONObject obj = new JSONObject(jsonTrace.concat("}"));
+ return new NoteOpTrace(obj.getString(STACKTRACE), obj.getInt(OP),
+ obj.getString(PACKAGENAME), obj.getLong(VERSION));
+ } catch (JSONException e) {
+ // Swallow error, only meant for logging ops, should not affect flow of the code
+ Slog.e(TAG, "Error constructing NoteOpTrace object "
+ + "JSON trace format incorrect", e);
+ return null;
+ }
+ }
+
+ NoteOpTrace(String stackTrace, int op, String packageName, long version) {
+ mStackTrace = stackTrace;
+ mOp = op;
+ mPackageName = packageName;
+ mVersion = version;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ NoteOpTrace that = (NoteOpTrace) o;
+ return mOp == that.mOp
+ && mVersion == that.mVersion
+ && mStackTrace.equals(that.mStackTrace)
+ && Objects.equals(mPackageName, that.mPackageName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mStackTrace, mOp, mPackageName, mVersion);
+ }
+
+ /**
+ * The object is formatted as a JSON object and returned as a String
+ *
+ * @return JSON formatted string
+ */
+ public String asJson() {
+ return "{"
+ + "\"" + STACKTRACE + "\":\"" + mStackTrace.replace("\n", "\\n")
+ + '\"' + ",\"" + OP + "\":" + mOp
+ + ",\"" + PACKAGENAME + "\":\"" + mPackageName + '\"'
+ + ",\"" + VERSION + "\":" + mVersion
+ + '}';
+ }
+ }
+
+ /**
+ * Collects noteOps, noteProxyOps and startOps from AppOpsManager and writes it into a file
+ * which will be used for permissions data validation, the given parameters to this method
+ * will be logged in json format
+ *
+ * @param stackTrace stacktrace from the most recent call in AppOpsManager
+ * @param op op code
+ * @param packageName package making call
+ * @param version android version for this call
+ */
+ @Override
+ public void collectNoteOpCallsForValidation(String stackTrace, int op, String packageName,
+ long version) {
+ if (!AppOpsManager.NOTE_OP_COLLECTION_ENABLED) {
+ return;
+ }
+
+ Objects.requireNonNull(stackTrace);
+ Preconditions.checkArgument(op >= 0);
+ Preconditions.checkArgument(op < AppOpsManager._NUM_OP);
+ Objects.requireNonNull(version);
+
+ NoteOpTrace noteOpTrace = new NoteOpTrace(stackTrace, op, packageName, version);
+
+ boolean noteOpSetWasChanged;
+ synchronized (this) {
+ noteOpSetWasChanged = mNoteOpCallerStacktraces.add(noteOpTrace);
+ if (noteOpSetWasChanged && !mWriteNoteOpsScheduled) {
+ mWriteNoteOpsScheduled = true;
+ mHandler.postDelayed(PooledLambda.obtainRunnable((that) -> {
+ AsyncTask.execute(() -> {
+ that.writeNoteOps();
+ });
+ }, this), 2500);
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/appop/HistoricalRegistry.java b/services/core/java/com/android/server/appop/HistoricalRegistry.java
index cd450d4..ed45069 100644
--- a/services/core/java/com/android/server/appop/HistoricalRegistry.java
+++ b/services/core/java/com/android/server/appop/HistoricalRegistry.java
@@ -15,7 +15,7 @@
*/
package com.android.server.appop;
-import static android.app.AppOpsManager.FILTER_BY_FEATURE_ID;
+import static android.app.AppOpsManager.FILTER_BY_ATTRIBUTION_TAG;
import static android.app.AppOpsManager.FILTER_BY_OP_NAMES;
import static android.app.AppOpsManager.FILTER_BY_PACKAGE_NAME;
import static android.app.AppOpsManager.FILTER_BY_UID;
@@ -23,7 +23,6 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AppOpsManager;
-import android.app.AppOpsManager.HistoricalFeatureOps;
import android.app.AppOpsManager.HistoricalMode;
import android.app.AppOpsManager.HistoricalOp;
import android.app.AppOpsManager.HistoricalOps;
@@ -282,7 +281,7 @@
}
void dump(String prefix, PrintWriter pw, int filterUid, @Nullable String filterPackage,
- @Nullable String filterFeatureId, int filterOp,
+ @Nullable String filterAttributionTag, int filterOp,
@HistoricalOpsRequestFilter int filter) {
if (!isApiEnabled()) {
return;
@@ -298,7 +297,7 @@
pw.println(AppOpsManager.historicalModeToString(mMode));
final StringDumpVisitor visitor = new StringDumpVisitor(prefix + " ",
- pw, filterUid, filterPackage, filterFeatureId, filterOp, filter);
+ pw, filterUid, filterPackage, filterAttributionTag, filterOp, filter);
final long nowMillis = System.currentTimeMillis();
// Dump in memory state first
@@ -338,7 +337,7 @@
}
void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
- @Nullable String featureId, @Nullable String[] opNames,
+ @Nullable String attributionTag, @Nullable String[] opNames,
@HistoricalOpsRequestFilter int filter, long beginTimeMillis, long endTimeMillis,
@OpFlags int flags, @NonNull RemoteCallback callback) {
if (!isApiEnabled()) {
@@ -354,7 +353,7 @@
return;
}
final HistoricalOps result = new HistoricalOps(beginTimeMillis, endTimeMillis);
- mPersistence.collectHistoricalOpsDLocked(result, uid, packageName, featureId,
+ mPersistence.collectHistoricalOpsDLocked(result, uid, packageName, attributionTag,
opNames, filter, beginTimeMillis, endTimeMillis, flags);
final Bundle payload = new Bundle();
payload.putParcelable(AppOpsManager.KEY_HISTORICAL_OPS, result);
@@ -363,7 +362,7 @@
}
}
- void getHistoricalOps(int uid, @NonNull String packageName, @Nullable String featureId,
+ void getHistoricalOps(int uid, @NonNull String packageName, @Nullable String attributionTag,
@Nullable String[] opNames, @HistoricalOpsRequestFilter int filter,
long beginTimeMillis, long endTimeMillis, @OpFlags int flags,
@NonNull RemoteCallback callback) {
@@ -401,7 +400,7 @@
|| inMemoryAdjEndTimeMillis <= currentOps.getBeginTimeMillis())) {
// Some of the current batch falls into the query, so extract that.
final HistoricalOps currentOpsCopy = new HistoricalOps(currentOps);
- currentOpsCopy.filter(uid, packageName, featureId, opNames, filter,
+ currentOpsCopy.filter(uid, packageName, attributionTag, opNames, filter,
inMemoryAdjBeginTimeMillis, inMemoryAdjEndTimeMillis);
result.merge(currentOpsCopy);
}
@@ -421,7 +420,7 @@
- onDiskAndInMemoryOffsetMillis, 0);
final long onDiskAdjEndTimeMillis = Math.max(inMemoryAdjEndTimeMillis
- onDiskAndInMemoryOffsetMillis, 0);
- mPersistence.collectHistoricalOpsDLocked(result, uid, packageName, featureId,
+ mPersistence.collectHistoricalOpsDLocked(result, uid, packageName, attributionTag,
opNames, filter, onDiskAdjBeginTimeMillis, onDiskAdjEndTimeMillis, flags);
}
@@ -436,7 +435,7 @@
}
void incrementOpAccessedCount(int op, int uid, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags) {
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags) {
synchronized (mInMemoryLock) {
if (mMode == AppOpsManager.HISTORICAL_MODE_ENABLED_ACTIVE) {
if (!isPersistenceInitializedMLocked()) {
@@ -445,13 +444,13 @@
}
getUpdatedPendingHistoricalOpsMLocked(
System.currentTimeMillis()).increaseAccessCount(op, uid, packageName,
- featureId, uidState, flags, 1);
+ attributionTag, uidState, flags, 1);
}
}
}
void incrementOpRejected(int op, int uid, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags) {
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags) {
synchronized (mInMemoryLock) {
if (mMode == AppOpsManager.HISTORICAL_MODE_ENABLED_ACTIVE) {
if (!isPersistenceInitializedMLocked()) {
@@ -460,13 +459,13 @@
}
getUpdatedPendingHistoricalOpsMLocked(
System.currentTimeMillis()).increaseRejectCount(op, uid, packageName,
- featureId, uidState, flags, 1);
+ attributionTag, uidState, flags, 1);
}
}
}
void increaseOpAccessDuration(int op, int uid, @NonNull String packageName,
- @Nullable String featureId, @UidState int uidState, @OpFlags int flags,
+ @Nullable String attributionTag, @UidState int uidState, @OpFlags int flags,
long increment) {
synchronized (mInMemoryLock) {
if (mMode == AppOpsManager.HISTORICAL_MODE_ENABLED_ACTIVE) {
@@ -476,7 +475,7 @@
}
getUpdatedPendingHistoricalOpsMLocked(
System.currentTimeMillis()).increaseAccessDuration(op, uid, packageName,
- featureId, uidState, flags, increment);
+ attributionTag, uidState, flags, increment);
}
}
}
@@ -728,7 +727,7 @@
private static final String TAG_OPS = "ops";
private static final String TAG_UID = "uid";
private static final String TAG_PACKAGE = "pkg";
- private static final String TAG_FEATURE = "ftr";
+ private static final String TAG_ATTRIBUTION = "ftr";
private static final String TAG_OP = "op";
private static final String TAG_STATE = "st";
@@ -807,9 +806,9 @@
@Nullable List<HistoricalOps> readHistoryRawDLocked() {
return collectHistoricalOpsBaseDLocked(Process.INVALID_UID /*filterUid*/,
- null /*filterPackageName*/, null /*filterFeatureId*/, null /*filterOpNames*/,
- 0 /*filter*/, 0 /*filterBeginTimeMills*/, Long.MAX_VALUE /*filterEndTimeMills*/,
- AppOpsManager.OP_FLAGS_ALL);
+ null /*filterPackageName*/, null /*filterAttributionTag*/,
+ null /*filterOpNames*/, 0 /*filter*/, 0 /*filterBeginTimeMills*/,
+ Long.MAX_VALUE /*filterEndTimeMills*/, AppOpsManager.OP_FLAGS_ALL);
}
@Nullable List<HistoricalOps> readHistoryDLocked() {
@@ -861,13 +860,13 @@
return 0;
}
- private void collectHistoricalOpsDLocked(@NonNull HistoricalOps currentOps,
- int filterUid, @Nullable String filterPackageName, @Nullable String filterFeatureId,
+ private void collectHistoricalOpsDLocked(@NonNull HistoricalOps currentOps, int filterUid,
+ @Nullable String filterPackageName, @Nullable String filterAttributionTag,
@Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
long filterBeingMillis, long filterEndMillis, @OpFlags int filterFlags) {
final List<HistoricalOps> readOps = collectHistoricalOpsBaseDLocked(filterUid,
- filterPackageName, filterFeatureId, filterOpNames, filter, filterBeingMillis,
- filterEndMillis, filterFlags);
+ filterPackageName, filterAttributionTag, filterOpNames, filter,
+ filterBeingMillis, filterEndMillis, filterFlags);
if (readOps != null) {
final int readCount = readOps.size();
for (int i = 0; i < readCount; i++) {
@@ -877,8 +876,8 @@
}
}
- private @Nullable LinkedList<HistoricalOps> collectHistoricalOpsBaseDLocked(
- int filterUid, @Nullable String filterPackageName, @Nullable String filterFeatureId,
+ private @Nullable LinkedList<HistoricalOps> collectHistoricalOpsBaseDLocked(int filterUid,
+ @Nullable String filterPackageName, @Nullable String filterAttributionTag,
@Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
long filterBeginTimeMillis, long filterEndTimeMillis, @OpFlags int filterFlags) {
File baseDir = null;
@@ -892,7 +891,7 @@
final Set<String> historyFiles = getHistoricalFileNames(baseDir);
final long[] globalContentOffsetMillis = {0};
final LinkedList<HistoricalOps> ops = collectHistoricalOpsRecursiveDLocked(
- baseDir, filterUid, filterPackageName, filterFeatureId, filterOpNames,
+ baseDir, filterUid, filterPackageName, filterAttributionTag, filterOpNames,
filter, filterBeginTimeMillis, filterEndTimeMillis, filterFlags,
globalContentOffsetMillis, null /*outOps*/, 0 /*depth*/, historyFiles);
if (DEBUG) {
@@ -909,7 +908,7 @@
private @Nullable LinkedList<HistoricalOps> collectHistoricalOpsRecursiveDLocked(
@NonNull File baseDir, int filterUid, @Nullable String filterPackageName,
- @Nullable String filterFeatureId, @Nullable String[] filterOpNames,
+ @Nullable String filterAttributionTag, @Nullable String[] filterOpNames,
@HistoricalOpsRequestFilter int filter, long filterBeginTimeMillis,
long filterEndTimeMillis, @OpFlags int filterFlags,
@NonNull long[] globalContentOffsetMillis,
@@ -927,7 +926,7 @@
// Read historical data at this level
final List<HistoricalOps> readOps = readHistoricalOpsLocked(baseDir,
previousIntervalEndMillis, currentIntervalEndMillis, filterUid,
- filterPackageName, filterFeatureId, filterOpNames, filter,
+ filterPackageName, filterAttributionTag, filterOpNames, filter,
filterBeginTimeMillis, filterEndTimeMillis, filterFlags,
globalContentOffsetMillis, depth, historyFiles);
// Empty is a special signal to stop diving
@@ -937,7 +936,7 @@
// Collect older historical data from subsequent levels
outOps = collectHistoricalOpsRecursiveDLocked(baseDir, filterUid, filterPackageName,
- filterFeatureId, filterOpNames, filter, filterBeginTimeMillis,
+ filterAttributionTag, filterOpNames, filter, filterBeginTimeMillis,
filterEndTimeMillis, filterFlags, globalContentOffsetMillis, outOps, depth + 1,
historyFiles);
@@ -1006,7 +1005,7 @@
final List<HistoricalOps> existingOps = readHistoricalOpsLocked(oldBaseDir,
previousIntervalEndMillis, currentIntervalEndMillis,
Process.INVALID_UID /*filterUid*/, null /*filterPackageName*/,
- null /*filterFeatureId*/, null /*filterOpNames*/, 0 /*filter*/,
+ null /*filterAttributionTag*/, null /*filterOpNames*/, 0 /*filter*/,
Long.MIN_VALUE /*filterBeginTimeMillis*/,
Long.MAX_VALUE /*filterEndTimeMillis*/, AppOpsManager.OP_FLAGS_ALL, null, depth,
null /*historyFiles*/);
@@ -1120,7 +1119,7 @@
private @Nullable List<HistoricalOps> readHistoricalOpsLocked(File baseDir,
long intervalBeginMillis, long intervalEndMillis, int filterUid,
- @Nullable String filterPackageName, @Nullable String filterFeatureId,
+ @Nullable String filterPackageName, @Nullable String filterAttributionTag,
@Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
long filterBeginTimeMillis, long filterEndTimeMillis, @OpFlags int filterFlags,
@Nullable long[] cumulativeOverflowMillis, int depth,
@@ -1147,15 +1146,16 @@
return null;
}
}
- return readHistoricalOpsLocked(file, filterUid, filterPackageName, filterFeatureId,
+ return readHistoricalOpsLocked(file, filterUid, filterPackageName, filterAttributionTag,
filterOpNames, filter, filterBeginTimeMillis, filterEndTimeMillis, filterFlags,
cumulativeOverflowMillis);
}
- private @Nullable List<HistoricalOps> readHistoricalOpsLocked(@NonNull File file,
- int filterUid, @Nullable String filterPackageName, @Nullable String filterFeatureId,
- @Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
- long filterBeginTimeMillis, long filterEndTimeMillis, @OpFlags int filterFlags,
+ private @Nullable List<HistoricalOps> readHistoricalOpsLocked(@NonNull File file,
+ int filterUid, @Nullable String filterPackageName,
+ @Nullable String filterAttributionTag, @Nullable String[] filterOpNames,
+ @HistoricalOpsRequestFilter int filter, long filterBeginTimeMillis,
+ long filterEndTimeMillis, @OpFlags int filterFlags,
@Nullable long[] cumulativeOverflowMillis)
throws IOException, XmlPullParserException {
if (DEBUG) {
@@ -1180,7 +1180,7 @@
while (XmlUtils.nextElementWithin(parser, depth)) {
if (TAG_OPS.equals(parser.getName())) {
final HistoricalOps ops = readeHistoricalOpsDLocked(parser, filterUid,
- filterPackageName, filterFeatureId, filterOpNames, filter,
+ filterPackageName, filterAttributionTag, filterOpNames, filter,
filterBeginTimeMillis, filterEndTimeMillis, filterFlags,
cumulativeOverflowMillis);
if (ops == null) {
@@ -1215,7 +1215,7 @@
private @Nullable HistoricalOps readeHistoricalOpsDLocked(
@NonNull XmlPullParser parser, int filterUid, @Nullable String filterPackageName,
- @Nullable String filterFeatureId, @Nullable String[] filterOpNames,
+ @Nullable String filterAttributionTag, @Nullable String[] filterOpNames,
@HistoricalOpsRequestFilter int filter, long filterBeginTimeMillis,
long filterEndTimeMillis, @OpFlags int filterFlags,
@Nullable long[] cumulativeOverflowMillis)
@@ -1245,8 +1245,8 @@
while (XmlUtils.nextElementWithin(parser, depth)) {
if (TAG_UID.equals(parser.getName())) {
final HistoricalOps returnedOps = readHistoricalUidOpsDLocked(ops, parser,
- filterUid, filterPackageName, filterFeatureId, filterOpNames, filter,
- filterFlags, filterScale);
+ filterUid, filterPackageName, filterAttributionTag, filterOpNames,
+ filter, filterFlags, filterScale);
if (ops == null) {
ops = returnedOps;
}
@@ -1260,7 +1260,7 @@
private @Nullable HistoricalOps readHistoricalUidOpsDLocked(
@Nullable HistoricalOps ops, @NonNull XmlPullParser parser, int filterUid,
- @Nullable String filterPackageName, @Nullable String filterFeatureId,
+ @Nullable String filterPackageName, @Nullable String filterAttributionTag,
@Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
@OpFlags int filterFlags, double filterScale)
throws IOException, XmlPullParserException {
@@ -1272,8 +1272,8 @@
final int depth = parser.getDepth();
while (XmlUtils.nextElementWithin(parser, depth)) {
if (TAG_PACKAGE.equals(parser.getName())) {
- final HistoricalOps returnedOps = readHistoricalPackageOpsDLocked(ops,
- uid, parser, filterPackageName, filterFeatureId, filterOpNames, filter,
+ final HistoricalOps returnedOps = readHistoricalPackageOpsDLocked(ops, uid,
+ parser, filterPackageName, filterAttributionTag, filterOpNames, filter,
filterFlags, filterScale);
if (ops == null) {
ops = returnedOps;
@@ -1285,7 +1285,7 @@
private @Nullable HistoricalOps readHistoricalPackageOpsDLocked(
@Nullable HistoricalOps ops, int uid, @NonNull XmlPullParser parser,
- @Nullable String filterPackageName, @Nullable String filterFeatureId,
+ @Nullable String filterPackageName, @Nullable String filterAttributionTag,
@Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
@OpFlags int filterFlags, double filterScale)
throws IOException, XmlPullParserException {
@@ -1296,9 +1296,9 @@
}
final int depth = parser.getDepth();
while (XmlUtils.nextElementWithin(parser, depth)) {
- if (TAG_FEATURE.equals(parser.getName())) {
- final HistoricalOps returnedOps = readHistoricalFeatureOpsDLocked(ops, uid,
- packageName, parser, filterFeatureId, filterOpNames, filter,
+ if (TAG_ATTRIBUTION.equals(parser.getName())) {
+ final HistoricalOps returnedOps = readHistoricalAttributionOpsDLocked(ops, uid,
+ packageName, parser, filterAttributionTag, filterOpNames, filter,
filterFlags, filterScale);
if (ops == null) {
ops = returnedOps;
@@ -1308,15 +1308,15 @@
return ops;
}
- private @Nullable HistoricalOps readHistoricalFeatureOpsDLocked(@Nullable HistoricalOps ops,
- int uid, String packageName, @NonNull XmlPullParser parser,
- @Nullable String filterFeatureId, @Nullable String[] filterOpNames,
- @HistoricalOpsRequestFilter int filter, @OpFlags int filterFlags,
- double filterScale)
+ private @Nullable HistoricalOps readHistoricalAttributionOpsDLocked(
+ @Nullable HistoricalOps ops, int uid, String packageName,
+ @NonNull XmlPullParser parser, @Nullable String filterAttributionTag,
+ @Nullable String[] filterOpNames, @HistoricalOpsRequestFilter int filter,
+ @OpFlags int filterFlags, double filterScale)
throws IOException, XmlPullParserException {
- final String featureId = XmlUtils.readStringAttribute(parser, ATTR_NAME);
- if ((filter & FILTER_BY_FEATURE_ID) != 0 && !Objects.equals(filterFeatureId,
- featureId)) {
+ final String attributionTag = XmlUtils.readStringAttribute(parser, ATTR_NAME);
+ if ((filter & FILTER_BY_ATTRIBUTION_TAG) != 0 && !Objects.equals(filterAttributionTag,
+ attributionTag)) {
XmlUtils.skipCurrentTag(parser);
return null;
}
@@ -1324,7 +1324,8 @@
while (XmlUtils.nextElementWithin(parser, depth)) {
if (TAG_OP.equals(parser.getName())) {
final HistoricalOps returnedOps = readHistoricalOpDLocked(ops, uid, packageName,
- featureId, parser, filterOpNames, filter, filterFlags, filterScale);
+ attributionTag, parser, filterOpNames, filter, filterFlags,
+ filterScale);
if (ops == null) {
ops = returnedOps;
}
@@ -1334,7 +1335,7 @@
}
private @Nullable HistoricalOps readHistoricalOpDLocked(@Nullable HistoricalOps ops,
- int uid, @NonNull String packageName, @Nullable String featureId,
+ int uid, @NonNull String packageName, @Nullable String attributionTag,
@NonNull XmlPullParser parser, @Nullable String[] filterOpNames,
@HistoricalOpsRequestFilter int filter, @OpFlags int filterFlags,
double filterScale)
@@ -1349,7 +1350,7 @@
while (XmlUtils.nextElementWithin(parser, depth)) {
if (TAG_STATE.equals(parser.getName())) {
final HistoricalOps returnedOps = readStateDLocked(ops, uid,
- packageName, featureId, op, parser, filterFlags, filterScale);
+ packageName, attributionTag, op, parser, filterFlags, filterScale);
if (ops == null) {
ops = returnedOps;
}
@@ -1359,7 +1360,7 @@
}
private @Nullable HistoricalOps readStateDLocked(@Nullable HistoricalOps ops,
- int uid, @NonNull String packageName, @Nullable String featureId, int op,
+ int uid, @NonNull String packageName, @Nullable String attributionTag, int op,
@NonNull XmlPullParser parser, @OpFlags int filterFlags, double filterScale)
throws IOException {
final long key = XmlUtils.readLongAttribute(parser, ATTR_NAME);
@@ -1377,7 +1378,7 @@
if (ops == null) {
ops = new HistoricalOps(0, 0);
}
- ops.increaseAccessCount(op, uid, packageName, featureId, uidState, flags,
+ ops.increaseAccessCount(op, uid, packageName, attributionTag, uidState, flags,
accessCount);
}
long rejectCount = XmlUtils.readLongAttribute(parser, ATTR_REJECT_COUNT, 0);
@@ -1389,7 +1390,7 @@
if (ops == null) {
ops = new HistoricalOps(0, 0);
}
- ops.increaseRejectCount(op, uid, packageName, featureId, uidState, flags,
+ ops.increaseRejectCount(op, uid, packageName, attributionTag, uidState, flags,
rejectCount);
}
long accessDuration = XmlUtils.readLongAttribute(parser, ATTR_ACCESS_DURATION, 0);
@@ -1401,7 +1402,7 @@
if (ops == null) {
ops = new HistoricalOps(0, 0);
}
- ops.increaseAccessDuration(op, uid, packageName, featureId, uidState, flags,
+ ops.increaseAccessDuration(op, uid, packageName, attributionTag, uidState, flags,
accessDuration);
}
return ops;
@@ -1467,24 +1468,25 @@
@NonNull XmlSerializer serializer) throws IOException {
serializer.startTag(null, TAG_PACKAGE);
serializer.attribute(null, ATTR_NAME, packageOps.getPackageName());
- final int numFeatures = packageOps.getFeatureCount();
- for (int i = 0; i < numFeatures; i++) {
- final HistoricalFeatureOps op = packageOps.getFeatureOpsAt(i);
- writeHistoricalFeatureOpsDLocked(op, serializer);
+ final int numAttributions = packageOps.getAttributedOpsCount();
+ for (int i = 0; i < numAttributions; i++) {
+ final AppOpsManager.AttributedHistoricalOps op = packageOps.getAttributedOpsAt(i);
+ writeHistoricalAttributionOpsDLocked(op, serializer);
}
serializer.endTag(null, TAG_PACKAGE);
}
- private void writeHistoricalFeatureOpsDLocked(@NonNull HistoricalFeatureOps featureOps,
+ private void writeHistoricalAttributionOpsDLocked(
+ @NonNull AppOpsManager.AttributedHistoricalOps attributionOps,
@NonNull XmlSerializer serializer) throws IOException {
- serializer.startTag(null, TAG_FEATURE);
- XmlUtils.writeStringAttribute(serializer, ATTR_NAME, featureOps.getFeatureId());
- final int opCount = featureOps.getOpCount();
+ serializer.startTag(null, TAG_ATTRIBUTION);
+ XmlUtils.writeStringAttribute(serializer, ATTR_NAME, attributionOps.getTag());
+ final int opCount = attributionOps.getOpCount();
for (int i = 0; i < opCount; i++) {
- final HistoricalOp op = featureOps.getOpAt(i);
+ final HistoricalOp op = attributionOps.getOpAt(i);
writeHistoricalOpDLocked(op, serializer);
}
- serializer.endTag(null, TAG_FEATURE);
+ serializer.endTag(null, TAG_ATTRIBUTION);
}
private void writeHistoricalOpDLocked(@NonNull HistoricalOp op,
@@ -1718,29 +1720,29 @@
private final @NonNull String mOpsPrefix;
private final @NonNull String mUidPrefix;
private final @NonNull String mPackagePrefix;
- private final @NonNull String mFeaturePrefix;
+ private final @NonNull String mAttributionPrefix;
private final @NonNull String mEntryPrefix;
private final @NonNull String mUidStatePrefix;
private final @NonNull PrintWriter mWriter;
private final int mFilterUid;
private final String mFilterPackage;
- private final String mFilterFeatureId;
+ private final String mFilterAttributionTag;
private final int mFilterOp;
private final @HistoricalOpsRequestFilter int mFilter;
StringDumpVisitor(@NonNull String prefix, @NonNull PrintWriter writer, int filterUid,
- @Nullable String filterPackage, @Nullable String filterFeatureId, int filterOp,
+ @Nullable String filterPackage, @Nullable String filterAttributionTag, int filterOp,
@HistoricalOpsRequestFilter int filter) {
mOpsPrefix = prefix + " ";
mUidPrefix = mOpsPrefix + " ";
mPackagePrefix = mUidPrefix + " ";
- mFeaturePrefix = mPackagePrefix + " ";
- mEntryPrefix = mFeaturePrefix + " ";
+ mAttributionPrefix = mPackagePrefix + " ";
+ mEntryPrefix = mAttributionPrefix + " ";
mUidStatePrefix = mEntryPrefix + " ";
mWriter = writer;
mFilterUid = filterUid;
mFilterPackage = filterPackage;
- mFilterFeatureId = filterFeatureId;
+ mFilterAttributionTag = filterAttributionTag;
mFilterOp = filterOp;
mFilter = filter;
}
@@ -1791,14 +1793,14 @@
}
@Override
- public void visitHistoricalFeatureOps(HistoricalFeatureOps ops) {
- if ((mFilter & FILTER_BY_FEATURE_ID) != 0 && !Objects.equals(mFilterPackage,
- ops.getFeatureId())) {
+ public void visitHistoricalAttributionOps(AppOpsManager.AttributedHistoricalOps ops) {
+ if ((mFilter & FILTER_BY_ATTRIBUTION_TAG) != 0 && !Objects.equals(mFilterPackage,
+ ops.getTag())) {
return;
}
- mWriter.print(mFeaturePrefix);
- mWriter.print("Feature ");
- mWriter.print(ops.getFeatureId());
+ mWriter.print(mAttributionPrefix);
+ mWriter.print("Attribution ");
+ mWriter.print(ops.getTag());
mWriter.println(":");
}
diff --git a/services/core/java/com/android/server/biometrics/BiometricService.java b/services/core/java/com/android/server/biometrics/BiometricService.java
index 858c157..e7c09ba 100644
--- a/services/core/java/com/android/server/biometrics/BiometricService.java
+++ b/services/core/java/com/android/server/biometrics/BiometricService.java
@@ -24,6 +24,7 @@
import static android.hardware.biometrics.BiometricManager.Authenticators;
import android.annotation.IntDef;
+import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.IActivityManager;
import android.app.UserSwitchObserver;
@@ -296,7 +297,7 @@
}
case MSG_ON_DISMISSED: {
- handleOnDismissed(msg.arg1);
+ handleOnDismissed(msg.arg1, (byte[]) msg.obj);
break;
}
@@ -611,8 +612,12 @@
}
@Override
- public void onDialogDismissed(int reason) throws RemoteException {
- mHandler.obtainMessage(MSG_ON_DISMISSED, reason, 0 /* arg2 */).sendToTarget();
+ public void onDialogDismissed(int reason, @Nullable byte[] credentialAttestation)
+ throws RemoteException {
+ mHandler.obtainMessage(MSG_ON_DISMISSED,
+ reason,
+ 0 /* arg2 */,
+ credentialAttestation /* obj */).sendToTarget();
}
@Override
@@ -1138,9 +1143,10 @@
biometricStatus = result.second;
- Slog.d(TAG, "Authenticator ID: " + authenticator.id
+ Slog.d(TAG, "Package: " + opPackageName
+ + " Authenticator ID: " + authenticator.id
+ " Modality: " + authenticator.modality
- + " ReportedModality: " + result.first
+ + " Reported Modality: " + result.first
+ " Status: " + biometricStatus);
if (firstBiometricModality == TYPE_NONE) {
@@ -1421,7 +1427,8 @@
0 /* biometricModality */,
false /* requireConfirmation */,
mCurrentAuthSession.mUserId,
- mCurrentAuthSession.mOpPackageName);
+ mCurrentAuthSession.mOpPackageName,
+ mCurrentAuthSession.mSessionId);
} else {
mPendingAuthSession.mClientReceiver.onError(modality, error, vendorCode);
mPendingAuthSession = null;
@@ -1457,7 +1464,7 @@
}
}
- private void handleOnDismissed(int reason) {
+ private void handleOnDismissed(int reason, @Nullable byte[] credentialAttestation) {
if (mCurrentAuthSession == null) {
Slog.e(TAG, "onDismissed: " + reason + ", auth session null");
return;
@@ -1468,6 +1475,7 @@
try {
switch (reason) {
case BiometricPrompt.DISMISSED_REASON_CREDENTIAL_CONFIRMED:
+ mKeyStore.addAuthToken(credentialAttestation);
case BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED:
case BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED:
if (mCurrentAuthSession.mTokenEscrow != null) {
@@ -1615,7 +1623,8 @@
try {
mStatusBarService.showAuthenticationDialog(mCurrentAuthSession.mBundle,
mInternalReceiver, modality, requireConfirmation, userId,
- mCurrentAuthSession.mOpPackageName);
+ mCurrentAuthSession.mOpPackageName,
+ mCurrentAuthSession.mSessionId);
} catch (RemoteException e) {
Slog.e(TAG, "Remote exception", e);
}
@@ -1700,7 +1709,8 @@
0 /* biometricModality */,
false /* requireConfirmation */,
mCurrentAuthSession.mUserId,
- mCurrentAuthSession.mOpPackageName);
+ mCurrentAuthSession.mOpPackageName,
+ sessionId);
} else {
mPendingAuthSession.mState = STATE_AUTH_CALLED;
for (AuthenticatorWrapper authenticator : mAuthenticators) {
diff --git a/services/core/java/com/android/server/compat/CompatChange.java b/services/core/java/com/android/server/compat/CompatChange.java
index 8687f35..2e9818d 100644
--- a/services/core/java/com/android/server/compat/CompatChange.java
+++ b/services/core/java/com/android/server/compat/CompatChange.java
@@ -63,7 +63,7 @@
private Map<String, Boolean> mPackageOverrides;
public CompatChange(long changeId) {
- this(changeId, null, -1, false, null);
+ this(changeId, null, -1, false, false, null);
}
/**
@@ -74,8 +74,8 @@
* @param disabled If {@code true}, overrides any {@code enableAfterTargetSdk} set.
*/
public CompatChange(long changeId, @Nullable String name, int enableAfterTargetSdk,
- boolean disabled, String description) {
- super(changeId, name, enableAfterTargetSdk, disabled, description);
+ boolean disabled, boolean loggingOnly, String description) {
+ super(changeId, name, enableAfterTargetSdk, disabled, loggingOnly, description);
}
/**
@@ -83,7 +83,7 @@
*/
public CompatChange(Change change) {
super(change.getId(), change.getName(), change.getEnableAfterTargetSdk(),
- change.getDisabled(), change.getDescription());
+ change.getDisabled(), change.getLoggingOnly(), change.getDescription());
}
void registerListener(ChangeListener listener) {
@@ -105,6 +105,10 @@
* @param enabled Whether or not to enable the change.
*/
void addPackageOverride(String pname, boolean enabled) {
+ if (getLoggingOnly()) {
+ throw new IllegalArgumentException(
+ "Can't add overrides for a logging only change " + toString());
+ }
if (mPackageOverrides == null) {
mPackageOverrides = new HashMap<>();
}
@@ -147,6 +151,15 @@
return true;
}
+ /**
+ * Checks whether a change has an override for a package.
+ * @param packageName name of the package
+ * @return true if there is such override
+ */
+ boolean hasOverride(String packageName) {
+ return mPackageOverrides != null && mPackageOverrides.containsKey(packageName);
+ }
+
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ChangeId(")
@@ -160,6 +173,9 @@
if (getDisabled()) {
sb.append("; disabled");
}
+ if (getLoggingOnly()) {
+ sb.append("; loggingOnly");
+ }
if (mPackageOverrides != null && mPackageOverrides.size() > 0) {
sb.append("; packageOverrides=").append(mPackageOverrides);
}
diff --git a/services/core/java/com/android/server/compat/CompatConfig.java b/services/core/java/com/android/server/compat/CompatConfig.java
index 441d9d9..aeaa1fe 100644
--- a/services/core/java/com/android/server/compat/CompatConfig.java
+++ b/services/core/java/com/android/server/compat/CompatConfig.java
@@ -206,6 +206,32 @@
}
/**
+ * Returns whether the change is marked as logging only.
+ */
+ boolean isLoggingOnly(long changeId) {
+ synchronized (mChanges) {
+ CompatChange c = mChanges.get(changeId);
+ if (c == null) {
+ return false;
+ }
+ return c.getLoggingOnly();
+ }
+ }
+
+ /**
+ * Returns whether the change is marked as disabled.
+ */
+ boolean isDisabled(long changeId) {
+ synchronized (mChanges) {
+ CompatChange c = mChanges.get(changeId);
+ if (c == null) {
+ return false;
+ }
+ return c.getDisabled();
+ }
+ }
+
+ /**
* Removes an override previously added via {@link #addOverride(long, String, boolean)}. This
* restores the default behaviour for the given change and app, once any app processes have been
* restarted.
@@ -221,11 +247,13 @@
CompatChange c = mChanges.get(changeId);
try {
if (c != null) {
- OverrideAllowedState allowedState =
- mOverrideValidator.getOverrideAllowedState(changeId, packageName);
- allowedState.enforce(changeId, packageName);
- overrideExists = true;
- c.removePackageOverride(packageName);
+ overrideExists = c.hasOverride(packageName);
+ if (overrideExists) {
+ OverrideAllowedState allowedState =
+ mOverrideValidator.getOverrideAllowedState(changeId, packageName);
+ allowedState.enforce(changeId, packageName);
+ c.removePackageOverride(packageName);
+ }
}
} catch (RemoteException e) {
// Should never occur, since validator is in the same process.
@@ -272,12 +300,14 @@
for (int i = 0; i < mChanges.size(); ++i) {
try {
CompatChange change = mChanges.valueAt(i);
- OverrideAllowedState allowedState =
- mOverrideValidator.getOverrideAllowedState(change.getId(),
- packageName);
- allowedState.enforce(change.getId(), packageName);
- if (change != null) {
- mChanges.valueAt(i).removePackageOverride(packageName);
+ if (change.hasOverride(packageName)) {
+ OverrideAllowedState allowedState =
+ mOverrideValidator.getOverrideAllowedState(change.getId(),
+ packageName);
+ allowedState.enforce(change.getId(), packageName);
+ if (change != null) {
+ mChanges.valueAt(i).removePackageOverride(packageName);
+ }
}
} catch (RemoteException e) {
// Should never occur, since validator is in the same process.
@@ -288,6 +318,63 @@
}
}
+ private long[] getAllowedChangesAfterTargetSdkForPackage(String packageName,
+ int targetSdkVersion)
+ throws RemoteException {
+ LongArray allowed = new LongArray();
+ synchronized (mChanges) {
+ for (int i = 0; i < mChanges.size(); ++i) {
+ try {
+ CompatChange change = mChanges.valueAt(i);
+ if (change.getEnableAfterTargetSdk() != targetSdkVersion) {
+ continue;
+ }
+ OverrideAllowedState allowedState =
+ mOverrideValidator.getOverrideAllowedState(change.getId(),
+ packageName);
+ if (allowedState.state == OverrideAllowedState.ALLOWED) {
+ allowed.add(change.getId());
+ }
+ } catch (RemoteException e) {
+ // Should never occur, since validator is in the same process.
+ throw new RuntimeException("Unable to call override validator!", e);
+ }
+ }
+ }
+ return allowed.toArray();
+ }
+
+ /**
+ * Enables all changes with enabledAfterTargetSdk == {@param targetSdkVersion} for
+ * {@param packageName}.
+ *
+ * @return The number of changes that were toggled.
+ */
+ int enableTargetSdkChangesForPackage(String packageName, int targetSdkVersion)
+ throws RemoteException {
+ long[] changes = getAllowedChangesAfterTargetSdkForPackage(packageName, targetSdkVersion);
+ for (long changeId : changes) {
+ addOverride(changeId, packageName, true);
+ }
+ return changes.length;
+ }
+
+
+ /**
+ * Disables all changes with enabledAfterTargetSdk == {@param targetSdkVersion} for
+ * {@param packageName}.
+ *
+ * @return The number of changes that were toggled.
+ */
+ int disableTargetSdkChangesForPackage(String packageName, int targetSdkVersion)
+ throws RemoteException {
+ long[] changes = getAllowedChangesAfterTargetSdkForPackage(packageName, targetSdkVersion);
+ for (long changeId : changes) {
+ addOverride(changeId, packageName, false);
+ }
+ return changes.length;
+ }
+
boolean registerListener(long changeId, CompatChange.ChangeListener listener) {
boolean alreadyKnown = true;
synchronized (mChanges) {
@@ -365,6 +452,7 @@
change.getName(),
change.getEnableAfterTargetSdk(),
change.getDisabled(),
+ change.getLoggingOnly(),
change.getDescription());
}
return changeInfos;
diff --git a/services/core/java/com/android/server/compat/OverrideValidatorImpl.java b/services/core/java/com/android/server/compat/OverrideValidatorImpl.java
index 4bf606e..f5d6e5a 100644
--- a/services/core/java/com/android/server/compat/OverrideValidatorImpl.java
+++ b/services/core/java/com/android/server/compat/OverrideValidatorImpl.java
@@ -20,6 +20,7 @@
import static com.android.internal.compat.OverrideAllowedState.DISABLED_NON_TARGET_SDK;
import static com.android.internal.compat.OverrideAllowedState.DISABLED_NOT_DEBUGGABLE;
import static com.android.internal.compat.OverrideAllowedState.DISABLED_TARGET_SDK_TOO_HIGH;
+import static com.android.internal.compat.OverrideAllowedState.LOGGING_ONLY_CHANGE;
import static com.android.internal.compat.OverrideAllowedState.PACKAGE_DOES_NOT_EXIST;
import android.content.Context;
@@ -51,12 +52,14 @@
@Override
public OverrideAllowedState getOverrideAllowedState(long changeId, String packageName) {
- boolean debuggableBuild = false;
- boolean finalBuild = false;
- int minTargetSdk = mCompatConfig.minTargetSdkForChangeId(changeId);
+ if (mCompatConfig.isLoggingOnly(changeId)) {
+ return new OverrideAllowedState(LOGGING_ONLY_CHANGE, -1, -1);
+ }
- debuggableBuild = mAndroidBuildClassifier.isDebuggableBuild();
- finalBuild = mAndroidBuildClassifier.isFinalBuild();
+ boolean debuggableBuild = mAndroidBuildClassifier.isDebuggableBuild();
+ boolean finalBuild = mAndroidBuildClassifier.isFinalBuild();
+ int minTargetSdk = mCompatConfig.minTargetSdkForChangeId(changeId);
+ boolean disabled = mCompatConfig.isDisabled(changeId);
// Allow any override for userdebug or eng builds.
if (debuggableBuild) {
@@ -81,12 +84,12 @@
if (!finalBuild) {
return new OverrideAllowedState(ALLOWED, appTargetSdk, minTargetSdk);
}
- // Do not allow overriding non-target sdk gated changes on user builds
- if (minTargetSdk == -1) {
+ // Do not allow overriding default enabled changes on user builds
+ if (minTargetSdk == -1 && !disabled) {
return new OverrideAllowedState(DISABLED_NON_TARGET_SDK, appTargetSdk, minTargetSdk);
}
// Only allow to opt-in for a targetSdk gated change.
- if (applicationInfo.targetSdkVersion < minTargetSdk) {
+ if (disabled || applicationInfo.targetSdkVersion < minTargetSdk) {
return new OverrideAllowedState(ALLOWED, appTargetSdk, minTargetSdk);
}
return new OverrideAllowedState(DISABLED_TARGET_SDK_TOO_HIGH, appTargetSdk, minTargetSdk);
diff --git a/services/core/java/com/android/server/compat/PlatformCompat.java b/services/core/java/com/android/server/compat/PlatformCompat.java
index 821653a..8519b00 100644
--- a/services/core/java/com/android/server/compat/PlatformCompat.java
+++ b/services/core/java/com/android/server/compat/PlatformCompat.java
@@ -166,6 +166,26 @@
}
@Override
+ public int enableTargetSdkChanges(String packageName, int targetSdkVersion)
+ throws RemoteException, SecurityException {
+ checkCompatChangeOverridePermission();
+ int numChanges = mCompatConfig.enableTargetSdkChangesForPackage(packageName,
+ targetSdkVersion);
+ killPackage(packageName);
+ return numChanges;
+ }
+
+ @Override
+ public int disableTargetSdkChanges(String packageName, int targetSdkVersion)
+ throws RemoteException, SecurityException {
+ checkCompatChangeOverridePermission();
+ int numChanges = mCompatConfig.disableTargetSdkChangesForPackage(packageName,
+ targetSdkVersion);
+ killPackage(packageName);
+ return numChanges;
+ }
+
+ @Override
public void clearOverrides(String packageName) throws RemoteException, SecurityException {
checkCompatChangeOverridePermission();
mCompatConfig.removePackageOverrides(packageName);
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index 58b5cba..2f04715 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -32,7 +32,6 @@
import android.net.NetworkInfo;
import android.net.NetworkMonitorManager;
import android.net.NetworkRequest;
-import android.net.NetworkScore;
import android.net.NetworkState;
import android.os.Handler;
import android.os.INetworkManagementService;
@@ -161,10 +160,6 @@
// Whether a captive portal was found during the last network validation attempt.
public boolean lastCaptivePortalDetected;
- // Indicates the captive portal app was opened to show a login UI to the user, but the network
- // has not validated yet.
- public volatile boolean captivePortalValidationPending;
-
// Set to true when partial connectivity was detected.
public boolean partialConnectivity;
@@ -236,10 +231,8 @@
// validated).
private boolean mLingering;
- // This represents the characteristics of a network that affects how good the network is
- // considered for a particular use.
- @NonNull
- private NetworkScore mNetworkScore;
+ // This represents the quality of the network with no clear scale.
+ private int mScore;
// The list of NetworkRequests being satisfied by this Network.
private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<>();
@@ -268,7 +261,7 @@
private final Handler mHandler;
public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
- LinkProperties lp, NetworkCapabilities nc, @NonNull NetworkScore ns, Context context,
+ LinkProperties lp, NetworkCapabilities nc, int score, Context context,
Handler handler, NetworkAgentConfig config, ConnectivityService connService, INetd netd,
IDnsResolver dnsResolver, INetworkManagementService nms, int factorySerialNumber) {
this.messenger = messenger;
@@ -277,7 +270,7 @@
networkInfo = info;
linkProperties = lp;
networkCapabilities = nc;
- mNetworkScore = ns;
+ mScore = score;
clatd = new Nat464Xlat(this, netd, dnsResolver, nms);
mConnService = connService;
mContext = context;
@@ -491,7 +484,7 @@
return ConnectivityConstants.EXPLICITLY_SELECTED_NETWORK_SCORE;
}
- int score = mNetworkScore.getIntExtension(NetworkScore.LEGACY_SCORE);
+ int score = mScore;
if (!lastValidated && !pretendValidated && !ignoreWifiUnvalidationPenalty() && !isVPN()) {
score -= ConnectivityConstants.UNVALIDATED_SCORE_PENALTY;
}
@@ -520,13 +513,8 @@
return getCurrentScore(true);
}
- public void setNetworkScore(@NonNull NetworkScore ns) {
- mNetworkScore = ns;
- }
-
- @NonNull
- public NetworkScore getNetworkScore() {
- return mNetworkScore;
+ public void setScore(final int score) {
+ mScore = score;
}
public NetworkState getNetworkState() {
@@ -646,7 +634,6 @@
+ "acceptUnvalidated{" + networkAgentConfig.acceptUnvalidated + "} "
+ "everCaptivePortalDetected{" + everCaptivePortalDetected + "} "
+ "lastCaptivePortalDetected{" + lastCaptivePortalDetected + "} "
- + "captivePortalValidationPending{" + captivePortalValidationPending + "} "
+ "partialConnectivity{" + partialConnectivity + "} "
+ "acceptPartialConnectivity{" + networkAgentConfig.acceptPartialConnectivity + "} "
+ "clat{" + clatd + "} "
diff --git a/services/core/java/com/android/server/connectivity/NetworkNotificationManager.java b/services/core/java/com/android/server/connectivity/NetworkNotificationManager.java
index 25c761a..0925de8 100644
--- a/services/core/java/com/android/server/connectivity/NetworkNotificationManager.java
+++ b/services/core/java/com/android/server/connectivity/NetworkNotificationManager.java
@@ -51,7 +51,6 @@
LOST_INTERNET(SystemMessage.NOTE_NETWORK_LOST_INTERNET),
NETWORK_SWITCH(SystemMessage.NOTE_NETWORK_SWITCH),
NO_INTERNET(SystemMessage.NOTE_NETWORK_NO_INTERNET),
- LOGGED_IN(SystemMessage.NOTE_NETWORK_LOGGED_IN),
PARTIAL_CONNECTIVITY(SystemMessage.NOTE_NETWORK_PARTIAL_CONNECTIVITY),
SIGN_IN(SystemMessage.NOTE_NETWORK_SIGN_IN),
PRIVATE_DNS_BROKEN(SystemMessage.NOTE_NETWORK_PRIVATE_DNS_BROKEN);
@@ -114,14 +113,10 @@
}
}
- private static int getIcon(int transportType, NotificationType notifyType) {
- if (transportType != TRANSPORT_WIFI) {
- return R.drawable.stat_notify_rssi_in_range;
- }
-
- return notifyType == NotificationType.LOGGED_IN
- ? R.drawable.ic_wifi_signal_4
- : R.drawable.stat_notify_wifi_in_range; // TODO: Distinguish ! from ?.
+ private static int getIcon(int transportType) {
+ return (transportType == TRANSPORT_WIFI)
+ ? R.drawable.stat_notify_wifi_in_range : // TODO: Distinguish ! from ?.
+ R.drawable.stat_notify_rssi_in_range;
}
/**
@@ -185,7 +180,7 @@
Resources r = mContext.getResources();
final CharSequence title;
final CharSequence details;
- int icon = getIcon(transportType, notifyType);
+ int icon = getIcon(transportType);
if (notifyType == NotificationType.NO_INTERNET && transportType == TRANSPORT_WIFI) {
title = r.getString(R.string.wifi_no_internet,
WifiInfo.sanitizeSsid(nai.networkCapabilities.getSSID()));
@@ -235,9 +230,6 @@
details = r.getString(R.string.network_available_sign_in_detailed, name);
break;
}
- } else if (notifyType == NotificationType.LOGGED_IN) {
- title = WifiInfo.sanitizeSsid(nai.networkCapabilities.getSSID());
- details = r.getString(R.string.captive_portal_logged_in_detailed);
} else if (notifyType == NotificationType.NETWORK_SWITCH) {
String fromTransport = getTransportName(transportType);
String toTransport = getTransportName(approximateTransportType(switchToNai));
@@ -379,7 +371,6 @@
case NETWORK_SWITCH:
return 2;
case LOST_INTERNET:
- case LOGGED_IN:
return 1;
default:
return 0;
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index e484ca0..20ffd9f 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -52,7 +52,6 @@
import android.net.IpPrefix;
import android.net.IpSecManager;
import android.net.IpSecManager.IpSecTunnelInterface;
-import android.net.IpSecManager.UdpEncapsulationSocket;
import android.net.IpSecTransform;
import android.net.LinkAddress;
import android.net.LinkProperties;
@@ -952,18 +951,18 @@
|| isVpnServicePreConsented(context, packageName);
}
- private int getAppUid(String app, int userHandle) {
+ private int getAppUid(final String app, final int userHandle) {
if (VpnConfig.LEGACY_VPN.equals(app)) {
return Process.myUid();
}
PackageManager pm = mContext.getPackageManager();
- int result;
- try {
- result = pm.getPackageUidAsUser(app, userHandle);
- } catch (NameNotFoundException e) {
- result = -1;
- }
- return result;
+ return Binder.withCleanCallingIdentity(() -> {
+ try {
+ return pm.getPackageUidAsUser(app, userHandle);
+ } catch (NameNotFoundException e) {
+ return -1;
+ }
+ });
}
private boolean doesPackageTargetAtLeastQ(String packageName) {
@@ -2201,7 +2200,6 @@
/** Signal to ensure shutdown is honored even if a new Network is connected. */
private boolean mIsRunning = true;
- @Nullable private UdpEncapsulationSocket mEncapSocket;
@Nullable private IpSecTunnelInterface mTunnelIface;
@Nullable private IkeSession mSession;
@Nullable private Network mActiveNetwork;
@@ -2352,29 +2350,21 @@
resetIkeState();
mActiveNetwork = network;
- // TODO(b/149356682): Update this based on new IKE API
- mEncapSocket = mIpSecManager.openUdpEncapsulationSocket();
-
- // TODO(b/149356682): Update this based on new IKE API
final IkeSessionParams ikeSessionParams =
- VpnIkev2Utils.buildIkeSessionParams(mProfile, mEncapSocket);
+ VpnIkev2Utils.buildIkeSessionParams(mContext, mProfile, network);
final ChildSessionParams childSessionParams =
VpnIkev2Utils.buildChildSessionParams();
// TODO: Remove the need for adding two unused addresses with
// IPsec tunnels.
+ final InetAddress address = InetAddress.getLocalHost();
mTunnelIface =
mIpSecManager.createIpSecTunnelInterface(
- ikeSessionParams.getServerAddress() /* unused */,
- ikeSessionParams.getServerAddress() /* unused */,
+ address /* unused */,
+ address /* unused */,
network);
mNetd.setInterfaceUp(mTunnelIface.getInterfaceName());
- // Socket must be bound to prevent network switches from causing
- // the IKE teardown to fail/timeout.
- // TODO(b/149356682): Update this based on new IKE API
- network.bindSocket(mEncapSocket.getFileDescriptor());
-
mSession = mIkev2SessionCreator.createIkeSession(
mContext,
ikeSessionParams,
@@ -2459,16 +2449,6 @@
mSession.kill(); // Kill here to make sure all resources are released immediately
mSession = null;
}
-
- // TODO(b/149356682): Update this based on new IKE API
- if (mEncapSocket != null) {
- try {
- mEncapSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "Failed to close encap socket", e);
- }
- mEncapSocket = null;
- }
}
/**
@@ -2583,7 +2563,7 @@
public void exitIfOuterInterfaceIs(String interfaze) {
if (interfaze.equals(mOuterInterface)) {
Log.i(TAG, "Legacy VPN is going down with " + interfaze);
- exit();
+ exitVpnRunner();
}
}
@@ -2592,6 +2572,10 @@
public void exitVpnRunner() {
// We assume that everything is reset after stopping the daemons.
interrupt();
+
+ // Always disconnect. This may be called again in cleanupVpnStateLocked() if
+ // exitVpnRunner() was called from exit(), but it will be a no-op.
+ agentDisconnect();
try {
mContext.unregisterReceiver(mBroadcastReceiver);
} catch (IllegalArgumentException e) {}
@@ -2814,7 +2798,7 @@
} catch (Exception e) {
Log.i(TAG, "Aborting", e);
updateState(DetailedState.FAILED, e.getMessage());
- exit();
+ exitVpnRunner();
}
}
diff --git a/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java b/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java
index 33fc32b..3da304c 100644
--- a/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java
+++ b/services/core/java/com/android/server/connectivity/VpnIkev2Utils.java
@@ -35,10 +35,10 @@
import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_HMAC_SHA1;
import android.annotation.NonNull;
+import android.content.Context;
import android.net.Ikev2VpnProfile;
import android.net.InetAddresses;
import android.net.IpPrefix;
-import android.net.IpSecManager.UdpEncapsulationSocket;
import android.net.IpSecTransform;
import android.net.Network;
import android.net.RouteInfo;
@@ -84,18 +84,14 @@
*/
public class VpnIkev2Utils {
static IkeSessionParams buildIkeSessionParams(
- @NonNull Ikev2VpnProfile profile, @NonNull UdpEncapsulationSocket socket) {
- // TODO(b/149356682): Update this based on new IKE API. Only numeric addresses supported
- // until then. All others throw IAE (caught by caller).
- final InetAddress serverAddr = InetAddresses.parseNumericAddress(profile.getServerAddr());
+ @NonNull Context context, @NonNull Ikev2VpnProfile profile, @NonNull Network network) {
final IkeIdentification localId = parseIkeIdentification(profile.getUserIdentity());
final IkeIdentification remoteId = parseIkeIdentification(profile.getServerAddr());
- // TODO(b/149356682): Update this based on new IKE API.
final IkeSessionParams.Builder ikeOptionsBuilder =
- new IkeSessionParams.Builder()
- .setServerAddress(serverAddr)
- .setUdpEncapsulationSocket(socket)
+ new IkeSessionParams.Builder(context)
+ .setServerHostname(profile.getServerAddr())
+ .setNetwork(network)
.setLocalIdentification(localId)
.setRemoteIdentification(remoteId);
setIkeAuth(profile, ikeOptionsBuilder);
diff --git a/services/core/java/com/android/server/content/SyncStorageEngine.java b/services/core/java/com/android/server/content/SyncStorageEngine.java
index 8c510b7..e9c4b51 100644
--- a/services/core/java/com/android/server/content/SyncStorageEngine.java
+++ b/services/core/java/com/android/server/content/SyncStorageEngine.java
@@ -472,8 +472,7 @@
private int mSyncRandomOffset;
- // STOPSHIP: b/143656271 this should be true on launch
- private static final boolean DELETE_LEGACY_PARCEL_FILES = false;
+ private static final boolean DELETE_LEGACY_PARCEL_FILES = true;
private static final String LEGACY_STATUS_FILE_NAME = "status.bin";
private static final String LEGACY_STATISTICS_FILE_NAME = "stats.bin";
@@ -2076,7 +2075,7 @@
}
// if upgrade to proto was successful, delete parcel file
- if (DELETE_LEGACY_PARCEL_FILES && mStatusFile.exists()) {
+ if (DELETE_LEGACY_PARCEL_FILES && parcelStatus.exists() && mStatusFile.exists()) {
parcelStatus.delete();
}
}
@@ -2475,7 +2474,7 @@
}
// if upgrade to proto was successful, delete parcel file
- if (DELETE_LEGACY_PARCEL_FILES && mStatisticsFile.exists()) {
+ if (DELETE_LEGACY_PARCEL_FILES && parcelStats.exists() && mStatisticsFile.exists()) {
parcelStats.delete();
}
}
diff --git a/services/core/java/com/android/server/hdmi/TEST_MAPPING b/services/core/java/com/android/server/hdmi/TEST_MAPPING
new file mode 100644
index 0000000..7245ec4
--- /dev/null
+++ b/services/core/java/com/android/server/hdmi/TEST_MAPPING
@@ -0,0 +1,34 @@
+{
+ "presubmit": [
+ {
+ "name": "FrameworksServicesTests",
+ "options": [
+ {
+ "include-filter": "com.android.server.hdmi"
+ },
+ {
+ "include-annotation": "android.platform.test.annotations.Presubmit"
+ },
+ {
+ "exclude-annotation": "androidx.test.filters.FlakyTest"
+ },
+ {
+ "exclude-annotation": "org.junit.Ignore"
+ }
+ ]
+ }
+ ],
+ "postsubmit": [
+ {
+ "name": "FrameworksServicesTests",
+ "options": [
+ {
+ "include-filter": "com.android.server.hdmi"
+ },
+ {
+ "exclude-annotation": "org.junit.Ignore"
+ }
+ ]
+ }
+ ]
+}
diff --git a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
index f773825..44ab438 100644
--- a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
+++ b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
@@ -50,9 +50,9 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
+import android.os.RemoteException;
import android.os.UserHandle;
import android.provider.Settings;
-import android.security.FileIntegrityManager;
import android.util.Slog;
import android.util.apk.SourceStampVerificationResult;
import android.util.apk.SourceStampVerifier;
@@ -70,8 +70,11 @@
import java.io.ByteArrayInputStream;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
@@ -86,6 +89,8 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/** Implementation of {@link AppIntegrityManagerService}. */
public class AppIntegrityManagerServiceImpl extends IAppIntegrityManager.Stub {
@@ -122,7 +127,6 @@
private final PackageManagerInternal mPackageManagerInternal;
private final RuleEvaluationEngine mEvaluationEngine;
private final IntegrityFileManager mIntegrityFileManager;
- private final FileIntegrityManager mFileIntegrityManager;
/** Create an instance of {@link AppIntegrityManagerServiceImpl}. */
public static AppIntegrityManagerServiceImpl create(Context context) {
@@ -134,7 +138,6 @@
LocalServices.getService(PackageManagerInternal.class),
RuleEvaluationEngine.getRuleEvaluationEngine(),
IntegrityFileManager.getInstance(),
- (FileIntegrityManager) context.getSystemService(Context.FILE_INTEGRITY_SERVICE),
handlerThread.getThreadHandler());
}
@@ -144,13 +147,11 @@
PackageManagerInternal packageManagerInternal,
RuleEvaluationEngine evaluationEngine,
IntegrityFileManager integrityFileManager,
- FileIntegrityManager fileIntegrityManager,
Handler handler) {
mContext = context;
mPackageManagerInternal = packageManagerInternal;
mEvaluationEngine = evaluationEngine;
mIntegrityFileManager = integrityFileManager;
- mFileIntegrityManager = fileIntegrityManager;
mHandler = handler;
IntentFilter integrityVerificationFilter = new IntentFilter();
@@ -244,6 +245,11 @@
return new ParceledListSlice<>(rules);
}
+ @Override
+ public List<String> getWhitelistedRuleProviders() throws RemoteException {
+ return getAllowedRuleProviders();
+ }
+
private void handleIntegrityVerification(Intent intent) {
int verificationId = intent.getIntExtra(EXTRA_VERIFICATION_ID, -1);
@@ -472,10 +478,27 @@
if (installationPath == null) {
throw new IllegalArgumentException("Installation path is null, package not found");
}
- SourceStampVerificationResult sourceStampVerificationResult =
- SourceStampVerifier.verify(installationPath.getAbsolutePath());
+
+ SourceStampVerificationResult sourceStampVerificationResult;
+ if (installationPath.isDirectory()) {
+ try (Stream<Path> filesList = Files.list(installationPath.toPath())) {
+ List<String> apkFiles =
+ filesList
+ .map(path -> path.toAbsolutePath().toString())
+ .collect(Collectors.toList());
+ sourceStampVerificationResult = SourceStampVerifier.verify(apkFiles);
+ } catch (IOException e) {
+ throw new IllegalArgumentException("Could not read APK directory");
+ }
+ } else {
+ sourceStampVerificationResult =
+ SourceStampVerifier.verify(installationPath.getAbsolutePath());
+ }
+
appInstallMetadata.setIsStampPresent(sourceStampVerificationResult.isPresent());
appInstallMetadata.setIsStampVerified(sourceStampVerificationResult.isVerified());
+ // A verified stamp is set to be trusted.
+ appInstallMetadata.setIsStampTrusted(sourceStampVerificationResult.isVerified());
if (sourceStampVerificationResult.isVerified()) {
X509Certificate sourceStampCertificate =
(X509Certificate) sourceStampVerificationResult.getCertificate();
@@ -488,16 +511,6 @@
throw new IllegalArgumentException(
"Error computing source stamp certificate digest", e);
}
- // Checks if the source stamp certificate is trusted.
- try {
- appInstallMetadata.setIsStampTrusted(
- mFileIntegrityManager.isApkVeritySupported()
- && mFileIntegrityManager.isAppSourceCertificateTrusted(
- sourceStampCertificate));
- } catch (CertificateEncodingException e) {
- throw new IllegalArgumentException(
- "Error checking if source stamp certificate is trusted", e);
- }
}
}
diff --git a/services/core/java/com/android/server/integrity/TEST_MAPPING b/services/core/java/com/android/server/integrity/TEST_MAPPING
index ca7f396..4959204 100644
--- a/services/core/java/com/android/server/integrity/TEST_MAPPING
+++ b/services/core/java/com/android/server/integrity/TEST_MAPPING
@@ -7,6 +7,14 @@
"include-filter": "com.android.server.integrity."
}
]
+ },
+ {
+ "name": "GtsSecurityHostTestCases",
+ "options": [
+ {
+ "include-filter": "com.google.android.security.gts.AppIntegrityManagerTest"
+ }
+ ]
}
]
}
diff --git a/services/core/java/com/android/server/location/CountryDetectorBase.java b/services/core/java/com/android/server/location/CountryDetectorBase.java
index b158388..682b104 100644
--- a/services/core/java/com/android/server/location/CountryDetectorBase.java
+++ b/services/core/java/com/android/server/location/CountryDetectorBase.java
@@ -31,7 +31,7 @@
* @hide
*/
public abstract class CountryDetectorBase {
- private static final String FEATURE_ID = "CountryDetector";
+ private static final String ATTRIBUTION_TAG = "CountryDetector";
protected final Handler mHandler;
protected final Context mContext;
@@ -39,7 +39,7 @@
protected Country mDetectedCountry;
public CountryDetectorBase(Context context) {
- mContext = context.createFeatureContext(FEATURE_ID);
+ mContext = context.createAttributionContext(ATTRIBUTION_TAG);
mHandler = new Handler();
}
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index 6faf674..c1c3760 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -1572,6 +1572,24 @@
"This operation requires secure lock screen feature");
}
checkWritePermission(userId);
+
+ // When changing credential for profiles with unified challenge, some callers
+ // will pass in empty credential while others will pass in the credential of
+ // the parent user. setLockCredentialInternal() handles the formal case (empty
+ // credential) correctly but not the latter. As a stopgap fix, convert the latter
+ // case to the formal. The long-term fix would be fixing LSS such that it should
+ // accept only the parent user credential on its public API interfaces, swap it
+ // with the profile's random credential at that API boundary (i.e. here) and make
+ // sure LSS internally does not special case profile with unififed challenge: b/80170828.
+ if (!savedCredential.isNone() && isManagedProfileWithUnifiedLock(userId)) {
+ // Verify the parent credential again, to make sure we have a fresh enough
+ // auth token such that getDecryptedPasswordForTiedProfile() inside
+ // setLockCredentialInternal() can function correctly.
+ verifyCredential(savedCredential, /* challenge */ 0,
+ mUserManager.getProfileParent(userId).id);
+ savedCredential.zeroize();
+ savedCredential = LockscreenCredential.createNone();
+ }
synchronized (mSeparateChallengeLock) {
if (!setLockCredentialInternal(credential, savedCredential,
userId, /* isLockTiedToParent= */ false)) {
@@ -1627,6 +1645,7 @@
// get credential from keystore when managed profile has unified lock
if (savedCredential.isNone()) {
try {
+ //TODO: remove as part of b/80170828
savedCredential = getDecryptedPasswordForTiedProfile(userId);
} catch (FileNotFoundException e) {
Slog.i(TAG, "Child profile key not found");
@@ -2876,6 +2895,7 @@
if (savedCredential.isNone() && isManagedProfileWithUnifiedLock(userId)) {
// get credential from keystore when managed profile has unified lock
try {
+ //TODO: remove as part of b/80170828
savedCredential = getDecryptedPasswordForTiedProfile(userId);
} catch (FileNotFoundException e) {
Slog.i(TAG, "Child profile key not found");
diff --git a/services/core/java/com/android/server/media/MediaRoute2Provider.java b/services/core/java/com/android/server/media/MediaRoute2Provider.java
index 4cb1ed9..2721678 100644
--- a/services/core/java/com/android/server/media/MediaRoute2Provider.java
+++ b/services/core/java/com/android/server/media/MediaRoute2Provider.java
@@ -51,17 +51,17 @@
mCallback = callback;
}
- public abstract void requestCreateSession(String packageName, String routeId, long requestId,
+ public abstract void requestCreateSession(long requestId, String packageName, String routeId,
@Nullable Bundle sessionHints);
- public abstract void releaseSession(String sessionId, long requestId);
+ public abstract void releaseSession(long requestId, String sessionId);
public abstract void updateDiscoveryPreference(RouteDiscoveryPreference discoveryPreference);
- public abstract void selectRoute(String sessionId, String routeId, long requestId);
- public abstract void deselectRoute(String sessionId, String routeId, long requestId);
- public abstract void transferToRoute(String sessionId, String routeId, long requestId);
+ public abstract void selectRoute(long requestId, String sessionId, String routeId);
+ public abstract void deselectRoute(long requestId, String sessionId, String routeId);
+ public abstract void transferToRoute(long requestId, String sessionId, String routeId);
- public abstract void setRouteVolume(String routeId, int volume, long requestId);
- public abstract void setSessionVolume(String sessionId, int volume, long requestId);
+ public abstract void setRouteVolume(long requestId, String routeId, int volume);
+ public abstract void setSessionVolume(long requestId, String sessionId, int volume);
@NonNull
public String getUniqueId() {
@@ -110,7 +110,7 @@
public interface Callback {
void onProviderStateChanged(@Nullable MediaRoute2Provider provider);
void onSessionCreated(@NonNull MediaRoute2Provider provider,
- @Nullable RoutingSessionInfo sessionInfo, long requestId);
+ long requestId, @Nullable RoutingSessionInfo sessionInfo);
void onSessionUpdated(@NonNull MediaRoute2Provider provider,
@NonNull RoutingSessionInfo sessionInfo);
void onSessionReleased(@NonNull MediaRoute2Provider provider,
diff --git a/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java b/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java
index 36a7bd9..2aa53cc 100644
--- a/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java
+++ b/services/core/java/com/android/server/media/MediaRoute2ProviderServiceProxy.java
@@ -60,6 +60,8 @@
private Connection mActiveConnection;
private boolean mConnectionReady;
+ private RouteDiscoveryPreference mPendingDiscoveryPreference = null;
+
MediaRoute2ProviderServiceProxy(@NonNull Context context, @NonNull ComponentName componentName,
int userId) {
super(componentName);
@@ -78,18 +80,18 @@
}
@Override
- public void requestCreateSession(String packageName, String routeId, long requestId,
+ public void requestCreateSession(long requestId, String packageName, String routeId,
Bundle sessionHints) {
if (mConnectionReady) {
- mActiveConnection.requestCreateSession(packageName, routeId, requestId, sessionHints);
+ mActiveConnection.requestCreateSession(requestId, packageName, routeId, sessionHints);
updateBinding();
}
}
@Override
- public void releaseSession(String sessionId, long requestId) {
+ public void releaseSession(long requestId, String sessionId) {
if (mConnectionReady) {
- mActiveConnection.releaseSession(sessionId, requestId);
+ mActiveConnection.releaseSession(requestId, sessionId);
updateBinding();
}
}
@@ -99,42 +101,44 @@
if (mConnectionReady) {
mActiveConnection.updateDiscoveryPreference(discoveryPreference);
updateBinding();
+ } else {
+ mPendingDiscoveryPreference = discoveryPreference;
}
}
@Override
- public void selectRoute(String sessionId, String routeId, long requestId) {
+ public void selectRoute(long requestId, String sessionId, String routeId) {
if (mConnectionReady) {
- mActiveConnection.selectRoute(sessionId, routeId, requestId);
+ mActiveConnection.selectRoute(requestId, sessionId, routeId);
}
}
@Override
- public void deselectRoute(String sessionId, String routeId, long requestId) {
+ public void deselectRoute(long requestId, String sessionId, String routeId) {
if (mConnectionReady) {
- mActiveConnection.deselectRoute(sessionId, routeId, requestId);
+ mActiveConnection.deselectRoute(requestId, sessionId, routeId);
}
}
@Override
- public void transferToRoute(String sessionId, String routeId, long requestId) {
+ public void transferToRoute(long requestId, String sessionId, String routeId) {
if (mConnectionReady) {
- mActiveConnection.transferToRoute(sessionId, routeId, requestId);
+ mActiveConnection.transferToRoute(requestId, sessionId, routeId);
}
}
@Override
- public void setRouteVolume(String routeId, int volume, long requestId) {
+ public void setRouteVolume(long requestId, String routeId, int volume) {
if (mConnectionReady) {
- mActiveConnection.setRouteVolume(routeId, volume, requestId);
+ mActiveConnection.setRouteVolume(requestId, routeId, volume);
updateBinding();
}
}
@Override
- public void setSessionVolume(String sessionId, int volume, long requestId) {
+ public void setSessionVolume(long requestId, String sessionId, int volume) {
if (mConnectionReady) {
- mActiveConnection.setSessionVolume(sessionId, volume, requestId);
+ mActiveConnection.setSessionVolume(requestId, sessionId, volume);
updateBinding();
}
}
@@ -271,6 +275,10 @@
private void onConnectionReady(Connection connection) {
if (mActiveConnection == connection) {
mConnectionReady = true;
+ if (mPendingDiscoveryPreference != null) {
+ updateDiscoveryPreference(mPendingDiscoveryPreference);
+ mPendingDiscoveryPreference = null;
+ }
}
}
@@ -294,8 +302,8 @@
setAndNotifyProviderState(providerInfo);
}
- private void onSessionCreated(Connection connection, RoutingSessionInfo sessionInfo,
- long requestId) {
+ private void onSessionCreated(Connection connection, long requestId,
+ RoutingSessionInfo sessionInfo) {
if (mActiveConnection != connection) {
return;
}
@@ -325,7 +333,7 @@
return;
}
- mCallback.onSessionCreated(this, sessionInfo, requestId);
+ mCallback.onSessionCreated(this, requestId, sessionInfo);
}
private void onSessionUpdated(Connection connection, RoutingSessionInfo sessionInfo) {
@@ -452,18 +460,18 @@
mCallbackStub.dispose();
}
- public void requestCreateSession(String packageName, String routeId, long requestId,
+ public void requestCreateSession(long requestId, String packageName, String routeId,
Bundle sessionHints) {
try {
- mService.requestCreateSession(packageName, routeId, requestId, sessionHints);
+ mService.requestCreateSession(requestId, packageName, routeId, sessionHints);
} catch (RemoteException ex) {
Slog.e(TAG, "requestCreateSession: Failed to deliver request.");
}
}
- public void releaseSession(String sessionId, long requestId) {
+ public void releaseSession(long requestId, String sessionId) {
try {
- mService.releaseSession(sessionId, requestId);
+ mService.releaseSession(requestId, sessionId);
} catch (RemoteException ex) {
Slog.e(TAG, "releaseSession: Failed to deliver request.");
}
@@ -477,41 +485,41 @@
}
}
- public void selectRoute(String sessionId, String routeId, long requestId) {
+ public void selectRoute(long requestId, String sessionId, String routeId) {
try {
- mService.selectRoute(sessionId, routeId, requestId);
+ mService.selectRoute(requestId, sessionId, routeId);
} catch (RemoteException ex) {
Slog.e(TAG, "selectRoute: Failed to deliver request.", ex);
}
}
- public void deselectRoute(String sessionId, String routeId, long requestId) {
+ public void deselectRoute(long requestId, String sessionId, String routeId) {
try {
- mService.deselectRoute(sessionId, routeId, requestId);
+ mService.deselectRoute(requestId, sessionId, routeId);
} catch (RemoteException ex) {
Slog.e(TAG, "deselectRoute: Failed to deliver request.", ex);
}
}
- public void transferToRoute(String sessionId, String routeId, long requestId) {
+ public void transferToRoute(long requestId, String sessionId, String routeId) {
try {
- mService.transferToRoute(sessionId, routeId, requestId);
+ mService.transferToRoute(requestId, sessionId, routeId);
} catch (RemoteException ex) {
Slog.e(TAG, "transferToRoute: Failed to deliver request.", ex);
}
}
- public void setRouteVolume(String routeId, int volume, long requestId) {
+ public void setRouteVolume(long requestId, String routeId, int volume) {
try {
- mService.setRouteVolume(routeId, volume, requestId);
+ mService.setRouteVolume(requestId, routeId, volume);
} catch (RemoteException ex) {
Slog.e(TAG, "setRouteVolume: Failed to deliver request.", ex);
}
}
- public void setSessionVolume(String sessionId, int volume, long requestId) {
+ public void setSessionVolume(long requestId, String sessionId, int volume) {
try {
- mService.setSessionVolume(sessionId, volume, requestId);
+ mService.setSessionVolume(requestId, sessionId, volume);
} catch (RemoteException ex) {
Slog.e(TAG, "setSessionVolume: Failed to deliver request.", ex);
}
@@ -526,8 +534,8 @@
mHandler.post(() -> onProviderStateUpdated(Connection.this, providerInfo));
}
- void postSessionCreated(RoutingSessionInfo sessionInfo, long requestId) {
- mHandler.post(() -> onSessionCreated(Connection.this, sessionInfo, requestId));
+ void postSessionCreated(long requestId, RoutingSessionInfo sessionInfo) {
+ mHandler.post(() -> onSessionCreated(Connection.this, requestId, sessionInfo));
}
void postSessionUpdated(RoutingSessionInfo sessionInfo) {
@@ -564,10 +572,10 @@
}
@Override
- public void notifySessionCreated(RoutingSessionInfo sessionInfo, long requestId) {
+ public void notifySessionCreated(long requestId, RoutingSessionInfo sessionInfo) {
Connection connection = mConnectionRef.get();
if (connection != null) {
- connection.postSessionCreated(sessionInfo, requestId);
+ connection.postSessionCreated(requestId, sessionInfo);
}
}
diff --git a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
index 16f2add..4b925ef 100644
--- a/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
+++ b/services/core/java/com/android/server/media/MediaRouter2ServiceImpl.java
@@ -216,15 +216,15 @@
}
}
- public void requestCreateSessionWithRouter2(IMediaRouter2 router, MediaRoute2Info route,
- int requestId, Bundle sessionHints) {
+ public void requestCreateSessionWithRouter2(IMediaRouter2 router, int requestId,
+ MediaRoute2Info route, Bundle sessionHints) {
Objects.requireNonNull(router, "router must not be null");
Objects.requireNonNull(route, "route must not be null");
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- requestCreateSessionWithRouter2Locked(router, route, requestId, sessionHints);
+ requestCreateSessionWithRouter2Locked(requestId, router, route, sessionHints);
}
} finally {
Binder.restoreCallingIdentity(token);
@@ -370,23 +370,23 @@
}
}
- public void setRouteVolumeWithManager(IMediaRouter2Manager manager,
- MediaRoute2Info route, int volume, int requestId) {
+ public void setRouteVolumeWithManager(IMediaRouter2Manager manager, int requestId,
+ MediaRoute2Info route, int volume) {
Objects.requireNonNull(manager, "manager must not be null");
Objects.requireNonNull(route, "route must not be null");
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- setRouteVolumeWithManagerLocked(manager, route, volume, requestId);
+ setRouteVolumeWithManagerLocked(requestId, manager, route, volume);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
- public void requestCreateSessionWithManager(IMediaRouter2Manager manager, String packageName,
- MediaRoute2Info route, int requestId) {
+ public void requestCreateSessionWithManager(IMediaRouter2Manager manager, int requestId,
+ String packageName, MediaRoute2Info route) {
Objects.requireNonNull(manager, "manager must not be null");
if (TextUtils.isEmpty(packageName)) {
throw new IllegalArgumentException("packageName must not be empty");
@@ -395,15 +395,15 @@
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- requestCreateSessionWithManagerLocked(manager, packageName, route, requestId);
+ requestCreateSessionWithManagerLocked(requestId, manager, packageName, route);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
- public void selectRouteWithManager(IMediaRouter2Manager manager, String uniqueSessionId,
- MediaRoute2Info route, int requestId) {
+ public void selectRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String uniqueSessionId, MediaRoute2Info route) {
Objects.requireNonNull(manager, "manager must not be null");
if (TextUtils.isEmpty(uniqueSessionId)) {
throw new IllegalArgumentException("uniqueSessionId must not be empty");
@@ -413,15 +413,15 @@
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- selectRouteWithManagerLocked(manager, uniqueSessionId, route, requestId);
+ selectRouteWithManagerLocked(requestId, manager, uniqueSessionId, route);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
- public void deselectRouteWithManager(IMediaRouter2Manager manager, String uniqueSessionId,
- MediaRoute2Info route, int requestId) {
+ public void deselectRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String uniqueSessionId, MediaRoute2Info route) {
Objects.requireNonNull(manager, "manager must not be null");
if (TextUtils.isEmpty(uniqueSessionId)) {
throw new IllegalArgumentException("uniqueSessionId must not be empty");
@@ -431,15 +431,15 @@
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- deselectRouteWithManagerLocked(manager, uniqueSessionId, route, requestId);
+ deselectRouteWithManagerLocked(requestId, manager, uniqueSessionId, route);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
- public void transferToRouteWithManager(IMediaRouter2Manager manager, String uniqueSessionId,
- MediaRoute2Info route, int requestId) {
+ public void transferToRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String uniqueSessionId, MediaRoute2Info route) {
Objects.requireNonNull(manager, "manager must not be null");
if (TextUtils.isEmpty(uniqueSessionId)) {
throw new IllegalArgumentException("uniqueSessionId must not be empty");
@@ -449,15 +449,15 @@
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- transferToRouteWithManagerLocked(manager, uniqueSessionId, route, requestId);
+ transferToRouteWithManagerLocked(requestId, manager, uniqueSessionId, route);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
- public void setSessionVolumeWithManager(IMediaRouter2Manager manager,
- String uniqueSessionId, int volume, int requestId) {
+ public void setSessionVolumeWithManager(IMediaRouter2Manager manager, int requestId,
+ String uniqueSessionId, int volume) {
Objects.requireNonNull(manager, "manager must not be null");
if (TextUtils.isEmpty(uniqueSessionId)) {
throw new IllegalArgumentException("uniqueSessionId must not be empty");
@@ -466,15 +466,15 @@
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- setSessionVolumeWithManagerLocked(manager, uniqueSessionId, volume, requestId);
+ setSessionVolumeWithManagerLocked(requestId, manager, uniqueSessionId, volume);
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
- public void releaseSessionWithManager(IMediaRouter2Manager manager, String uniqueSessionId,
- int requestId) {
+ public void releaseSessionWithManager(IMediaRouter2Manager manager, int requestId,
+ String uniqueSessionId) {
Objects.requireNonNull(manager, "manager must not be null");
if (TextUtils.isEmpty(uniqueSessionId)) {
throw new IllegalArgumentException("uniqueSessionId must not be empty");
@@ -483,7 +483,7 @@
final long token = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
- releaseSessionWithManagerLocked(manager, uniqueSessionId, requestId);
+ releaseSessionWithManagerLocked(requestId, manager, uniqueSessionId);
}
} finally {
Binder.restoreCallingIdentity(token);
@@ -591,12 +591,13 @@
if (routerRecord != null) {
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::setRouteVolumeOnHandler,
- routerRecord.mUserRecord.mHandler, route, volume, DUMMY_REQUEST_ID));
+ routerRecord.mUserRecord.mHandler,
+ DUMMY_REQUEST_ID, route, volume));
}
}
- private void requestCreateSessionWithRouter2Locked(@NonNull IMediaRouter2 router,
- @NonNull MediaRoute2Info route, int requestId, @Nullable Bundle sessionHints) {
+ private void requestCreateSessionWithRouter2Locked(int requestId, @NonNull IMediaRouter2 router,
+ @NonNull MediaRoute2Info route, @Nullable Bundle sessionHints) {
final IBinder binder = router.asBinder();
final RouterRecord routerRecord = mAllRouterRecords.get(binder);
@@ -608,7 +609,7 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::requestCreateSessionOnHandler,
routerRecord.mUserRecord.mHandler,
- routerRecord, /* managerRecord= */ null, route, uniqueRequestId,
+ uniqueRequestId, routerRecord, /* managerRecord= */ null, route,
sessionHints));
}
@@ -623,8 +624,8 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::selectRouteOnHandler,
- routerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId, route,
- DUMMY_REQUEST_ID));
+ routerRecord.mUserRecord.mHandler,
+ DUMMY_REQUEST_ID, routerRecord, uniqueSessionId, route));
}
private void deselectRouteWithRouter2Locked(@NonNull IMediaRouter2 router,
@@ -638,8 +639,8 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::deselectRouteOnHandler,
- routerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId, route,
- DUMMY_REQUEST_ID));
+ routerRecord.mUserRecord.mHandler,
+ DUMMY_REQUEST_ID, routerRecord, uniqueSessionId, route));
}
private void transferToRouteWithRouter2Locked(@NonNull IMediaRouter2 router,
@@ -653,8 +654,8 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::transferToRouteOnHandler,
- routerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId, route,
- DUMMY_REQUEST_ID));
+ routerRecord.mUserRecord.mHandler,
+ DUMMY_REQUEST_ID, routerRecord, uniqueSessionId, route));
}
private void setSessionVolumeWithRouter2Locked(@NonNull IMediaRouter2 router,
@@ -668,8 +669,8 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::setSessionVolumeOnHandler,
- routerRecord.mUserRecord.mHandler, uniqueSessionId, volume,
- DUMMY_REQUEST_ID));
+ routerRecord.mUserRecord.mHandler,
+ DUMMY_REQUEST_ID, uniqueSessionId, volume));
}
private void releaseSessionWithRouter2Locked(@NonNull IMediaRouter2 router,
@@ -683,8 +684,8 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::releaseSessionOnHandler,
- routerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId,
- DUMMY_REQUEST_ID));
+ routerRecord.mUserRecord.mHandler,
+ DUMMY_REQUEST_ID, routerRecord, uniqueSessionId));
}
////////////////////////////////////////////////////////////
@@ -756,8 +757,9 @@
disposeUserIfNeededLocked(userRecord); // since manager removed from user
}
- private void setRouteVolumeWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull MediaRoute2Info route, int volume, int requestId) {
+ private void setRouteVolumeWithManagerLocked(int requestId,
+ @NonNull IMediaRouter2Manager manager,
+ @NonNull MediaRoute2Info route, int volume) {
final IBinder binder = manager.asBinder();
ManagerRecord managerRecord = mAllManagerRecords.get(binder);
@@ -768,11 +770,13 @@
long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
managerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::setRouteVolumeOnHandler,
- managerRecord.mUserRecord.mHandler, route, volume, uniqueRequestId));
+ managerRecord.mUserRecord.mHandler,
+ uniqueRequestId, route, volume));
}
- private void requestCreateSessionWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull String packageName, @NonNull MediaRoute2Info route, int requestId) {
+ private void requestCreateSessionWithManagerLocked(int requestId,
+ @NonNull IMediaRouter2Manager manager,
+ @NonNull String packageName, @NonNull MediaRoute2Info route) {
ManagerRecord managerRecord = mAllManagerRecords.get(manager.asBinder());
if (managerRecord == null || !managerRecord.mTrusted) {
return;
@@ -789,12 +793,12 @@
routerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::requestCreateSessionOnHandler,
routerRecord.mUserRecord.mHandler,
- routerRecord, managerRecord, route, uniqueRequestId,
+ uniqueRequestId, routerRecord, managerRecord, route,
/* sessionHints= */ null));
}
- private void selectRouteWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route, int requestId) {
+ private void selectRouteWithManagerLocked(int requestId, @NonNull IMediaRouter2Manager manager,
+ @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route) {
final IBinder binder = manager.asBinder();
ManagerRecord managerRecord = mAllManagerRecords.get(binder);
@@ -809,12 +813,13 @@
long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
managerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::selectRouteOnHandler,
- managerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId, route,
- uniqueRequestId));
+ managerRecord.mUserRecord.mHandler,
+ uniqueRequestId, routerRecord, uniqueSessionId, route));
}
- private void deselectRouteWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route, int requestId) {
+ private void deselectRouteWithManagerLocked(int requestId,
+ @NonNull IMediaRouter2Manager manager,
+ @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route) {
final IBinder binder = manager.asBinder();
ManagerRecord managerRecord = mAllManagerRecords.get(binder);
@@ -829,12 +834,13 @@
long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
managerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::deselectRouteOnHandler,
- managerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId, route,
- uniqueRequestId));
+ managerRecord.mUserRecord.mHandler,
+ uniqueRequestId, routerRecord, uniqueSessionId, route));
}
- private void transferToRouteWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route, int requestId) {
+ private void transferToRouteWithManagerLocked(int requestId,
+ @NonNull IMediaRouter2Manager manager,
+ @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route) {
final IBinder binder = manager.asBinder();
ManagerRecord managerRecord = mAllManagerRecords.get(binder);
@@ -849,12 +855,13 @@
long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
managerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::transferToRouteOnHandler,
- managerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId, route,
- uniqueRequestId));
+ managerRecord.mUserRecord.mHandler,
+ uniqueRequestId, routerRecord, uniqueSessionId, route));
}
- private void setSessionVolumeWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull String uniqueSessionId, int volume, int requestId) {
+ private void setSessionVolumeWithManagerLocked(int requestId,
+ @NonNull IMediaRouter2Manager manager,
+ @NonNull String uniqueSessionId, int volume) {
final IBinder binder = manager.asBinder();
ManagerRecord managerRecord = mAllManagerRecords.get(binder);
@@ -865,12 +872,13 @@
long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
managerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::setSessionVolumeOnHandler,
- managerRecord.mUserRecord.mHandler, uniqueSessionId, volume,
- uniqueRequestId));
+ managerRecord.mUserRecord.mHandler,
+ uniqueRequestId, uniqueSessionId, volume));
}
- private void releaseSessionWithManagerLocked(@NonNull IMediaRouter2Manager manager,
- @NonNull String uniqueSessionId, int requestId) {
+ private void releaseSessionWithManagerLocked(int requestId,
+ @NonNull IMediaRouter2Manager manager,
+ @NonNull String uniqueSessionId) {
final IBinder binder = manager.asBinder();
ManagerRecord managerRecord = mAllManagerRecords.get(binder);
@@ -887,8 +895,8 @@
long uniqueRequestId = toUniqueRequestId(managerRecord.mManagerId, requestId);
managerRecord.mUserRecord.mHandler.sendMessage(
obtainMessage(UserHandler::releaseSessionOnHandler,
- managerRecord.mUserRecord.mHandler, routerRecord, uniqueSessionId,
- uniqueRequestId));
+ managerRecord.mUserRecord.mHandler,
+ uniqueRequestId, routerRecord, uniqueSessionId));
}
////////////////////////////////////////////////////////////
@@ -925,8 +933,8 @@
}
}
- static long toUniqueRequestId(int routerOrManagerId, int originalRequestId) {
- return ((long) routerOrManagerId << 32) | originalRequestId;
+ static long toUniqueRequestId(int requesterId, int originalRequestId) {
+ return ((long) requesterId << 32) | originalRequestId;
}
static int toRequesterId(long uniqueRequestId) {
@@ -1104,9 +1112,9 @@
@Override
public void onSessionCreated(@NonNull MediaRoute2Provider provider,
- @NonNull RoutingSessionInfo sessionInfo, long requestId) {
+ long requestId, @NonNull RoutingSessionInfo sessionInfo) {
sendMessage(PooledLambda.obtainMessage(UserHandler::onSessionCreatedOnHandler,
- this, provider, sessionInfo, requestId));
+ this, provider, requestId, sessionInfo));
}
@@ -1219,9 +1227,9 @@
return -1;
}
- private void requestCreateSessionOnHandler(@NonNull RouterRecord routerRecord,
- @Nullable ManagerRecord managerRecord, @NonNull MediaRoute2Info route,
- long requestId, @Nullable Bundle sessionHints) {
+ private void requestCreateSessionOnHandler(long requestId,
+ @NonNull RouterRecord routerRecord, @Nullable ManagerRecord managerRecord,
+ @NonNull MediaRoute2Info route, @Nullable Bundle sessionHints) {
final MediaRoute2Provider provider = findProvider(route.getProviderId());
if (provider == null) {
@@ -1231,18 +1239,17 @@
return;
}
- // TODO: Apply timeout for each request (How many seconds should we wait?)
SessionCreationRequest request =
- new SessionCreationRequest(routerRecord, managerRecord, route, requestId);
+ new SessionCreationRequest(routerRecord, requestId, route, managerRecord);
mSessionCreationRequests.add(request);
- provider.requestCreateSession(routerRecord.mPackageName, route.getOriginalId(),
- requestId, sessionHints);
+ provider.requestCreateSession(requestId, routerRecord.mPackageName,
+ route.getOriginalId(), sessionHints);
}
// routerRecord can be null if the session is system's.
- private void selectRouteOnHandler(@Nullable RouterRecord routerRecord,
- @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route, long requestId) {
+ private void selectRouteOnHandler(long requestId, @Nullable RouterRecord routerRecord,
+ @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route) {
if (!checkArgumentsForSessionControl(routerRecord, uniqueSessionId, route,
"selecting")) {
return;
@@ -1254,12 +1261,12 @@
if (provider == null) {
return;
}
- provider.selectRoute(getOriginalId(uniqueSessionId), route.getOriginalId(), requestId);
+ provider.selectRoute(requestId, getOriginalId(uniqueSessionId), route.getOriginalId());
}
// routerRecord can be null if the session is system's.
- private void deselectRouteOnHandler(@Nullable RouterRecord routerRecord,
- @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route, long requestId) {
+ private void deselectRouteOnHandler(long requestId, @Nullable RouterRecord routerRecord,
+ @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route) {
if (!checkArgumentsForSessionControl(routerRecord, uniqueSessionId, route,
"deselecting")) {
return;
@@ -1271,13 +1278,14 @@
if (provider == null) {
return;
}
- provider.deselectRoute(getOriginalId(uniqueSessionId), route.getOriginalId(),
- requestId);
+
+ provider.deselectRoute(requestId, getOriginalId(uniqueSessionId),
+ route.getOriginalId());
}
// routerRecord can be null if the session is system's.
- private void transferToRouteOnHandler(@Nullable RouterRecord routerRecord,
- @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route, long requestId) {
+ private void transferToRouteOnHandler(long requestId, @Nullable RouterRecord routerRecord,
+ @NonNull String uniqueSessionId, @NonNull MediaRoute2Info route) {
if (!checkArgumentsForSessionControl(routerRecord, uniqueSessionId, route,
"transferring to")) {
return;
@@ -1289,8 +1297,8 @@
if (provider == null) {
return;
}
- provider.transferToRoute(getOriginalId(uniqueSessionId), route.getOriginalId(),
- requestId);
+ provider.transferToRoute(requestId, getOriginalId(uniqueSessionId),
+ route.getOriginalId());
}
private boolean checkArgumentsForSessionControl(@Nullable RouterRecord routerRecord,
@@ -1332,8 +1340,29 @@
return true;
}
- private void releaseSessionOnHandler(@NonNull RouterRecord routerRecord,
- @NonNull String uniqueSessionId, long uniqueRequestId) {
+ private void setRouteVolumeOnHandler(long requestId, @NonNull MediaRoute2Info route,
+ int volume) {
+ final MediaRoute2Provider provider = findProvider(route.getProviderId());
+ if (provider == null) {
+ Slog.w(TAG, "setRouteVolume: couldn't find provider for route=" + route);
+ return;
+ }
+ provider.setRouteVolume(requestId, route.getOriginalId(), volume);
+ }
+
+ private void setSessionVolumeOnHandler(long requestId, @NonNull String uniqueSessionId,
+ int volume) {
+ final MediaRoute2Provider provider = findProvider(getProviderId(uniqueSessionId));
+ if (provider == null) {
+ Slog.w(TAG, "setSessionVolume: couldn't find provider for session "
+ + "id=" + uniqueSessionId);
+ return;
+ }
+ provider.setSessionVolume(requestId, getOriginalId(uniqueSessionId), volume);
+ }
+
+ private void releaseSessionOnHandler(long uniqueRequestId,
+ @NonNull RouterRecord routerRecord, @NonNull String uniqueSessionId) {
final RouterRecord matchingRecord = mSessionToRouterMap.get(uniqueSessionId);
if (matchingRecord != routerRecord) {
Slog.w(TAG, "Ignoring releasing session from non-matching router."
@@ -1363,11 +1392,11 @@
return;
}
- provider.releaseSession(sessionId, uniqueRequestId);
+ provider.releaseSession(uniqueRequestId, sessionId);
}
private void onSessionCreatedOnHandler(@NonNull MediaRoute2Provider provider,
- @NonNull RoutingSessionInfo sessionInfo, long requestId) {
+ long requestId, @NonNull RoutingSessionInfo sessionInfo) {
notifySessionCreatedToManagers(getManagers(), sessionInfo);
if (requestId == REQUEST_ID_NONE) {
@@ -1415,7 +1444,7 @@
// Succeeded
notifySessionCreatedToRouter(matchingRequest.mRouterRecord,
- sessionInfo, toOriginalRequestId(requestId));
+ toOriginalRequestId(requestId), sessionInfo);
mSessionToRouterMap.put(sessionInfo.getId(), routerRecord);
}
@@ -1510,9 +1539,9 @@
}
private void notifySessionCreatedToRouter(@NonNull RouterRecord routerRecord,
- @NonNull RoutingSessionInfo sessionInfo, int requestId) {
+ int requestId, @NonNull RoutingSessionInfo sessionInfo) {
try {
- routerRecord.mRouter.notifySessionCreated(sessionInfo, requestId);
+ routerRecord.mRouter.notifySessionCreated(requestId, sessionInfo);
} catch (RemoteException ex) {
Slog.w(TAG, "Failed to notify router of the session creation."
+ " Router probably died.", ex);
@@ -1522,7 +1551,7 @@
private void notifySessionCreationFailedToRouter(@NonNull RouterRecord routerRecord,
int requestId) {
try {
- routerRecord.mRouter.notifySessionCreated(/* sessionInfo= */ null, requestId);
+ routerRecord.mRouter.notifySessionCreated(requestId, /* sessionInfo= */ null);
} catch (RemoteException ex) {
Slog.w(TAG, "Failed to notify router of the session creation failure."
+ " Router probably died.", ex);
@@ -1549,25 +1578,6 @@
}
}
- private void setRouteVolumeOnHandler(@NonNull MediaRoute2Info route, int volume,
- long requestId) {
- final MediaRoute2Provider provider = findProvider(route.getProviderId());
- if (provider != null) {
- provider.setRouteVolume(route.getOriginalId(), volume, requestId);
- }
- }
-
- private void setSessionVolumeOnHandler(@NonNull String uniqueSessionId, int volume,
- long requestId) {
- final MediaRoute2Provider provider = findProvider(getProviderId(uniqueSessionId));
- if (provider == null) {
- Slog.w(TAG, "setSessionVolume: couldn't find provider for session "
- + "id=" + uniqueSessionId);
- return;
- }
- provider.setSessionVolume(getOriginalId(uniqueSessionId), volume, requestId);
- }
-
private List<IMediaRouter2> getRouters() {
final List<IMediaRouter2> routers = new ArrayList<>();
MediaRouter2ServiceImpl service = mServiceRef.get();
@@ -1599,7 +1609,7 @@
private List<ManagerRecord> getManagerRecords() {
MediaRouter2ServiceImpl service = mServiceRef.get();
if (service == null) {
- return new ArrayList<>();
+ return Collections.emptyList();
}
synchronized (service.mLock) {
return new ArrayList<>(mUserRecord.mManagerRecords);
@@ -1799,18 +1809,18 @@
final class SessionCreationRequest {
public final RouterRecord mRouterRecord;
- public final ManagerRecord mRequestedManagerRecord;
- public final MediaRoute2Info mRoute;
public final long mRequestId;
+ public final MediaRoute2Info mRoute;
+ public final ManagerRecord mRequestedManagerRecord;
// requestedManagerRecord is not null only when the request is made by manager.
- SessionCreationRequest(@NonNull RouterRecord routerRecord,
- @Nullable ManagerRecord requestedManagerRecord,
- @NonNull MediaRoute2Info route, long requestId) {
+ SessionCreationRequest(@NonNull RouterRecord routerRecord, long requestId,
+ @NonNull MediaRoute2Info route,
+ @Nullable ManagerRecord requestedManagerRecord) {
mRouterRecord = routerRecord;
- mRequestedManagerRecord = requestedManagerRecord;
- mRoute = route;
mRequestId = requestId;
+ mRoute = route;
+ mRequestedManagerRecord = requestedManagerRecord;
}
}
}
diff --git a/services/core/java/com/android/server/media/MediaRouterService.java b/services/core/java/com/android/server/media/MediaRouterService.java
index a13ee10..d6bf9fb 100644
--- a/services/core/java/com/android/server/media/MediaRouterService.java
+++ b/services/core/java/com/android/server/media/MediaRouterService.java
@@ -480,9 +480,9 @@
// Binder call
@Override
- public void requestCreateSessionWithRouter2(IMediaRouter2 router, MediaRoute2Info route,
- int requestId, Bundle sessionHints) {
- mService2.requestCreateSessionWithRouter2(router, route, requestId, sessionHints);
+ public void requestCreateSessionWithRouter2(IMediaRouter2 router, int requestId,
+ MediaRoute2Info route, Bundle sessionHints) {
+ mService2.requestCreateSessionWithRouter2(router, requestId, route, sessionHints);
}
// Binder call
@@ -542,51 +542,51 @@
// Binder call
@Override
- public void setRouteVolumeWithManager(IMediaRouter2Manager manager,
- MediaRoute2Info route, int volume, int requestId) {
- mService2.setRouteVolumeWithManager(manager, route, volume, requestId);
+ public void setRouteVolumeWithManager(IMediaRouter2Manager manager, int requestId,
+ MediaRoute2Info route, int volume) {
+ mService2.setRouteVolumeWithManager(manager, requestId, route, volume);
}
// Binder call
@Override
- public void requestCreateSessionWithManager(IMediaRouter2Manager manager, String packageName,
- MediaRoute2Info route, int requestId) {
- mService2.requestCreateSessionWithManager(manager, packageName, route, requestId);
+ public void requestCreateSessionWithManager(IMediaRouter2Manager manager,
+ int requestId, String packageName, MediaRoute2Info route) {
+ mService2.requestCreateSessionWithManager(manager, requestId, packageName, route);
}
// Binder call
@Override
- public void selectRouteWithManager(IMediaRouter2Manager manager, String sessionId,
- MediaRoute2Info route, int requestId) {
- mService2.selectRouteWithManager(manager, sessionId, route, requestId);
+ public void selectRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, MediaRoute2Info route) {
+ mService2.selectRouteWithManager(manager, requestId, sessionId, route);
}
// Binder call
@Override
- public void deselectRouteWithManager(IMediaRouter2Manager manager, String sessionId,
- MediaRoute2Info route, int requestId) {
- mService2.deselectRouteWithManager(manager, sessionId, route, requestId);
+ public void deselectRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, MediaRoute2Info route) {
+ mService2.deselectRouteWithManager(manager, requestId, sessionId, route);
}
// Binder call
@Override
- public void transferToRouteWithManager(IMediaRouter2Manager manager, String sessionId,
- MediaRoute2Info route, int requestId) {
- mService2.transferToRouteWithManager(manager, sessionId, route, requestId);
+ public void transferToRouteWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, MediaRoute2Info route) {
+ mService2.transferToRouteWithManager(manager, requestId, sessionId, route);
}
// Binder call
@Override
- public void setSessionVolumeWithManager(IMediaRouter2Manager manager,
- String sessionId, int volume, int requestId) {
- mService2.setSessionVolumeWithManager(manager, sessionId, volume, requestId);
+ public void setSessionVolumeWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId, int volume) {
+ mService2.setSessionVolumeWithManager(manager, requestId, sessionId, volume);
}
// Binder call
@Override
- public void releaseSessionWithManager(IMediaRouter2Manager manager, String sessionId,
- int requestId) {
- mService2.releaseSessionWithManager(manager, sessionId, requestId);
+ public void releaseSessionWithManager(IMediaRouter2Manager manager, int requestId,
+ String sessionId) {
+ mService2.releaseSessionWithManager(manager, requestId, sessionId);
}
void restoreBluetoothA2dp() {
diff --git a/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java b/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java
index 1922c8c..5c97e90 100644
--- a/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java
+++ b/services/core/java/com/android/server/media/SystemMediaRoute2Provider.java
@@ -125,14 +125,16 @@
}
@Override
- public void requestCreateSession(String packageName, String routeId, long requestId,
+ public void requestCreateSession(long requestId, String packageName, String routeId,
Bundle sessionHints) {
- // Handle it as an internal transfer.
- transferToRoute(SYSTEM_SESSION_ID, routeId, requestId);
+
+ transferToRoute(requestId, SYSTEM_SESSION_ID, routeId);
+ mCallback.onSessionCreated(this, requestId, mSessionInfos.get(0));
+ //TODO: We should call after the session info is changed.
}
@Override
- public void releaseSession(String sessionId, long requestId) {
+ public void releaseSession(long requestId, String sessionId) {
// Do nothing
}
@@ -142,17 +144,17 @@
}
@Override
- public void selectRoute(String sessionId, String routeId, long requestId) {
+ public void selectRoute(long requestId, String sessionId, String routeId) {
// Do nothing since we don't support multiple BT yet.
}
@Override
- public void deselectRoute(String sessionId, String routeId, long requestId) {
+ public void deselectRoute(long requestId, String sessionId, String routeId) {
// Do nothing since we don't support multiple BT yet.
}
@Override
- public void transferToRoute(String sessionId, String routeId, long requestId) {
+ public void transferToRoute(long requestId, String sessionId, String routeId) {
if (TextUtils.equals(routeId, mDefaultRoute.getId())) {
mBtRouteProvider.transferTo(null);
} else {
@@ -161,7 +163,7 @@
}
@Override
- public void setRouteVolume(String routeId, int volume, long requestId) {
+ public void setRouteVolume(long requestId, String routeId, int volume) {
if (!TextUtils.equals(routeId, mSelectedRouteId)) {
return;
}
@@ -169,7 +171,7 @@
}
@Override
- public void setSessionVolume(String sessionId, int volume, long requestId) {
+ public void setSessionVolume(long requestId, String sessionId, int volume) {
// Do nothing since we don't support grouping volume yet.
}
@@ -240,7 +242,6 @@
builder.addTransferableRoute(route.getId());
}
-
RoutingSessionInfo newSessionInfo = builder.setProviderId(mUniqueId).build();
if (Objects.equals(oldSessionInfo, newSessionInfo)) {
return false;
@@ -261,6 +262,7 @@
synchronized (mLock) {
sessionInfo = mSessionInfos.get(0);
}
+
mCallback.onSessionUpdated(this, sessionInfo);
}
diff --git a/services/core/java/com/android/server/net/NetworkStatsService.java b/services/core/java/com/android/server/net/NetworkStatsService.java
index ee5a4fe..cb3da91 100644
--- a/services/core/java/com/android/server/net/NetworkStatsService.java
+++ b/services/core/java/com/android/server/net/NetworkStatsService.java
@@ -23,6 +23,7 @@
import static android.content.Intent.ACTION_UID_REMOVED;
import static android.content.Intent.ACTION_USER_REMOVED;
import static android.content.Intent.EXTRA_UID;
+import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.ConnectivityManager.ACTION_TETHER_STATE_CHANGED;
import static android.net.ConnectivityManager.isNetworkTypeMobile;
import static android.net.NetworkStack.checkNetworkStackPermission;
@@ -306,9 +307,8 @@
/** Data layer operation counters for splicing into other structures. */
private NetworkStats mUidOperations = new NetworkStats(0L, 10);
- /** Must be set in factory by calling #setHandler. */
- private Handler mHandler;
- private Handler.Callback mHandlerCallback;
+ @NonNull
+ private final Handler mHandler;
private volatile boolean mSystemReady;
private long mPersistThreshold = 2 * MB_IN_BYTES;
@@ -324,6 +324,9 @@
private final static int DUMP_STATS_SESSION_COUNT = 20;
+ @NonNull
+ private final Dependencies mDeps;
+
private static @NonNull File getDefaultSystemDir() {
return new File(Environment.getDataDirectory(), "system");
}
@@ -339,9 +342,24 @@
Clock.systemUTC());
}
- private static final class NetworkStatsHandler extends Handler {
- NetworkStatsHandler(Looper looper, Handler.Callback callback) {
- super(looper, callback);
+ private final class NetworkStatsHandler extends Handler {
+ NetworkStatsHandler(@NonNull Looper looper) {
+ super(looper);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MSG_PERFORM_POLL: {
+ performPoll(FLAG_PERSIST_ALL);
+ break;
+ }
+ case MSG_PERFORM_POLL_REGISTER_ALERT: {
+ performPoll(FLAG_PERSIST_NETWORK);
+ registerGlobalAlert();
+ break;
+ }
+ }
}
}
@@ -355,14 +373,10 @@
NetworkStatsService service = new NetworkStatsService(context, networkManager, alarmManager,
wakeLock, getDefaultClock(), context.getSystemService(TelephonyManager.class),
new DefaultNetworkStatsSettings(context), new NetworkStatsFactory(),
- new NetworkStatsObservers(), getDefaultSystemDir(), getDefaultBaseDir());
+ new NetworkStatsObservers(), getDefaultSystemDir(), getDefaultBaseDir(),
+ new Dependencies());
service.registerLocalService();
- HandlerThread handlerThread = new HandlerThread(TAG);
- Handler.Callback callback = new HandlerCallback(service);
- handlerThread.start();
- Handler handler = new NetworkStatsHandler(handlerThread.getLooper(), callback);
- service.setHandler(handler, callback);
return service;
}
@@ -373,7 +387,7 @@
AlarmManager alarmManager, PowerManager.WakeLock wakeLock, Clock clock,
TelephonyManager teleManager, NetworkStatsSettings settings,
NetworkStatsFactory factory, NetworkStatsObservers statsObservers, File systemDir,
- File baseDir) {
+ File baseDir, @NonNull Dependencies deps) {
mContext = Objects.requireNonNull(context, "missing Context");
mNetworkManager = Objects.requireNonNull(networkManager,
"missing INetworkManagementService");
@@ -387,6 +401,26 @@
mSystemDir = Objects.requireNonNull(systemDir, "missing systemDir");
mBaseDir = Objects.requireNonNull(baseDir, "missing baseDir");
mUseBpfTrafficStats = new File("/sys/fs/bpf/map_netd_app_uid_stats_map").exists();
+ mDeps = Objects.requireNonNull(deps, "missing Dependencies");
+
+ final HandlerThread handlerThread = mDeps.makeHandlerThread();
+ handlerThread.start();
+ mHandler = new NetworkStatsHandler(handlerThread.getLooper());
+ }
+
+ /**
+ * Dependencies of NetworkStatsService, for injection in tests.
+ */
+ // TODO: Move more stuff into dependencies object.
+ @VisibleForTesting
+ public static class Dependencies {
+ /**
+ * Create a HandlerThread to use in NetworkStatsService.
+ */
+ @NonNull
+ public HandlerThread makeHandlerThread() {
+ return new HandlerThread(TAG);
+ }
}
private void registerLocalService() {
@@ -394,12 +428,6 @@
new NetworkStatsManagerInternalImpl());
}
- @VisibleForTesting
- void setHandler(Handler handler, Handler.Callback callback) {
- mHandler = handler;
- mHandlerCallback = callback;
- }
-
public void systemReady() {
synchronized (mStatsLock) {
mSystemReady = true;
@@ -1766,6 +1794,24 @@
}
}
+ // TODO: It is copied from ConnectivitySerivce, consider refactor these check permission
+ // functions to a proper util.
+ private boolean checkAnyPermissionOf(String... permissions) {
+ for (String permission : permissions) {
+ if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void enforceAnyPermissionOf(String... permissions) {
+ if (!checkAnyPermissionOf(permissions)) {
+ throw new SecurityException("Requires one of the following permissions: "
+ + String.join(", ", permissions) + ".");
+ }
+ }
+
/**
* Registers a custom provider of {@link android.net.NetworkStats} to combine the network
* statistics that cannot be seen by the kernel to system. To unregister, invoke the
@@ -1920,33 +1966,6 @@
}
- @VisibleForTesting
- static class HandlerCallback implements Handler.Callback {
- private final NetworkStatsService mService;
-
- HandlerCallback(NetworkStatsService service) {
- this.mService = service;
- }
-
- @Override
- public boolean handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_PERFORM_POLL: {
- mService.performPoll(FLAG_PERSIST_ALL);
- return true;
- }
- case MSG_PERFORM_POLL_REGISTER_ALERT: {
- mService.performPoll(FLAG_PERSIST_NETWORK);
- mService.registerGlobalAlert();
- return true;
- }
- default: {
- return false;
- }
- }
- }
- }
-
private void assertSystemReady() {
if (!mSystemReady) {
throw new IllegalStateException("System not ready");
diff --git a/services/core/java/com/android/server/notification/BubbleExtractor.java b/services/core/java/com/android/server/notification/BubbleExtractor.java
index c9c8042..c96880c 100644
--- a/services/core/java/com/android/server/notification/BubbleExtractor.java
+++ b/services/core/java/com/android/server/notification/BubbleExtractor.java
@@ -15,9 +15,27 @@
*/
package com.android.server.notification;
+import static android.app.Notification.CATEGORY_CALL;
+import static android.app.Notification.FLAG_BUBBLE;
+import static android.app.Notification.FLAG_FOREGROUND_SERVICE;
+
+import static com.android.internal.util.FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING;
+import static com.android.internal.util.FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE;
+
+import android.app.ActivityManager;
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.Person;
import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
import android.util.Slog;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.FrameworkStatsLog;
+
+import java.util.ArrayList;
+
/**
* Determines whether a bubble can be shown for this notification
*/
@@ -25,10 +43,15 @@
private static final String TAG = "BubbleExtractor";
private static final boolean DBG = false;
+ private BubbleChecker mBubbleChecker;
private RankingConfig mConfig;
+ private ActivityManager mActivityManager;
+ private Context mContext;
- public void initialize(Context ctx, NotificationUsageStats usageStats) {
+ public void initialize(Context context, NotificationUsageStats usageStats) {
if (DBG) Slog.d(TAG, "Initializing " + getClass().getSimpleName() + ".");
+ mContext = context;
+ mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
}
public RankingReconsideration process(NotificationRecord record) {
@@ -41,6 +64,12 @@
if (DBG) Slog.d(TAG, "missing config");
return null;
}
+
+ if (mBubbleChecker == null) {
+ if (DBG) Slog.d(TAG, "missing bubble checker");
+ return null;
+ }
+
boolean appCanShowBubble =
mConfig.areBubblesAllowed(record.getSbn().getPackageName(), record.getSbn().getUid());
if (!mConfig.bubblesEnabled() || !appCanShowBubble) {
@@ -52,7 +81,12 @@
record.setAllowBubble(appCanShowBubble);
}
}
-
+ final boolean applyFlag = mBubbleChecker.isNotificationAppropriateToBubble(record);
+ if (applyFlag) {
+ record.getNotification().flags |= FLAG_BUBBLE;
+ } else {
+ record.getNotification().flags &= ~FLAG_BUBBLE;
+ }
return null;
}
@@ -64,4 +98,185 @@
@Override
public void setZenHelper(ZenModeHelper helper) {
}
+
+ /**
+ * Expected to be called after {@link #setConfig(RankingConfig)} has occurred.
+ */
+ void setShortcutHelper(ShortcutHelper helper) {
+ if (mConfig == null) {
+ if (DBG) Slog.d(TAG, "setting shortcut helper prior to setConfig");
+ return;
+ }
+ mBubbleChecker = new BubbleChecker(mContext, helper, mConfig, mActivityManager);
+ }
+
+ @VisibleForTesting
+ void setBubbleChecker(BubbleChecker checker) {
+ mBubbleChecker = checker;
+ }
+
+ /**
+ * Encapsulates special checks to see if a notification can be flagged as a bubble. This
+ * makes testing a bit easier.
+ */
+ public static class BubbleChecker {
+
+ private ActivityManager mActivityManager;
+ private RankingConfig mRankingConfig;
+ private Context mContext;
+ private ShortcutHelper mShortcutHelper;
+
+ BubbleChecker(Context context, ShortcutHelper helper, RankingConfig config,
+ ActivityManager activityManager) {
+ mContext = context;
+ mActivityManager = activityManager;
+ mShortcutHelper = helper;
+ mRankingConfig = config;
+ }
+
+ /**
+ * @return whether the provided notification record is allowed to be represented as a
+ * bubble, accounting for user choice & policy.
+ */
+ public boolean isNotificationAppropriateToBubble(NotificationRecord r) {
+ final String pkg = r.getSbn().getPackageName();
+ final int userId = r.getSbn().getUser().getIdentifier();
+ Notification notification = r.getNotification();
+ if (!canBubble(r, pkg, userId)) {
+ // no log: canBubble has its own
+ return false;
+ }
+
+ if (mActivityManager.isLowRamDevice()) {
+ logBubbleError(r.getKey(), "low ram device");
+ return false;
+ }
+
+ // At this point the bubble must fulfill communication policy
+
+ // Communication always needs a person
+ ArrayList<Person> peopleList = notification.extras != null
+ ? notification.extras.getParcelableArrayList(Notification.EXTRA_PEOPLE_LIST)
+ : null;
+ // Message style requires a person & it's not included in the list
+ boolean isMessageStyle = Notification.MessagingStyle.class.equals(
+ notification.getNotificationStyle());
+ if (!isMessageStyle && (peopleList == null || peopleList.isEmpty())) {
+ logBubbleError(r.getKey(), "Must have a person and be "
+ + "Notification.MessageStyle or Notification.CATEGORY_CALL");
+ return false;
+ }
+
+ // Communication is a message or a call
+ boolean isCall = CATEGORY_CALL.equals(notification.category);
+ boolean hasForegroundService = (notification.flags & FLAG_FOREGROUND_SERVICE) != 0;
+ if (hasForegroundService && !isCall) {
+ logBubbleError(r.getKey(),
+ "foreground services must be Notification.CATEGORY_CALL to bubble");
+ return false;
+ }
+ if (isMessageStyle) {
+ return true;
+ } else if (isCall) {
+ if (hasForegroundService) {
+ return true;
+ }
+ logBubbleError(r.getKey(), "calls require foreground service");
+ return false;
+ }
+ logBubbleError(r.getKey(), "Must be "
+ + "Notification.MessageStyle or Notification.CATEGORY_CALL");
+ return false;
+ }
+
+ /**
+ * @return whether the user has enabled the provided notification to bubble, does not
+ * account for policy.
+ */
+ @VisibleForTesting
+ boolean canBubble(NotificationRecord r, String pkg, int userId) {
+ Notification notification = r.getNotification();
+ Notification.BubbleMetadata metadata = notification.getBubbleMetadata();
+ if (metadata == null) {
+ // no log: no need to inform dev if they didn't attach bubble metadata
+ return false;
+ }
+ if (!mRankingConfig.bubblesEnabled()) {
+ logBubbleError(r.getKey(), "bubbles disabled for user: " + userId);
+ return false;
+ }
+ if (!mRankingConfig.areBubblesAllowed(pkg, userId)) {
+ logBubbleError(r.getKey(),
+ "bubbles for package: " + pkg + " disabled for user: " + userId);
+ return false;
+ }
+ if (!r.getChannel().canBubble()) {
+ logBubbleError(r.getKey(),
+ "bubbles for channel " + r.getChannel().getId() + " disabled");
+ return false;
+ }
+
+ String shortcutId = metadata.getShortcutId();
+ boolean shortcutValid = shortcutId != null
+ && mShortcutHelper.hasValidShortcutInfo(shortcutId, pkg, r.getUser());
+ if (metadata.getBubbleIntent() == null && !shortcutValid) {
+ // Should have a shortcut if intent is null
+ logBubbleError(r.getKey(),
+ "couldn't find valid shortcut for bubble with shortcutId: " + shortcutId);
+ return false;
+ }
+ if (shortcutValid) {
+ return true;
+ }
+ // no log: canLaunch method has the failure log
+ return canLaunchInActivityView(mContext, metadata.getBubbleIntent(), pkg);
+ }
+
+ /**
+ * Whether an intent is properly configured to display in an {@link
+ * android.app.ActivityView}.
+ *
+ * @param context the context to use.
+ * @param pendingIntent the pending intent of the bubble.
+ * @param packageName the notification package name for this bubble.
+ */
+ // Keep checks in sync with BubbleController#canLaunchInActivityView.
+ @VisibleForTesting
+ protected boolean canLaunchInActivityView(Context context, PendingIntent pendingIntent,
+ String packageName) {
+ if (pendingIntent == null) {
+ Slog.w(TAG, "Unable to create bubble -- no intent");
+ return false;
+ }
+
+ Intent intent = pendingIntent.getIntent();
+
+ ActivityInfo info = intent != null
+ ? intent.resolveActivityInfo(context.getPackageManager(), 0)
+ : null;
+ if (info == null) {
+ FrameworkStatsLog.write(FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED,
+ packageName,
+ BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING);
+ Slog.w(TAG, "Unable to send as bubble -- couldn't find activity info for intent: "
+ + intent);
+ return false;
+ }
+ if (!ActivityInfo.isResizeableMode(info.resizeMode)) {
+ FrameworkStatsLog.write(FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED,
+ packageName,
+ BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE);
+ Slog.w(TAG, "Unable to send as bubble -- activity is not resizable for intent: "
+ + intent);
+ return false;
+ }
+ return true;
+ }
+
+ private void logBubbleError(String key, String failureMessage) {
+ if (DBG) {
+ Slog.w(TAG, "Bubble notification: " + key + " failed: " + failureMessage);
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/notification/NotificationHistoryManager.java b/services/core/java/com/android/server/notification/NotificationHistoryManager.java
index 7d68012..f7fb9b7 100644
--- a/services/core/java/com/android/server/notification/NotificationHistoryManager.java
+++ b/services/core/java/com/android/server/notification/NotificationHistoryManager.java
@@ -358,7 +358,9 @@
false, this, UserHandle.USER_ALL);
synchronized (mLock) {
for (UserInfo userInfo : mUserManager.getUsers()) {
- update(null, userInfo.id);
+ if (!userInfo.isProfile()) {
+ update(null, userInfo.id);
+ }
}
}
}
@@ -379,7 +381,10 @@
boolean historyEnabled = Settings.Secure.getIntForUser(resolver,
Settings.Secure.NOTIFICATION_HISTORY_ENABLED, 0, userId)
!= 0;
- onHistoryEnabledChanged(userId, historyEnabled);
+ int[] profiles = mUserManager.getProfileIds(userId, true);
+ for (int profileId : profiles) {
+ onHistoryEnabledChanged(profileId, historyEnabled);
+ }
}
}
}
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index b5e7ea0..20ad87a 100755
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -17,7 +17,6 @@
package com.android.server.notification;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
-import static android.app.Notification.CATEGORY_CALL;
import static android.app.Notification.FLAG_AUTOGROUP_SUMMARY;
import static android.app.Notification.FLAG_BUBBLE;
import static android.app.Notification.FLAG_FOREGROUND_SERVICE;
@@ -51,9 +50,6 @@
import static android.content.Context.BIND_AUTO_CREATE;
import static android.content.Context.BIND_FOREGROUND_SERVICE;
import static android.content.Context.BIND_NOT_PERCEPTIBLE;
-import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_CACHED;
-import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC;
-import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED;
import static android.content.pm.PackageManager.FEATURE_LEANBACK;
import static android.content.pm.PackageManager.FEATURE_TELEVISION;
import static android.content.pm.PackageManager.MATCH_ALL;
@@ -93,8 +89,6 @@
import static android.service.notification.NotificationListenerService.TRIM_LIGHT;
import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
-import static com.android.internal.util.FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING;
-import static com.android.internal.util.FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE;
import static com.android.internal.util.FrameworkStatsLog.PACKAGE_NOTIFICATION_CHANNEL_GROUP_PREFERENCES;
import static com.android.internal.util.FrameworkStatsLog.PACKAGE_NOTIFICATION_CHANNEL_PREFERENCES;
import static com.android.internal.util.FrameworkStatsLog.PACKAGE_NOTIFICATION_PREFERENCES;
@@ -131,8 +125,6 @@
import android.app.NotificationManager;
import android.app.NotificationManager.Policy;
import android.app.PendingIntent;
-import android.app.Person;
-import android.app.RemoteInput;
import android.app.StatsManager;
import android.app.StatusBarManager;
import android.app.UriGrantsManager;
@@ -152,7 +144,6 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.LauncherApps;
@@ -160,7 +151,6 @@
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageManagerInternal;
import android.content.pm.ParceledListSlice;
-import android.content.pm.ShortcutInfo;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.database.ContentObserver;
@@ -251,7 +241,6 @@
import com.android.internal.util.CollectionUtils;
import com.android.internal.util.DumpUtils;
import com.android.internal.util.FastXmlSerializer;
-import com.android.internal.util.FrameworkStatsLog;
import com.android.internal.util.Preconditions;
import com.android.internal.util.XmlUtils;
import com.android.internal.util.function.TriPredicate;
@@ -296,7 +285,6 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
@@ -421,7 +409,7 @@
private RoleObserver mRoleObserver;
private UserManager mUm;
private IPlatformCompat mPlatformCompat;
- private LauncherApps mLauncherAppsService;
+ private ShortcutHelper mShortcutHelper;
final IBinder mForegroundToken = new Binder();
private WorkerHandler mHandler;
@@ -497,7 +485,8 @@
"allow-secure-notifications-on-lockscreen";
private static final String LOCKSCREEN_ALLOW_SECURE_NOTIFICATIONS_VALUE = "value";
- private RankingHelper mRankingHelper;
+ @VisibleForTesting
+ RankingHelper mRankingHelper;
@VisibleForTesting
PreferencesHelper mPreferencesHelper;
@@ -931,6 +920,8 @@
.setType(MetricsEvent.TYPE_ACTION)
.addTaggedData(MetricsEvent.NOTIFICATION_SHADE_INDEX, nv.rank)
.addTaggedData(MetricsEvent.NOTIFICATION_SHADE_COUNT, nv.count));
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLICKED, r);
EventLogTags.writeNotificationClicked(key,
r.getLifespanMs(now), r.getFreshnessMs(now), r.getExposureMs(now),
nv.rank, nv.count);
@@ -970,7 +961,8 @@
generatedByAssistant ? 1 : 0)
.addTaggedData(MetricsEvent.NOTIFICATION_LOCATION,
nv.location.toMetricsEventEnum()));
-
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_ACTION_CLICKED, r);
EventLogTags.writeNotificationActionClicked(key, actionIndex,
r.getLifespanMs(now), r.getFreshnessMs(now), r.getExposureMs(now),
nv.rank, nv.count);
@@ -1004,6 +996,8 @@
public void onPanelRevealed(boolean clearEffects, int items) {
MetricsLogger.visible(getContext(), MetricsEvent.NOTIFICATION_PANEL);
MetricsLogger.histogram(getContext(), "note_load", items);
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationPanelEvent.NOTIFICATION_PANEL_OPEN);
EventLogTags.writeNotificationPanelRevealed(items);
if (clearEffects) {
clearEffects();
@@ -1014,6 +1008,8 @@
@Override
public void onPanelHidden() {
MetricsLogger.hidden(getContext(), MetricsEvent.NOTIFICATION_PANEL);
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationPanelEvent.NOTIFICATION_PANEL_CLOSE);
EventLogTags.writeNotificationPanelHidden();
mAssistants.onPanelHidden();
}
@@ -1103,6 +1099,10 @@
MetricsLogger.action(r.getItemLogMaker()
.setType(expanded ? MetricsEvent.TYPE_DETAIL
: MetricsEvent.TYPE_COLLAPSE));
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.fromExpanded(expanded,
+ userAction),
+ r);
}
if (expanded && userAction) {
r.recordExpanded();
@@ -1124,6 +1124,9 @@
mMetricsLogger.write(r.getLogMaker()
.setCategory(MetricsEvent.NOTIFICATION_DIRECT_REPLY_ACTION)
.setType(MetricsEvent.TYPE_ACTION));
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_DIRECT_REPLIED,
+ r);
reportUserInteraction(r);
mAssistants.notifyAssistantNotificationDirectReplyLocked(r.getSbn());
}
@@ -1166,6 +1169,9 @@
MetricsEvent.NOTIFICATION_SMART_REPLY_MODIFIED_BEFORE_SENDING,
modifiedBeforeSending ? 1 : 0);
mMetricsLogger.write(logMaker);
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_SMART_REPLIED,
+ r);
// Treat clicking on a smart reply as a user interaction.
reportUserInteraction(r);
mAssistants.notifyAssistantSuggestedReplySent(
@@ -1186,13 +1192,30 @@
@Override
public void onNotificationBubbleChanged(String key, boolean isBubble) {
+ String pkg;
+ synchronized (mNotificationLock) {
+ NotificationRecord r = mNotificationsByKey.get(key);
+ pkg = r != null && r.getSbn() != null ? r.getSbn().getPackageName() : null;
+ }
+ boolean isAppForeground = pkg != null
+ && mActivityManager.getPackageImportance(pkg) == IMPORTANCE_FOREGROUND;
synchronized (mNotificationLock) {
NotificationRecord r = mNotificationsByKey.get(key);
if (r != null) {
- final StatusBarNotification n = r.getSbn();
- final int callingUid = n.getUid();
- final String pkg = n.getPackageName();
- applyFlagBubble(r, pkg, callingUid, null /* oldEntry */, isBubble);
+ if (!isBubble) {
+ // This happens if the user has dismissed the bubble but the notification
+ // is still active in the shade, enqueuing would create a bubble since
+ // the notification is technically allowed. Flip the flag so that
+ // apps querying noMan will know that their notification is not showing
+ // as a bubble.
+ r.getNotification().flags &= ~FLAG_BUBBLE;
+ } else {
+ // Enqueue will trigger resort & if the flag is allowed to be true it'll
+ // be applied there.
+ r.getNotification().flags |= FLAG_ONLY_ALERT_ONCE;
+ mHandler.post(new EnqueueNotificationRunnable(r.getUser().getIdentifier(),
+ r, isAppForeground));
+ }
}
}
}
@@ -1219,6 +1242,7 @@
flags &= ~Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION;
}
data.setFlags(flags);
+ r.getNotification().flags |= FLAG_ONLY_ALERT_ONCE;
mHandler.post(new EnqueueNotificationRunnable(r.getUser().getIdentifier(), r,
true /* isAppForeground */));
}
@@ -1310,6 +1334,9 @@
MetricsEvent.NOTIFICATION_SMART_REPLY_EDIT_BEFORE_SENDING,
r.getEditChoicesBeforeSending() ? 1 : 0);
mMetricsLogger.write(logMaker);
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_SMART_REPLY_VISIBLE,
+ r);
}
}
@@ -1595,80 +1622,6 @@
}
};
- // Key: packageName Value: <shortcutId, notifId>
- private HashMap<String, HashMap<String, String>> mActiveShortcutBubbles = new HashMap<>();
-
- private boolean mLauncherAppsCallbackRegistered;
-
- // Bubbles can be created based on a shortcut, we need to listen for changes to
- // that shortcut so that we may update the bubble appropriately.
- private final LauncherApps.Callback mLauncherAppsCallback = new LauncherApps.Callback() {
- @Override
- public void onPackageRemoved(String packageName, UserHandle user) {
- }
-
- @Override
- public void onPackageAdded(String packageName, UserHandle user) {
- }
-
- @Override
- public void onPackageChanged(String packageName, UserHandle user) {
- }
-
- @Override
- public void onPackagesAvailable(String[] packageNames, UserHandle user,
- boolean replacing) {
- }
-
- @Override
- public void onPackagesUnavailable(String[] packageNames, UserHandle user,
- boolean replacing) {
- }
-
- @Override
- public void onShortcutsChanged(@NonNull String packageName,
- @NonNull List<ShortcutInfo> shortcuts, @NonNull UserHandle user) {
- HashMap<String, String> shortcutBubbles = mActiveShortcutBubbles.get(packageName);
- boolean isAppForeground = packageName != null
- && mActivityManager.getPackageImportance(packageName) == IMPORTANCE_FOREGROUND;
- ArrayList<String> bubbleKeysToRemove = new ArrayList<>();
- if (shortcutBubbles != null) {
- // If we can't find one of our bubbles in the shortcut list, that bubble needs
- // to be removed.
- for (String shortcutId : shortcutBubbles.keySet()) {
- boolean foundShortcut = false;
- for (int i = 0; i < shortcuts.size(); i++) {
- if (shortcuts.get(i).getId().equals(shortcutId)) {
- foundShortcut = true;
- break;
- }
- }
- if (!foundShortcut) {
- bubbleKeysToRemove.add(shortcutBubbles.get(shortcutId));
- }
- }
- }
-
- // Do the removals
- for (int i = 0; i < bubbleKeysToRemove.size(); i++) {
- // update flag bubble
- String bubbleKey = bubbleKeysToRemove.get(i);
- synchronized (mNotificationLock) {
- NotificationRecord r = mNotificationsByKey.get(bubbleKey);
- if (r != null) {
- final StatusBarNotification n = r.getSbn();
- final int callingUid = n.getUid();
- final String pkg = n.getPackageName();
- applyFlagBubble(r, pkg, callingUid, null /* oldEntry */, isAppForeground);
- mHandler.post(new EnqueueNotificationRunnable(user.getIdentifier(), r,
- false /* isAppForeground */));
- }
- }
- }
- }
- };
-
-
private final class SettingsObserver extends ContentObserver {
private final Uri NOTIFICATION_BADGING_URI
= Settings.Secure.getUriFor(Settings.Secure.NOTIFICATION_BADGING);
@@ -1763,8 +1716,8 @@
}
@VisibleForTesting
- void setLauncherApps(LauncherApps launcherApps) {
- mLauncherAppsService = launcherApps;
+ ShortcutHelper getShortcutHelper() {
+ return mShortcutHelper;
}
@VisibleForTesting
@@ -2189,19 +2142,19 @@
private void registerNotificationPreferencesPullers() {
mPullAtomCallback = new StatsPullAtomCallbackImpl();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
PACKAGE_NOTIFICATION_PREFERENCES,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
mPullAtomCallback
);
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
PACKAGE_NOTIFICATION_CHANNEL_PREFERENCES,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
mPullAtomCallback
);
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
PACKAGE_NOTIFICATION_CHANNEL_GROUP_PREFERENCES,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2314,8 +2267,13 @@
mRoleObserver = new RoleObserver(getContext().getSystemService(RoleManager.class),
mPackageManager, getContext().getMainExecutor());
mRoleObserver.init();
- mLauncherAppsService =
+ LauncherApps launcherApps =
(LauncherApps) getContext().getSystemService(Context.LAUNCHER_APPS_SERVICE);
+ mShortcutHelper = new ShortcutHelper(launcherApps, mShortcutListener);
+ BubbleExtractor bubbsExtractor = mRankingHelper.findExtractor(BubbleExtractor.class);
+ if (bubbsExtractor != null) {
+ bubbsExtractor.setShortcutHelper(mShortcutHelper);
+ }
registerNotificationPreferencesPullers();
} else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
// This observer will force an update when observe is called, causing us to
@@ -2684,6 +2642,7 @@
mHistoryManager.addNotification(new HistoricalNotification.Builder()
.setPackage(r.getSbn().getPackageName())
.setUid(r.getSbn().getUid())
+ .setUserId(r.getUserId())
.setChannelId(r.getChannel().getId())
.setChannelName(r.getChannel().getName().toString())
.setPostedTimeMs(System.currentTimeMillis())
@@ -3457,7 +3416,7 @@
ArrayList<ConversationChannelWrapper> conversations =
mPreferencesHelper.getConversations(onlyImportant);
for (ConversationChannelWrapper conversation : conversations) {
- conversation.setShortcutInfo(getShortcutInfo(
+ conversation.setShortcutInfo(mShortcutHelper.getShortcutInfo(
conversation.getNotificationChannel().getConversationId(),
conversation.getPkg(),
UserHandle.of(UserHandle.getUserId(conversation.getUid()))));
@@ -3480,7 +3439,7 @@
ArrayList<ConversationChannelWrapper> conversations =
mPreferencesHelper.getConversations(pkg, uid);
for (ConversationChannelWrapper conversation : conversations) {
- conversation.setShortcutInfo(getShortcutInfo(
+ conversation.setShortcutInfo(mShortcutHelper.getShortcutInfo(
conversation.getNotificationChannel().getConversationId(),
pkg,
UserHandle.of(UserHandle.getUserId(uid))));
@@ -5651,7 +5610,7 @@
}
}
- r.setShortcutInfo(getShortcutInfo(notification.getShortcutId(), pkg, user));
+ r.setShortcutInfo(mShortcutHelper.getShortcutInfo(notification.getShortcutId(), pkg, user));
if (!checkDisqualifyingFeatures(userId, notificationUid, id, tag, r,
r.getSbn().getOverrideGroupKey() != null)) {
@@ -5779,16 +5738,12 @@
}
/**
- * Updates the flags for this notification to reflect whether it is a bubble or not. Some
- * bubble specific flags only work if the app is foreground, this will strip those flags
+ * Some bubble specific flags only work if the app is foreground, this will strip those flags
* if the app wasn't foreground.
*/
- private void updateNotificationBubbleFlags(NotificationRecord r, String pkg, int userId,
- NotificationRecord oldRecord, boolean isAppForeground) {
- Notification notification = r.getNotification();
- applyFlagBubble(r, pkg, userId, oldRecord, true /* desiredFlag */);
-
+ private void updateNotificationBubbleFlags(NotificationRecord r, boolean isAppForeground) {
// Remove any bubble specific flags that only work when foregrounded
+ Notification notification = r.getNotification();
Notification.BubbleMetadata metadata = notification.getBubbleMetadata();
if (!isAppForeground && metadata != null) {
int flags = metadata.getFlags();
@@ -5798,252 +5753,30 @@
}
}
- /**
- * Handles actually applying or removing {@link Notification#FLAG_BUBBLE}. Performs necessary
- * checks for the provided record to see if it can actually be a bubble.
- * Tracks shortcut based bubbles so that we can find out if they've changed or been removed.
- */
- private void applyFlagBubble(NotificationRecord r, String pkg, int userId,
- NotificationRecord oldRecord, boolean desiredFlag) {
- boolean applyFlag = desiredFlag
- && isNotificationAppropriateToBubble(r, pkg, userId, oldRecord);
- final String shortcutId = r.getNotification().getBubbleMetadata() != null
- ? r.getNotification().getBubbleMetadata().getShortcutId()
- : null;
- if (applyFlag) {
- if (shortcutId != null) {
- // Must track shortcut based bubbles in case the shortcut is removed
- HashMap<String, String> packageBubbles = mActiveShortcutBubbles.get(
- r.getSbn().getPackageName());
- if (packageBubbles == null) {
- packageBubbles = new HashMap<>();
+ private ShortcutHelper.ShortcutListener mShortcutListener =
+ new ShortcutHelper.ShortcutListener() {
+ @Override
+ public void onShortcutRemoved(String key) {
+ String packageName;
+ synchronized (mNotificationLock) {
+ NotificationRecord r = mNotificationsByKey.get(key);
+ packageName = r != null ? r.getSbn().getPackageName() : null;
+ }
+ boolean isAppForeground = packageName != null
+ && mActivityManager.getPackageImportance(packageName)
+ == IMPORTANCE_FOREGROUND;
+ synchronized (mNotificationLock) {
+ NotificationRecord r = mNotificationsByKey.get(key);
+ if (r != null) {
+ // Enqueue will trigger resort & flag is updated that way.
+ r.getNotification().flags |= FLAG_ONLY_ALERT_ONCE;
+ mHandler.post(
+ new NotificationManagerService.EnqueueNotificationRunnable(
+ r.getUser().getIdentifier(), r, isAppForeground));
+ }
+ }
}
- packageBubbles.put(shortcutId, r.getKey());
- mActiveShortcutBubbles.put(r.getSbn().getPackageName(), packageBubbles);
- if (!mLauncherAppsCallbackRegistered) {
- mLauncherAppsService.registerCallback(mLauncherAppsCallback, mHandler);
- mLauncherAppsCallbackRegistered = true;
- }
- }
- r.getNotification().flags |= FLAG_BUBBLE;
- } else {
- if (shortcutId != null) {
- // No longer track shortcut
- HashMap<String, String> packageBubbles = mActiveShortcutBubbles.get(
- r.getSbn().getPackageName());
- if (packageBubbles != null) {
- packageBubbles.remove(shortcutId);
- }
- if (packageBubbles != null && packageBubbles.isEmpty()) {
- mActiveShortcutBubbles.remove(r.getSbn().getPackageName());
- }
- if (mLauncherAppsCallbackRegistered && mActiveShortcutBubbles.isEmpty()) {
- mLauncherAppsService.unregisterCallback(mLauncherAppsCallback);
- mLauncherAppsCallbackRegistered = false;
- }
- }
- r.getNotification().flags &= ~FLAG_BUBBLE;
- }
- }
-
- /**
- * @return whether the provided notification record is allowed to be represented as a bubble,
- * accounting for user choice & policy.
- */
- private boolean isNotificationAppropriateToBubble(NotificationRecord r, String pkg, int userId,
- NotificationRecord oldRecord) {
- Notification notification = r.getNotification();
- if (!canBubble(r, pkg, userId)) {
- // no log: canBubble has its own
- return false;
- }
-
- if (mActivityManager.isLowRamDevice()) {
- logBubbleError(r.getKey(), "low ram device");
- return false;
- }
-
- if (oldRecord != null && (oldRecord.getNotification().flags & FLAG_BUBBLE) != 0) {
- // This is an update to an active bubble
- return true;
- }
-
- // At this point the bubble must fulfill communication policy
-
- // Communication always needs a person
- ArrayList<Person> peopleList = notification.extras != null
- ? notification.extras.getParcelableArrayList(Notification.EXTRA_PEOPLE_LIST)
- : null;
- // Message style requires a person & it's not included in the list
- boolean isMessageStyle = Notification.MessagingStyle.class.equals(
- notification.getNotificationStyle());
- if (!isMessageStyle && (peopleList == null || peopleList.isEmpty())) {
- logBubbleError(r.getKey(), "Must have a person and be "
- + "Notification.MessageStyle or Notification.CATEGORY_CALL");
- return false;
- }
-
- // Communication is a message or a call
- boolean isCall = CATEGORY_CALL.equals(notification.category);
- boolean hasForegroundService = (notification.flags & FLAG_FOREGROUND_SERVICE) != 0;
- if (hasForegroundService && !isCall) {
- logBubbleError(r.getKey(),
- "foreground services must be Notification.CATEGORY_CALL to bubble");
- return false;
- }
- if (isMessageStyle) {
- if (hasValidRemoteInput(notification)) {
- return true;
- }
- logBubbleError(r.getKey(), "messages require valid remote input");
- return false;
- } else if (isCall) {
- if (hasForegroundService) {
- return true;
- }
- logBubbleError(r.getKey(), "calls require foreground service");
- return false;
- }
- logBubbleError(r.getKey(), "Must be "
- + "Notification.MessageStyle or Notification.CATEGORY_CALL");
- return false;
- }
-
- /**
- * @return whether the user has enabled the provided notification to bubble, does not account
- * for policy.
- */
- private boolean canBubble(NotificationRecord r, String pkg, int userId) {
- Notification notification = r.getNotification();
- Notification.BubbleMetadata metadata = notification.getBubbleMetadata();
- if (metadata == null) {
- // no log: no need to inform dev if they didn't attach bubble metadata
- return false;
- }
- if (!mPreferencesHelper.bubblesEnabled()) {
- logBubbleError(r.getKey(), "bubbles disabled for user: " + userId);
- return false;
- }
- if (!mPreferencesHelper.areBubblesAllowed(pkg, userId)) {
- logBubbleError(r.getKey(),
- "bubbles for package: " + pkg + " disabled for user: " + userId);
- return false;
- }
- if (!r.getChannel().canBubble()) {
- logBubbleError(r.getKey(),
- "bubbles for channel " + r.getChannel().getId() + " disabled");
- return false;
- }
-
- String shortcutId = metadata.getShortcutId();
- boolean shortcutValid = shortcutId != null
- && hasValidShortcutInfo(shortcutId, pkg, r.getUser());
- if (metadata.getBubbleIntent() == null && !shortcutValid) {
- // Should have a shortcut if intent is null
- logBubbleError(r.getKey(), "couldn't find shortcutId for bubble: " + shortcutId);
- return false;
- }
- if (shortcutValid) {
- return true;
- }
- // no log: canLaunch method has the failure log
- return canLaunchInActivityView(getContext(), metadata.getBubbleIntent(), pkg);
- }
-
- private boolean hasValidRemoteInput(Notification n) {
- // Also check for inline reply
- Notification.Action[] actions = n.actions;
- if (actions != null) {
- // Get the remote inputs
- for (int i = 0; i < actions.length; i++) {
- Notification.Action action = actions[i];
- RemoteInput[] inputs = action.getRemoteInputs();
- if (inputs != null && inputs.length > 0) {
- return true;
- }
- }
- }
- return false;
- }
-
- private ShortcutInfo getShortcutInfo(String shortcutId, String packageName, UserHandle user) {
- final long token = Binder.clearCallingIdentity();
- try {
- if (shortcutId == null || packageName == null || user == null) {
- return null;
- }
- LauncherApps.ShortcutQuery query = new LauncherApps.ShortcutQuery();
- if (packageName != null) {
- query.setPackage(packageName);
- }
- if (shortcutId != null) {
- query.setShortcutIds(Arrays.asList(shortcutId));
- }
- query.setQueryFlags(FLAG_MATCH_DYNAMIC | FLAG_MATCH_PINNED | FLAG_MATCH_CACHED);
- List<ShortcutInfo> shortcuts = mLauncherAppsService.getShortcuts(query, user);
- ShortcutInfo shortcutInfo = shortcuts != null && shortcuts.size() > 0
- ? shortcuts.get(0)
- : null;
- return shortcutInfo;
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
-
- private boolean hasValidShortcutInfo(String shortcutId, String packageName, UserHandle user) {
- ShortcutInfo shortcutInfo = getShortcutInfo(shortcutId, packageName, user);
- return shortcutInfo != null && shortcutInfo.isLongLived();
- }
-
- private void logBubbleError(String key, String failureMessage) {
- if (DBG) {
- Log.w(TAG, "Bubble notification: " + key + " failed: " + failureMessage);
- }
- }
- /**
- * Whether an intent is properly configured to display in an {@link android.app.ActivityView}.
- *
- * @param context the context to use.
- * @param pendingIntent the pending intent of the bubble.
- * @param packageName the notification package name for this bubble.
- */
- // Keep checks in sync with BubbleController#canLaunchInActivityView.
- @VisibleForTesting
- protected boolean canLaunchInActivityView(Context context, PendingIntent pendingIntent,
- String packageName) {
- if (pendingIntent == null) {
- Log.w(TAG, "Unable to create bubble -- no intent");
- return false;
- }
-
- // Need escalated privileges to get the intent.
- final long token = Binder.clearCallingIdentity();
- Intent intent;
- try {
- intent = pendingIntent.getIntent();
- } finally {
- Binder.restoreCallingIdentity(token);
- }
-
- ActivityInfo info = intent != null
- ? intent.resolveActivityInfo(context.getPackageManager(), 0)
- : null;
- if (info == null) {
- FrameworkStatsLog.write(FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
- BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING);
- Log.w(TAG, "Unable to send as bubble -- couldn't find activity info for intent: "
- + intent);
- return false;
- }
- if (!ActivityInfo.isResizeableMode(info.resizeMode)) {
- FrameworkStatsLog.write(FrameworkStatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
- BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE);
- Log.w(TAG, "Unable to send as bubble -- activity is not resizable for intent: "
- + intent);
- return false;
- }
- return true;
- }
+ };
private void doChannelWarningToast(CharSequence toastText) {
Binder.withCleanCallingIdentity(() -> {
@@ -6149,6 +5882,9 @@
MetricsLogger.action(r.getLogMaker()
.setType(MetricsProto.MetricsEvent.TYPE_UPDATE)
.setCategory(MetricsProto.MetricsEvent.NOTIFICATION_SNOOZED));
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_NOT_POSTED_SNOOZED,
+ r);
if (DBG) {
Slog.d(TAG, "Ignored enqueue for snoozed notification " + r.getKey());
}
@@ -6278,6 +6014,8 @@
mDuration)
.addTaggedData(MetricsEvent.NOTIFICATION_SNOOZED_CRITERIA,
mSnoozeCriterionId == null ? 0 : 1));
+ mNotificationRecordLogger.log(
+ NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED, r);
reportUserInteraction(r);
boolean wasPosted = removeFromNotificationListsLocked(r);
cancelNotificationLocked(r, false, REASON_SNOOZED, wasPosted, null);
@@ -6405,6 +6143,8 @@
cancelGroupChildrenLocked(r, mCallingUid, mCallingPid, listenerName,
mSendDelete, childrenFlagChecker);
updateLightsLocked();
+ mShortcutHelper.maybeListenForShortcutChangesForBubbles(r, true /* isRemoved */,
+ mHandler);
} else {
// No notification was found, assume that it is snoozed and cancel it.
if (mReason != REASON_SNOOZED) {
@@ -6472,7 +6212,7 @@
final String tag = n.getTag();
// We need to fix the notification up a little for bubbles
- updateNotificationBubbleFlags(r, pkg, callingUid, old, isAppForeground);
+ updateNotificationBubbleFlags(r, isAppForeground);
// Handle grouped notifications and bail out early if we
// can to avoid extracting signals.
@@ -6642,6 +6382,10 @@
+ n.getPackageName());
}
+ mShortcutHelper.maybeListenForShortcutChangesForBubbles(r,
+ false /* isRemoved */,
+ mHandler);
+
maybeRecordInterruptionLocked(r);
// Log event to statsd
@@ -7401,6 +7145,7 @@
int[] visibilities = new int[N];
boolean[] showBadges = new boolean[N];
boolean[] allowBubbles = new boolean[N];
+ boolean[] isBubble = new boolean[N];
ArrayList<NotificationChannel> channelBefore = new ArrayList<>(N);
ArrayList<String> groupKeyBefore = new ArrayList<>(N);
ArrayList<ArrayList<String>> overridePeopleBefore = new ArrayList<>(N);
@@ -7416,6 +7161,7 @@
visibilities[i] = r.getPackageVisibilityOverride();
showBadges[i] = r.canShowBadge();
allowBubbles[i] = r.canBubble();
+ isBubble[i] = r.getNotification().isBubbleNotification();
channelBefore.add(r.getChannel());
groupKeyBefore.add(r.getGroupKey());
overridePeopleBefore.add(r.getPeopleOverride());
@@ -7434,6 +7180,7 @@
|| visibilities[i] != r.getPackageVisibilityOverride()
|| showBadges[i] != r.canShowBadge()
|| allowBubbles[i] != r.canBubble()
+ || isBubble[i] != r.getNotification().isBubbleNotification()
|| !Objects.equals(channelBefore.get(i), r.getChannel())
|| !Objects.equals(groupKeyBefore.get(i), r.getGroupKey())
|| !Objects.equals(overridePeopleBefore.get(i), r.getPeopleOverride())
@@ -8596,7 +8343,8 @@
record.canBubble(),
record.isInterruptive(),
record.isConversation(),
- record.getShortcutInfo()
+ record.getShortcutInfo(),
+ record.getNotification().isBubbleNotification()
);
rankings.add(ranking);
}
diff --git a/services/core/java/com/android/server/notification/NotificationRecordLogger.java b/services/core/java/com/android/server/notification/NotificationRecordLogger.java
index f4ee461..6c833f9 100644
--- a/services/core/java/com/android/server/notification/NotificationRecordLogger.java
+++ b/services/core/java/com/android/server/notification/NotificationRecordLogger.java
@@ -34,11 +34,14 @@
import java.util.Objects;
/**
- * Interface for writing NotificationReported atoms to statsd log.
+ * Interface for writing NotificationReported atoms to statsd log. Use NotificationRecordLoggerImpl
+ * in production. Use NotificationRecordLoggerFake for testing.
* @hide
*/
public interface NotificationRecordLogger {
+ // The high-level interface used by clients.
+
/**
* May log a NotificationReported atom reflecting the posting or update of a notification.
* @param r The new NotificationRecord. If null, no action is taken.
@@ -57,9 +60,11 @@
* @param reason The reason the notification was canceled.
* @param dismissalSurface The surface the notification was dismissed from.
*/
- void logNotificationCancelled(@Nullable NotificationRecord r,
+ default void logNotificationCancelled(@Nullable NotificationRecord r,
@NotificationListenerService.NotificationCancelReason int reason,
- @NotificationStats.DismissalSurface int dismissalSurface);
+ @NotificationStats.DismissalSurface int dismissalSurface) {
+ log(NotificationCancelledEvent.fromCancelReason(reason, dismissalSurface), r);
+ }
/**
* Logs a notification visibility change event using UiEventReported (event ids from the
@@ -67,7 +72,17 @@
* @param r The NotificationRecord. If null, no action is taken.
* @param visible True if the notification became visible.
*/
- void logNotificationVisibility(@Nullable NotificationRecord r, boolean visible);
+ default void logNotificationVisibility(@Nullable NotificationRecord r, boolean visible) {
+ log(NotificationEvent.fromVisibility(visible), r);
+ }
+
+ // The UiEventReported logging methods are implemented in terms of this lower-level interface.
+
+ /** Logs a UiEventReported event for the given notification. */
+ void log(UiEventLogger.UiEventEnum event, NotificationRecord r);
+
+ /** Logs a UiEventReported event that is not associated with any notification. */
+ void log(UiEventLogger.UiEventEnum event);
/**
* The UiEvent enums that this class can log.
@@ -204,7 +219,30 @@
@UiEvent(doc = "Notification became visible.")
NOTIFICATION_OPEN(197),
@UiEvent(doc = "Notification stopped being visible.")
- NOTIFICATION_CLOSE(198);
+ NOTIFICATION_CLOSE(198),
+ @UiEvent(doc = "Notification was snoozed.")
+ NOTIFICATION_SNOOZED(317),
+ @UiEvent(doc = "Notification was not posted because its app is snoozed.")
+ NOTIFICATION_NOT_POSTED_SNOOZED(319),
+ @UiEvent(doc = "Notification was clicked.")
+ NOTIFICATION_CLICKED(320),
+ @UiEvent(doc = "Notification action was clicked.")
+ NOTIFICATION_ACTION_CLICKED(321),
+ @UiEvent(doc = "Notification detail was expanded due to non-user action.")
+ NOTIFICATION_DETAIL_OPEN_SYSTEM(327),
+ @UiEvent(doc = "Notification detail was collapsed due to non-user action.")
+ NOTIFICATION_DETAIL_CLOSE_SYSTEM(328),
+ @UiEvent(doc = "Notification detail was expanded due to user action.")
+ NOTIFICATION_DETAIL_OPEN_USER(329),
+ @UiEvent(doc = "Notification detail was collapsed due to user action.")
+ NOTIFICATION_DETAIL_CLOSE_USER(330),
+ @UiEvent(doc = "Notification direct reply action was used.")
+ NOTIFICATION_DIRECT_REPLIED(331),
+ @UiEvent(doc = "Notification smart reply action was used.")
+ NOTIFICATION_SMART_REPLIED(332),
+ @UiEvent(doc = "Notification smart reply action was visible.")
+ NOTIFICATION_SMART_REPLY_VISIBLE(333),
+ ;
private final int mId;
NotificationEvent(int id) {
@@ -217,7 +255,29 @@
public static NotificationEvent fromVisibility(boolean visible) {
return visible ? NOTIFICATION_OPEN : NOTIFICATION_CLOSE;
}
+ public static NotificationEvent fromExpanded(boolean expanded, boolean userAction) {
+ if (userAction) {
+ return expanded ? NOTIFICATION_DETAIL_OPEN_USER : NOTIFICATION_DETAIL_CLOSE_USER;
+ }
+ return expanded ? NOTIFICATION_DETAIL_OPEN_SYSTEM : NOTIFICATION_DETAIL_CLOSE_SYSTEM;
+ }
}
+
+ enum NotificationPanelEvent implements UiEventLogger.UiEventEnum {
+ @UiEvent(doc = "Notification panel became visible.")
+ NOTIFICATION_PANEL_OPEN(325),
+ @UiEvent(doc = "Notification panel stopped being visible.")
+ NOTIFICATION_PANEL_CLOSE(326);
+
+ private final int mId;
+ NotificationPanelEvent(int id) {
+ mId = id;
+ }
+ @Override public int getId() {
+ return mId;
+ }
+ }
+
/**
* A helper for extracting logging information from one or two NotificationRecords.
*/
diff --git a/services/core/java/com/android/server/notification/NotificationRecordLoggerImpl.java b/services/core/java/com/android/server/notification/NotificationRecordLoggerImpl.java
index 9fcac25..494ff31 100644
--- a/services/core/java/com/android/server/notification/NotificationRecordLoggerImpl.java
+++ b/services/core/java/com/android/server/notification/NotificationRecordLoggerImpl.java
@@ -65,20 +65,16 @@
}
@Override
- public void logNotificationCancelled(NotificationRecord r, int reason, int dismissalSurface) {
- log(NotificationCancelledEvent.fromCancelReason(reason, dismissalSurface), r);
- }
-
- @Override
- public void logNotificationVisibility(NotificationRecord r, boolean visible) {
- log(NotificationEvent.fromVisibility(visible), r);
- }
-
- void log(UiEventLogger.UiEventEnum event, NotificationRecord r) {
+ public void log(UiEventLogger.UiEventEnum event, NotificationRecord r) {
if (r == null) {
return;
}
mUiEventLogger.logWithInstanceId(event, r.getUid(), r.getSbn().getPackageName(),
r.getSbn().getInstanceId());
}
+
+ @Override
+ public void log(UiEventLogger.UiEventEnum event) {
+ mUiEventLogger.log(event);
+ }
}
diff --git a/services/core/java/com/android/server/notification/ShortcutHelper.java b/services/core/java/com/android/server/notification/ShortcutHelper.java
new file mode 100644
index 0000000..7bbb3b1
--- /dev/null
+++ b/services/core/java/com/android/server/notification/ShortcutHelper.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2020 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.notification;
+
+import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_CACHED;
+import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC;
+import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED;
+
+import android.annotation.NonNull;
+import android.content.pm.LauncherApps;
+import android.content.pm.ShortcutInfo;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.UserHandle;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+/**
+ * Helper for querying shortcuts.
+ */
+class ShortcutHelper {
+
+ /**
+ * Listener to call when a shortcut we're tracking has been removed.
+ */
+ interface ShortcutListener {
+ void onShortcutRemoved(String key);
+ }
+
+ private LauncherApps mLauncherAppsService;
+ private ShortcutListener mShortcutListener;
+
+ // Key: packageName Value: <shortcutId, notifId>
+ private HashMap<String, HashMap<String, String>> mActiveShortcutBubbles = new HashMap<>();
+ private boolean mLauncherAppsCallbackRegistered;
+
+ // Bubbles can be created based on a shortcut, we need to listen for changes to
+ // that shortcut so that we may update the bubble appropriately.
+ private final LauncherApps.Callback mLauncherAppsCallback = new LauncherApps.Callback() {
+ @Override
+ public void onPackageRemoved(String packageName, UserHandle user) {
+ }
+
+ @Override
+ public void onPackageAdded(String packageName, UserHandle user) {
+ }
+
+ @Override
+ public void onPackageChanged(String packageName, UserHandle user) {
+ }
+
+ @Override
+ public void onPackagesAvailable(String[] packageNames, UserHandle user,
+ boolean replacing) {
+ }
+
+ @Override
+ public void onPackagesUnavailable(String[] packageNames, UserHandle user,
+ boolean replacing) {
+ }
+
+ @Override
+ public void onShortcutsChanged(@NonNull String packageName,
+ @NonNull List<ShortcutInfo> shortcuts, @NonNull UserHandle user) {
+ HashMap<String, String> shortcutBubbles = mActiveShortcutBubbles.get(packageName);
+ ArrayList<String> bubbleKeysToRemove = new ArrayList<>();
+ if (shortcutBubbles != null) {
+ // If we can't find one of our bubbles in the shortcut list, that bubble needs
+ // to be removed.
+ for (String shortcutId : shortcutBubbles.keySet()) {
+ boolean foundShortcut = false;
+ for (int i = 0; i < shortcuts.size(); i++) {
+ if (shortcuts.get(i).getId().equals(shortcutId)) {
+ foundShortcut = true;
+ break;
+ }
+ }
+ if (!foundShortcut) {
+ bubbleKeysToRemove.add(shortcutBubbles.get(shortcutId));
+ }
+ }
+ }
+
+ // Let NoMan know about the updates
+ for (int i = 0; i < bubbleKeysToRemove.size(); i++) {
+ // update flag bubble
+ String bubbleKey = bubbleKeysToRemove.get(i);
+ if (mShortcutListener != null) {
+ mShortcutListener.onShortcutRemoved(bubbleKey);
+ }
+ }
+ }
+ };
+
+ ShortcutHelper(LauncherApps launcherApps, ShortcutListener listener) {
+ mLauncherAppsService = launcherApps;
+ mShortcutListener = listener;
+ }
+
+ @VisibleForTesting
+ void setLauncherApps(LauncherApps launcherApps) {
+ mLauncherAppsService = launcherApps;
+ }
+
+ ShortcutInfo getShortcutInfo(String shortcutId, String packageName, UserHandle user) {
+ if (mLauncherAppsService == null) {
+ return null;
+ }
+ final long token = Binder.clearCallingIdentity();
+ try {
+ if (shortcutId == null || packageName == null || user == null) {
+ return null;
+ }
+ LauncherApps.ShortcutQuery query = new LauncherApps.ShortcutQuery();
+ query.setPackage(packageName);
+ query.setShortcutIds(Arrays.asList(shortcutId));
+ query.setQueryFlags(FLAG_MATCH_DYNAMIC | FLAG_MATCH_PINNED | FLAG_MATCH_CACHED);
+ List<ShortcutInfo> shortcuts = mLauncherAppsService.getShortcuts(query, user);
+ return shortcuts != null && shortcuts.size() > 0
+ ? shortcuts.get(0)
+ : null;
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
+ boolean hasValidShortcutInfo(String shortcutId, String packageName,
+ UserHandle user) {
+ ShortcutInfo shortcutInfo = getShortcutInfo(shortcutId, packageName, user);
+ return shortcutInfo != null && shortcutInfo.isLongLived();
+ }
+
+ /**
+ * Shortcut based bubbles require some extra work to listen for shortcut changes.
+ *
+ * @param r the notification record to check
+ * @param removedNotification true if this notification is being removed
+ * @param handler handler to register the callback with
+ */
+ void maybeListenForShortcutChangesForBubbles(NotificationRecord r, boolean removedNotification,
+ Handler handler) {
+ final String shortcutId = r.getNotification().getBubbleMetadata() != null
+ ? r.getNotification().getBubbleMetadata().getShortcutId()
+ : null;
+ if (shortcutId == null) {
+ return;
+ }
+ if (r.getNotification().isBubbleNotification() && !removedNotification) {
+ // Must track shortcut based bubbles in case the shortcut is removed
+ HashMap<String, String> packageBubbles = mActiveShortcutBubbles.get(
+ r.getSbn().getPackageName());
+ if (packageBubbles == null) {
+ packageBubbles = new HashMap<>();
+ }
+ packageBubbles.put(shortcutId, r.getKey());
+ mActiveShortcutBubbles.put(r.getSbn().getPackageName(), packageBubbles);
+ if (!mLauncherAppsCallbackRegistered) {
+ mLauncherAppsService.registerCallback(mLauncherAppsCallback, handler);
+ mLauncherAppsCallbackRegistered = true;
+ }
+ } else {
+ // No longer track shortcut
+ HashMap<String, String> packageBubbles = mActiveShortcutBubbles.get(
+ r.getSbn().getPackageName());
+ if (packageBubbles != null) {
+ packageBubbles.remove(shortcutId);
+ }
+ if (packageBubbles != null && packageBubbles.isEmpty()) {
+ mActiveShortcutBubbles.remove(r.getSbn().getPackageName());
+ }
+ if (mLauncherAppsCallbackRegistered && mActiveShortcutBubbles.isEmpty()) {
+ mLauncherAppsService.unregisterCallback(mLauncherAppsCallback);
+ mLauncherAppsCallbackRegistered = false;
+ }
+ }
+ }
+}
diff --git a/services/core/java/com/android/server/om/OverlayActorEnforcer.java b/services/core/java/com/android/server/om/OverlayActorEnforcer.java
index 40efb7c..9197956 100644
--- a/services/core/java/com/android/server/om/OverlayActorEnforcer.java
+++ b/services/core/java/com/android/server/om/OverlayActorEnforcer.java
@@ -29,7 +29,6 @@
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.CollectionUtils;
-import com.android.server.SystemConfig;
import java.io.IOException;
import java.util.List;
@@ -38,6 +37,8 @@
/**
* Performs verification that a calling UID can act on a target package's overlayable.
*
+ * Actors requirements are specified in {@link android.content.om.OverlayManager}.
+ *
* @hide
*/
public class OverlayActorEnforcer {
@@ -99,13 +100,7 @@
}
/**
- * An actor is valid if any of the following is true:
- * - is {@link Process#ROOT_UID}, {@link Process#SYSTEM_UID}
- * - is the target overlay package
- * - has the CHANGE_OVERLAY_PACKAGES permission and an actor is not defined
- * - is the same the as the package defined in {@link SystemConfig#getNamedActors()} for a given
- * namespace and actor name
- *
+ * See {@link OverlayActorEnforcer} class comment for actor requirements.
* @return true if the actor is allowed to act on the target overlayInfo
*/
private ActorState isAllowedActor(String methodName, OverlayInfo overlayInfo,
diff --git a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
index 6c2d77c..8349632 100644
--- a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
+++ b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java
@@ -66,7 +66,7 @@
@RequiresPermission(android.Manifest.permission.DUMP)
public void startBugreport(int callingUidUnused, String callingPackage,
FileDescriptor bugreportFd, FileDescriptor screenshotFd,
- int bugreportMode, IDumpstateListener listener) {
+ int bugreportMode, IDumpstateListener listener, boolean isScreenshotRequested) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, "startBugreport");
Objects.requireNonNull(callingPackage);
Objects.requireNonNull(bugreportFd);
@@ -88,7 +88,7 @@
}
synchronized (mLock) {
startBugreportLocked(callingUid, callingPackage, bugreportFd, screenshotFd,
- bugreportMode, listener);
+ bugreportMode, listener, isScreenshotRequested);
}
}
@@ -145,7 +145,7 @@
@GuardedBy("mLock")
private void startBugreportLocked(int callingUid, String callingPackage,
FileDescriptor bugreportFd, FileDescriptor screenshotFd,
- int bugreportMode, IDumpstateListener listener) {
+ int bugreportMode, IDumpstateListener listener, boolean isScreenshotRequested) {
if (isDumpstateBinderServiceRunningLocked()) {
Slog.w(TAG, "'dumpstate' is already running. Cannot start a new bugreport"
+ " while another one is currently in progress.");
@@ -165,7 +165,7 @@
IDumpstateListener myListener = new DumpstateListener(listener, ds);
try {
ds.startBugreport(callingUid, callingPackage,
- bugreportFd, screenshotFd, bugreportMode, myListener);
+ bugreportFd, screenshotFd, bugreportMode, myListener, isScreenshotRequested);
} catch (RemoteException e) {
// bugreportd service is already started now. We need to kill it to manage the
// lifecycle correctly. If we don't subsequent callers will get
diff --git a/services/core/java/com/android/server/pm/ApexManager.java b/services/core/java/com/android/server/pm/ApexManager.java
index d12e03d..c37ea8b 100644
--- a/services/core/java/com/android/server/pm/ApexManager.java
+++ b/services/core/java/com/android/server/pm/ApexManager.java
@@ -301,6 +301,14 @@
public abstract boolean destroyDeSnapshots(int rollbackId);
/**
+ * Deletes snapshots of the credential encrypted apex data directories for the specified user,
+ * where the rollback id is not included in {@code retainRollbackIds}.
+ *
+ * @return boolean true if the delete was successful
+ */
+ public abstract boolean destroyCeSnapshotsNotSpecified(int userId, int[] retainRollbackIds);
+
+ /**
* Dumps various state information to the provided {@link PrintWriter} object.
*
* @param pw the {@link PrintWriter} object to send information to.
@@ -745,6 +753,17 @@
}
}
+ @Override
+ public boolean destroyCeSnapshotsNotSpecified(int userId, int[] retainRollbackIds) {
+ try {
+ mApexService.destroyCeSnapshotsNotSpecified(userId, retainRollbackIds);
+ return true;
+ } catch (Exception e) {
+ Slog.e(TAG, e.getMessage(), e);
+ return false;
+ }
+ }
+
/**
* Dump information about the packages contained in a particular cache
* @param packagesCache the cache to print information about.
@@ -963,6 +982,11 @@
}
@Override
+ public boolean destroyCeSnapshotsNotSpecified(int userId, int[] retainRollbackIds) {
+ return true;
+ }
+
+ @Override
void dump(PrintWriter pw, String packageName) {
// No-op
}
diff --git a/services/core/java/com/android/server/pm/AppsFilter.java b/services/core/java/com/android/server/pm/AppsFilter.java
index b90681d..79a4da2 100644
--- a/services/core/java/com/android/server/pm/AppsFilter.java
+++ b/services/core/java/com/android/server/pm/AppsFilter.java
@@ -388,7 +388,7 @@
for (int i = ArrayUtils.size(intents) - 1; i >= 0; i--) {
IntentFilter intentFilter = intents.get(i);
if (intentFilter.match(intent.getAction(), intent.getType(), intent.getScheme(),
- intent.getData(), intent.getCategories(), "AppsFilter") > 0) {
+ intent.getData(), intent.getCategories(), "AppsFilter", true) > 0) {
return true;
}
}
diff --git a/services/core/java/com/android/server/pm/CrossProfileAppsServiceImpl.java b/services/core/java/com/android/server/pm/CrossProfileAppsServiceImpl.java
index ec9b37d..83da381 100644
--- a/services/core/java/com/android/server/pm/CrossProfileAppsServiceImpl.java
+++ b/services/core/java/com/android/server/pm/CrossProfileAppsServiceImpl.java
@@ -45,6 +45,7 @@
import android.content.pm.PackageManagerInternal;
import android.content.pm.ResolveInfo;
import android.os.Binder;
+import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -183,7 +184,8 @@
String callingFeatureId,
Intent intent,
@UserIdInt int userId,
- IBinder callingActivity) throws RemoteException {
+ IBinder callingActivity,
+ Bundle options) throws RemoteException {
Objects.requireNonNull(callingPackage);
Objects.requireNonNull(intent);
Objects.requireNonNull(intent.getComponent(), "The intent must have a Component set");
@@ -226,7 +228,7 @@
launchIntent,
callingActivity,
/* startFlags= */ 0,
- /* options= */ null,
+ options,
userId);
logStartActivityByIntent(callingPackage);
}
diff --git a/services/core/java/com/android/server/pm/DataLoaderManagerService.java b/services/core/java/com/android/server/pm/DataLoaderManagerService.java
index ad20d38..8eb773a 100644
--- a/services/core/java/com/android/server/pm/DataLoaderManagerService.java
+++ b/services/core/java/com/android/server/pm/DataLoaderManagerService.java
@@ -116,9 +116,6 @@
return null;
}
- // TODO(b/136132412): better way to enable privileged data loaders in tests
- boolean checkLoader =
- android.os.SystemProperties.getBoolean("incremental.check_loader", false);
int numServices = services.size();
for (int i = 0; i < numServices; i++) {
ResolveInfo ri = services.get(i);
@@ -128,7 +125,7 @@
// If there's more than one, return the first one found.
try {
ApplicationInfo ai = pm.getApplicationInfo(resolved.getPackageName(), 0);
- if (checkLoader && !ai.isPrivilegedApp()) {
+ if (!ai.isPrivilegedApp()) {
Slog.w(TAG,
"Data loader: " + resolved + " is not a privileged app, skipping.");
continue;
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 33ef2d4..cdc3736 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -805,26 +805,30 @@
public SessionInfo getSessionInfo(int sessionId) {
synchronized (mSessions) {
final PackageInstallerSession session = mSessions.get(sessionId);
- return session != null ? session.generateInfo() : null;
+
+ return session != null
+ ? session.generateInfoForCaller(true /*withIcon*/, Binder.getCallingUid())
+ : null;
}
}
@Override
public ParceledListSlice<SessionInfo> getStagedSessions() {
- return mStagingManager.getSessions();
+ return mStagingManager.getSessions(Binder.getCallingUid());
}
@Override
public ParceledListSlice<SessionInfo> getAllSessions(int userId) {
+ final int callingUid = Binder.getCallingUid();
mPermissionManager.enforceCrossUserPermission(
- Binder.getCallingUid(), userId, true, false, "getAllSessions");
+ callingUid, userId, true, false, "getAllSessions");
final List<SessionInfo> result = new ArrayList<>();
synchronized (mSessions) {
for (int i = 0; i < mSessions.size(); i++) {
final PackageInstallerSession session = mSessions.valueAt(i);
if (session.userId == userId && !session.hasParentSessionId()) {
- result.add(session.generateInfo(false));
+ result.add(session.generateInfoForCaller(false, callingUid));
}
}
}
@@ -842,7 +846,8 @@
for (int i = 0; i < mSessions.size(); i++) {
final PackageInstallerSession session = mSessions.valueAt(i);
- SessionInfo info = session.generateInfo(false);
+ SessionInfo info =
+ session.generateInfoForCaller(false /*withIcon*/, Process.SYSTEM_UID);
if (Objects.equals(info.getInstallerPackageName(), installerPackageName)
&& session.userId == userId && !session.hasParentSessionId()) {
result.add(info);
@@ -1302,7 +1307,10 @@
session.markUpdated();
writeSessionsAsync();
if (mOkToSendBroadcasts) {
- mPm.sendSessionUpdatedBroadcast(session.generateInfo(false),
+ // we don't scrub the data here as this is sent only to the installer several
+ // privileged system packages
+ mPm.sendSessionUpdatedBroadcast(
+ session.generateInfoForCaller(false/*icon*/, Process.SYSTEM_UID),
session.userId);
}
}
diff --git a/services/core/java/com/android/server/pm/PackageInstallerSession.java b/services/core/java/com/android/server/pm/PackageInstallerSession.java
index 97aa79d..28d7c13 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerSession.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerSession.java
@@ -16,6 +16,7 @@
package com.android.server.pm;
+import static android.app.AppOpsManager.MODE_DEFAULT;
import static android.content.pm.DataLoaderType.INCREMENTAL;
import static android.content.pm.DataLoaderType.STREAMING;
import static android.content.pm.PackageInstaller.LOCATION_DATA_APP;
@@ -166,6 +167,8 @@
private static final String TAG_GRANTED_RUNTIME_PERMISSION = "granted-runtime-permission";
private static final String TAG_WHITELISTED_RESTRICTED_PERMISSION =
"whitelisted-restricted-permission";
+ private static final String TAG_AUTO_REVOKE_PERMISSIONS_MODE =
+ "auto-revoke-permissions-mode";
private static final String ATTR_SESSION_ID = "sessionId";
private static final String ATTR_USER_ID = "userId";
private static final String ATTR_INSTALLER_PACKAGE_NAME = "installerPackageName";
@@ -311,8 +314,41 @@
@GuardedBy("mLock")
private int mParentSessionId;
+ static class FileEntry {
+ private final int mIndex;
+ private final InstallationFile mFile;
+
+ FileEntry(int index, InstallationFile file) {
+ this.mIndex = index;
+ this.mFile = file;
+ }
+
+ int getIndex() {
+ return this.mIndex;
+ }
+
+ InstallationFile getFile() {
+ return this.mFile;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof FileEntry)) {
+ return false;
+ }
+ final FileEntry rhs = (FileEntry) obj;
+ return (mFile.getLocation() == rhs.mFile.getLocation()) && TextUtils.equals(
+ mFile.getName(), rhs.mFile.getName());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mFile.getLocation(), mFile.getName());
+ }
+ }
+
@GuardedBy("mLock")
- private ArrayList<InstallationFile> mFiles = new ArrayList<>();
+ private ArraySet<FileEntry> mFiles = new ArraySet<>();
@GuardedBy("mLock")
private boolean mStagedSessionApplied;
@@ -516,8 +552,12 @@
this.mParentSessionId = parentSessionId;
if (files != null) {
- for (InstallationFile file : files) {
- mFiles.add(file);
+ for (int i = 0, size = files.length; i < size; ++i) {
+ InstallationFile file = files[i];
+ if (!mFiles.add(new FileEntry(i, file))) {
+ throw new IllegalArgumentException(
+ "Trying to add a duplicate installation file");
+ }
}
}
@@ -557,11 +597,41 @@
}
}
- public SessionInfo generateInfo() {
- return generateInfo(true);
+ /**
+ * Returns {@code true} if the {@link SessionInfo} object should be produced with potentially
+ * sensitive data scrubbed from its fields.
+ *
+ * @param callingUid the uid of the caller; the recipient of the {@link SessionInfo} that may
+ * need to be scrubbed
+ */
+ private boolean shouldScrubData(int callingUid) {
+ return !(callingUid < Process.FIRST_APPLICATION_UID || getInstallerUid() == callingUid);
}
- public SessionInfo generateInfo(boolean includeIcon) {
+ /**
+ * Generates a {@link SessionInfo} object for the provided uid. This may result in some fields
+ * that may contain sensitive info being filtered.
+ *
+ * @param includeIcon true if the icon should be included in the object
+ * @param callingUid the uid of the caller; the recipient of the {@link SessionInfo} that may
+ * need to be scrubbed
+ * @see #shouldScrubData(int)
+ */
+ public SessionInfo generateInfoForCaller(boolean includeIcon, int callingUid) {
+ return generateInfoInternal(includeIcon, shouldScrubData(callingUid));
+ }
+
+ /**
+ * Generates a {@link SessionInfo} object to ensure proper hiding of sensitive fields.
+ *
+ * @param includeIcon true if the icon should be included in the object
+ * @see #generateInfoForCaller(boolean, int)
+ */
+ public SessionInfo generateInfoScrubbed(boolean includeIcon) {
+ return generateInfoInternal(includeIcon, true /*scrubData*/);
+ }
+
+ private SessionInfo generateInfoInternal(boolean includeIcon, boolean scrubData) {
final SessionInfo info = new SessionInfo();
synchronized (mLock) {
info.sessionId = sessionId;
@@ -584,11 +654,16 @@
info.appLabel = params.appLabel;
info.installLocation = params.installLocation;
- info.originatingUri = params.originatingUri;
+ if (!scrubData) {
+ info.originatingUri = params.originatingUri;
+ }
info.originatingUid = params.originatingUid;
- info.referrerUri = params.referrerUri;
+ if (!scrubData) {
+ info.referrerUri = params.referrerUri;
+ }
info.grantedRuntimePermissions = params.grantedRuntimePermissions;
info.whitelistedRestrictedPermissions = params.whitelistedRestrictedPermissions;
+ info.autoRevokePermissionsMode = params.autoRevokePermissionsMode;
info.installFlags = params.installFlags;
info.isMultiPackage = params.isMultiPackage;
info.isStaged = params.isStaged;
@@ -716,9 +791,19 @@
return result;
}
- String[] result = new String[mFiles.size()];
- for (int i = 0, size = mFiles.size(); i < size; ++i) {
- result[i] = mFiles.get(i).getName();
+ InstallationFile[] files = getInstallationFilesLocked();
+ String[] result = new String[files.length];
+ for (int i = 0, size = files.length; i < size; ++i) {
+ result[i] = files[i].getName();
+ }
+ return result;
+ }
+
+ @GuardedBy("mLock")
+ private InstallationFile[] getInstallationFilesLocked() {
+ final InstallationFile[] result = new InstallationFile[mFiles.size()];
+ for (FileEntry fileEntry : mFiles) {
+ result[fileEntry.getIndex()] = fileEntry.getFile();
}
return result;
}
@@ -2410,7 +2495,10 @@
assertCallerIsOwnerOrRootLocked();
assertPreparedAndNotSealedLocked("addFile");
- mFiles.add(new InstallationFile(location, name, lengthBytes, metadata, signature));
+ if (!mFiles.add(new FileEntry(mFiles.size(),
+ new InstallationFile(location, name, lengthBytes, metadata, signature)))) {
+ throw new IllegalArgumentException("File already added: " + name);
+ }
}
}
@@ -2428,7 +2516,10 @@
assertCallerIsOwnerOrRootLocked();
assertPreparedAndNotSealedLocked("removeFile");
- mFiles.add(new InstallationFile(location, getRemoveMarkerName(name), -1, null, null));
+ if (!mFiles.add(new FileEntry(mFiles.size(),
+ new InstallationFile(location, getRemoveMarkerName(name), -1, null, null)))) {
+ throw new IllegalArgumentException("File already removed: " + name);
+ }
}
}
@@ -2448,7 +2539,8 @@
final List<InstallationFileParcel> addedFiles = new ArrayList<>();
final List<String> removedFiles = new ArrayList<>();
- for (InstallationFile file : mFiles) {
+ final InstallationFile[] files = getInstallationFilesLocked();
+ for (InstallationFile file : files) {
if (sAddedFilter.accept(new File(this.stageDir, file.getName()))) {
addedFiles.add(file.getData());
continue;
@@ -2664,7 +2756,7 @@
final boolean isNewInstall = extras == null || !extras.getBoolean(Intent.EXTRA_REPLACING);
if (success && isNewInstall && mPm.mInstallerService.okToSendBroadcasts()
&& (params.installFlags & PackageManager.INSTALL_DRY_RUN) == 0) {
- mPm.sendSessionCommitBroadcast(generateInfo(), userId);
+ mPm.sendSessionCommitBroadcast(generateInfoScrubbed(true /*icon*/), userId);
}
mCallback.onSessionFinished(this, success);
@@ -2855,6 +2947,13 @@
}
}
+ private static void writeAutoRevokePermissionsMode(@NonNull XmlSerializer out, int mode)
+ throws IOException {
+ out.startTag(null, TAG_AUTO_REVOKE_PERMISSIONS_MODE);
+ writeIntAttribute(out, ATTR_MODE, mode);
+ out.endTag(null, TAG_AUTO_REVOKE_PERMISSIONS_MODE);
+ }
+
private static File buildAppIconFile(int sessionId, @NonNull File sessionsDir) {
return new File(sessionsDir, "app_icon." + sessionId + ".png");
@@ -2935,6 +3034,7 @@
writeGrantedRuntimePermissionsLocked(out, params.grantedRuntimePermissions);
writeWhitelistedRestrictedPermissionsLocked(out,
params.whitelistedRestrictedPermissions);
+ writeAutoRevokePermissionsMode(out, params.autoRevokePermissionsMode);
// Persist app icon if changed since last written
File appIconFile = buildAppIconFile(sessionId, sessionsDir);
@@ -2961,7 +3061,9 @@
writeIntAttribute(out, ATTR_SESSION_ID, childSessionId);
out.endTag(null, TAG_CHILD_SESSION);
}
- for (InstallationFile file : mFiles) {
+
+ final InstallationFile[] files = getInstallationFilesLocked();
+ for (InstallationFile file : getInstallationFilesLocked()) {
out.startTag(null, TAG_SESSION_FILE);
writeIntAttribute(out, ATTR_LOCATION, file.getLocation());
writeStringAttribute(out, ATTR_NAME, file.getName());
@@ -3078,6 +3180,7 @@
// depth.
List<String> grantedRuntimePermissions = new ArrayList<>();
List<String> whitelistedRestrictedPermissions = new ArrayList<>();
+ int autoRevokePermissionsMode = MODE_DEFAULT;
List<Integer> childSessionIds = new ArrayList<>();
List<InstallationFile> files = new ArrayList<>();
int outerDepth = in.getDepth();
@@ -3094,6 +3197,9 @@
whitelistedRestrictedPermissions.add(readStringAttribute(in, ATTR_NAME));
}
+ if (TAG_AUTO_REVOKE_PERMISSIONS_MODE.equals(in.getName())) {
+ autoRevokePermissionsMode = readIntAttribute(in, ATTR_MODE);
+ }
if (TAG_CHILD_SESSION.equals(in.getName())) {
childSessionIds.add(readIntAttribute(in, ATTR_SESSION_ID, SessionInfo.INVALID_ID));
}
@@ -3116,6 +3222,8 @@
params.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions;
}
+ params.autoRevokePermissionsMode = autoRevokePermissionsMode;
+
int[] childSessionIdsArray;
if (childSessionIds.size() > 0) {
childSessionIdsArray = new int[childSessionIds.size()];
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 799ce65..24ebd32 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -24,6 +24,9 @@
import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+import static android.app.AppOpsManager.MODE_ALLOWED;
+import static android.app.AppOpsManager.MODE_DEFAULT;
+import static android.app.AppOpsManager.MODE_IGNORED;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_DEFAULT;
import static android.content.Intent.CATEGORY_HOME;
@@ -1654,12 +1657,13 @@
&& parentRes.pkg != null)
? parentRes.pkg.getRequestedPermissions()
: args.whitelistedRestrictedPermissions;
+ int autoRevokePermissionsMode = args.autoRevokePermissionsMode;
// Handle the parent package
handlePackagePostInstall(parentRes, grantPermissions,
killApp, virtualPreload, grantedPermissions,
- whitelistedRestrictedPermissions, didRestore,
- args.installSource.installerPackageName, args.observer,
+ whitelistedRestrictedPermissions, autoRevokePermissionsMode,
+ didRestore, args.installSource.installerPackageName, args.observer,
args.mDataLoaderType);
// Handle the child packages
@@ -1669,7 +1673,8 @@
PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
handlePackagePostInstall(childRes, grantPermissions,
killApp, virtualPreload, grantedPermissions,
- whitelistedRestrictedPermissions, false /*didRestore*/,
+ whitelistedRestrictedPermissions, autoRevokePermissionsMode,
+ false /*didRestore*/,
args.installSource.installerPackageName, args.observer,
args.mDataLoaderType);
}
@@ -1998,6 +2003,7 @@
private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
boolean killApp, boolean virtualPreload,
String[] grantedPermissions, List<String> whitelistedRestrictedPermissions,
+ int autoRevokePermissionsMode,
boolean launchedForRestore, String installerPackage,
IPackageInstallObserver2 installObserver, int dataLoaderType) {
final boolean succeeded = res.returnCode == PackageManager.INSTALL_SUCCEEDED;
@@ -2018,6 +2024,11 @@
Process.myUid(), FLAG_PERMISSION_WHITELIST_INSTALLER);
}
+ if (autoRevokePermissionsMode == MODE_ALLOWED || autoRevokePermissionsMode == MODE_IGNORED) {
+ mPermissionManager.setAutoRevokeWhitelisted(res.pkg.getPackageName(),
+ autoRevokePermissionsMode == MODE_IGNORED, UserHandle.myUserId());
+ }
+
// Now that we successfully installed the package, grant runtime
// permissions if requested before broadcasting the install. Also
// for legacy apps in permission review mode we clear the permission
@@ -11514,8 +11525,8 @@
"Static shared libs cannot declare permission groups");
}
- // Static shared libs cannot declare features
- if (!pkg.getFeatures().isEmpty()) {
+ // Static shared libs cannot declare attributions
+ if (!pkg.getAttributions().isEmpty()) {
throw new PackageManagerException(
"Static shared libs cannot declare features");
}
@@ -14295,6 +14306,7 @@
final String packageAbiOverride;
final String[] grantedRuntimePermissions;
final List<String> whitelistedRestrictedPermissions;
+ final int autoRevokePermissionsMode;
final VerificationInfo verificationInfo;
final PackageParser.SigningDetails signingDetails;
final int installReason;
@@ -14309,6 +14321,7 @@
int installFlags, InstallSource installSource, String volumeUuid,
VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
String[] grantedPermissions, List<String> whitelistedRestrictedPermissions,
+ int autoRevokePermissionsMode,
SigningDetails signingDetails, int installReason,
long requiredInstalledVersionCode, int dataLoaderType) {
super(user);
@@ -14322,6 +14335,7 @@
this.packageAbiOverride = packageAbiOverride;
this.grantedRuntimePermissions = grantedPermissions;
this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions;
+ this.autoRevokePermissionsMode = autoRevokePermissionsMode;
this.signingDetails = signingDetails;
this.installReason = installReason;
this.requiredInstalledVersionCode = requiredInstalledVersionCode;
@@ -14358,6 +14372,7 @@
packageAbiOverride = sessionParams.abiOverride;
grantedRuntimePermissions = sessionParams.grantedRuntimePermissions;
whitelistedRestrictedPermissions = sessionParams.whitelistedRestrictedPermissions;
+ autoRevokePermissionsMode = sessionParams.autoRevokePermissionsMode;
signingDetails = activeInstallSession.getSigningDetails();
requiredInstalledVersionCode = sessionParams.requiredInstalledVersionCode;
forceQueryableOverride = sessionParams.forceQueryableOverride;
@@ -14726,9 +14741,8 @@
verificationState.setRequiredVerifierUid(requiredUid);
final int installerUid =
verificationInfo == null ? -1 : verificationInfo.installerUid;
- if (!origin.existing && requiredUid != -1
- && isVerificationEnabled(
- pkgLite, verifierUser.getIdentifier(), installFlags, installerUid)) {
+ if (!origin.existing && isVerificationEnabled(pkgLite, verifierUser.getIdentifier(),
+ installFlags, installerUid)) {
final Intent verification = new Intent(
Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
@@ -14794,9 +14808,9 @@
}
}
- final ComponentName requiredVerifierComponent = matchComponentForVerifier(
- mRequiredVerifierPackage, receivers);
if (mRequiredVerifierPackage != null) {
+ final ComponentName requiredVerifierComponent = matchComponentForVerifier(
+ mRequiredVerifierPackage, receivers);
/*
* Send the intent to the required verification agent,
* but only start the verification timeout after the
@@ -14954,6 +14968,7 @@
final String abiOverride;
final String[] installGrantPermissions;
final List<String> whitelistedRestrictedPermissions;
+ final int autoRevokePermissionsMode;
/** If non-null, drop an async trace when the install completes */
final String traceMethod;
final int traceCookie;
@@ -14973,6 +14988,7 @@
UserHandle user, String[] instructionSets,
String abiOverride, String[] installGrantPermissions,
List<String> whitelistedRestrictedPermissions,
+ int autoRevokePermissionsMode,
String traceMethod, int traceCookie, SigningDetails signingDetails,
int installReason, boolean forceQueryableOverride,
MultiPackageInstallParams multiPackageInstallParams, int dataLoaderType) {
@@ -14987,6 +15003,7 @@
this.abiOverride = abiOverride;
this.installGrantPermissions = installGrantPermissions;
this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions;
+ this.autoRevokePermissionsMode = autoRevokePermissionsMode;
this.traceMethod = traceMethod;
this.traceCookie = traceCookie;
this.signingDetails = signingDetails;
@@ -15002,6 +15019,7 @@
params.installSource, params.volumeUuid,
params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions,
+ params.autoRevokePermissionsMode,
params.traceMethod, params.traceCookie, params.signingDetails,
params.installReason, params.forceQueryableOverride,
params.mParentInstallParams, params.mDataLoaderType);
@@ -15093,7 +15111,7 @@
/** Existing install */
FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
super(OriginInfo.fromNothing(), null, null, 0, InstallSource.EMPTY,
- null, null, instructionSets, null, null, null, null, 0,
+ null, null, instructionSets, null, null, null, MODE_DEFAULT, null, 0,
PackageParser.SigningDetails.UNKNOWN,
PackageManager.INSTALL_REASON_UNKNOWN, false, null /* parent */,
DataLoaderType.NONE);
@@ -22469,7 +22487,8 @@
final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
installSource, volumeUuid, null /*verificationInfo*/, user,
packageAbiOverride, null /*grantedPermissions*/,
- null /*whitelistedRestrictedPermissions*/, PackageParser.SigningDetails.UNKNOWN,
+ null /*whitelistedRestrictedPermissions*/, MODE_DEFAULT /* autoRevokePermissions */,
+ PackageParser.SigningDetails.UNKNOWN,
PackageManager.INSTALL_REASON_UNKNOWN, PackageManager.VERSION_CODE_HIGHEST,
DataLoaderType.NONE);
params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
@@ -24173,6 +24192,12 @@
}
mAppsFilter.getFeatureConfig().enableLogging(pkg.appId, enable);
}
+
+ @Override
+ public boolean isSystemPackage(@NonNull String packageName) {
+ return packageName.equals(
+ PackageManagerService.this.ensureSystemPackageName(packageName));
+ }
}
@GuardedBy("mLock")
@@ -24361,6 +24386,24 @@
}
@Override
+ public boolean isAutoRevokeWhitelisted(String packageName) {
+ int mode = mInjector.getAppOpsManager().checkOpNoThrow(
+ AppOpsManager.OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
+ Binder.getCallingUid(), packageName);
+ if (mode == MODE_ALLOWED) {
+ return false;
+ } else if (mode == MODE_IGNORED) {
+ return true;
+ } else {
+ synchronized (mLock) {
+ boolean manifestWhitelisted =
+ mPackages.get(packageName).isAllowDontAutoRevokePermmissions();
+ return manifestWhitelisted;
+ }
+ }
+ }
+
+ @Override
public int getInstallReason(String packageName, int userId) {
final int callingUid = Binder.getCallingUid();
mPermissionManager.enforceCrossUserPermission(callingUid, userId,
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index be17dd8..8a9f1b3 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -3017,9 +3017,11 @@
private int doAddFiles(int sessionId, ArrayList<String> args, long sessionSizeBytes,
boolean isApex) throws RemoteException {
- PackageInstaller.Session session = new PackageInstaller.Session(
- mInterface.getPackageInstaller().openSession(sessionId));
+ PackageInstaller.Session session = null;
try {
+ session = new PackageInstaller.Session(
+ mInterface.getPackageInstaller().openSession(sessionId));
+
// 1. Single file from stdin.
if (args.isEmpty() || STDIN_PATH.equals(args.get(0))) {
final String name = "base." + (isApex ? "apex" : "apk");
@@ -3043,6 +3045,10 @@
}
}
return 0;
+ } catch (IllegalArgumentException e) {
+ getErrPrintWriter().println("Failed to add file(s), reason: " + e);
+ getOutPrintWriter().println("Failure [failed to add file(s)]");
+ return 1;
} finally {
IoUtils.closeQuietly(session);
}
diff --git a/services/core/java/com/android/server/pm/PackageSetting.java b/services/core/java/com/android/server/pm/PackageSetting.java
index 2bd1a26..a83a847 100644
--- a/services/core/java/com/android/server/pm/PackageSetting.java
+++ b/services/core/java/com/android/server/pm/PackageSetting.java
@@ -321,6 +321,8 @@
Set<String> mimeGroupNames = other.mimeGroups != null ? other.mimeGroups.keySet() : null;
updateMimeGroups(mimeGroupNames);
+
+ getPkgState().updateFrom(other.getPkgState());
}
@NonNull
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 2d16854..62541ab 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -5450,7 +5450,7 @@
packagePermissions, sharedUserPermissions);
}
- mPersistence.writeAsUser(runtimePermissions, UserHandle.of(userId));
+ mPersistence.writeForUser(runtimePermissions, UserHandle.of(userId));
}
@NonNull
@@ -5504,12 +5504,12 @@
}
public void deleteUserRuntimePermissionsFile(int userId) {
- mPersistence.deleteAsUser(UserHandle.of(userId));
+ mPersistence.deleteForUser(UserHandle.of(userId));
}
@GuardedBy("Settings.this.mLock")
public void readStateForUserSyncLPr(int userId) {
- RuntimePermissionsState runtimePermissions = mPersistence.readAsUser(UserHandle.of(
+ RuntimePermissionsState runtimePermissions = mPersistence.readForUser(UserHandle.of(
userId));
if (runtimePermissions == null) {
readLegacyStateForUserSyncLPr(userId);
diff --git a/services/core/java/com/android/server/pm/StagingManager.java b/services/core/java/com/android/server/pm/StagingManager.java
index 7dd2e55..342c907 100644
--- a/services/core/java/com/android/server/pm/StagingManager.java
+++ b/services/core/java/com/android/server/pm/StagingManager.java
@@ -128,11 +128,12 @@
}
}
- ParceledListSlice<PackageInstaller.SessionInfo> getSessions() {
+ ParceledListSlice<PackageInstaller.SessionInfo> getSessions(int callingUid) {
final List<PackageInstaller.SessionInfo> result = new ArrayList<>();
synchronized (mStagedSessions) {
for (int i = 0; i < mStagedSessions.size(); i++) {
- result.add(mStagedSessions.valueAt(i).generateInfo(false));
+ final PackageInstallerSession stagedSession = mStagedSessions.valueAt(i);
+ result.add(stagedSession.generateInfoForCaller(false /*icon*/, callingUid));
}
}
return new ParceledListSlice<>(result);
@@ -331,7 +332,8 @@
}
// Reverts apex sessions and user data (if checkpoint is supported). Also reboots the device.
- private void abortCheckpoint() {
+ private void abortCheckpoint(String errorMsg) {
+ Slog.e(TAG, "Aborting checkpoint: " + errorMsg);
try {
if (supportsCheckpoint() && needsCheckpoint()) {
mApexManager.revertActiveSessions();
@@ -504,6 +506,8 @@
// mode. If not, we fail all sessions.
if (supportsCheckpoint() && !needsCheckpoint()) {
// TODO(b/146343545): Persist failure reason across checkpoint reboot
+ Slog.d(TAG, "Reverting back to safe state. Marking " + session.sessionId
+ + " as failed.");
session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_UNKNOWN,
"Reverting back to safe state");
return;
@@ -524,26 +528,29 @@
if (hasApex) {
if (apexSessionInfo == null) {
+ String errorMsg = "apexd did not know anything about a staged session supposed to"
+ + " be activated";
session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
- "apexd did not know anything about a staged session supposed to be"
- + "activated");
- abortCheckpoint();
+ errorMsg);
+ abortCheckpoint(errorMsg);
return;
}
if (isApexSessionFailed(apexSessionInfo)) {
+ String errorMsg = "APEX activation failed. Check logcat messages from apexd for "
+ + "more information.";
session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
- "APEX activation failed. Check logcat messages from apexd for "
- + "more information.");
- abortCheckpoint();
+ errorMsg);
+ abortCheckpoint(errorMsg);
return;
}
if (!apexSessionInfo.isActivated && !apexSessionInfo.isSuccess) {
// Apexd did not apply the session for some unknown reason. There is no guarantee
// that apexd will install it next time. Safer to proactively mark as failed.
+ String errorMsg = "Staged session " + session.sessionId + "at boot didn't "
+ + "activate nor fail. Marking it as failed anyway.";
session.setStagedSessionFailed(SessionInfo.STAGED_SESSION_ACTIVATION_FAILED,
- "Staged session " + session.sessionId + "at boot didn't "
- + "activate nor fail. Marking it as failed anyway.");
- abortCheckpoint();
+ errorMsg);
+ abortCheckpoint(errorMsg);
return;
}
snapshotAndRestoreForApexSession(session);
@@ -556,7 +563,7 @@
installApksInSession(session);
} catch (PackageManagerException e) {
session.setStagedSessionFailed(e.error, e.getMessage());
- abortCheckpoint();
+ abortCheckpoint(e.getMessage());
// If checkpoint is not supported, we have to handle failure for one staged session.
if (!hasApex) {
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index df3c83a..1c2fcc1 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -1300,14 +1300,15 @@
@Override
public boolean hasBadge(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "hasBadge");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "hasBadge");
final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
return userTypeDetails != null && userTypeDetails.hasBadge();
}
@Override
public @StringRes int getUserBadgeLabelResId(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeLabelResId");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
+ "getUserBadgeLabelResId");
final UserInfo userInfo = getUserInfoNoChecks(userId);
final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
@@ -1320,7 +1321,8 @@
@Override
public @ColorRes int getUserBadgeColorResId(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeColorResId");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
+ "getUserBadgeColorResId");
final UserInfo userInfo = getUserInfoNoChecks(userId);
final UserTypeDetails userTypeDetails = getUserTypeDetails(userInfo);
if (userInfo == null || userTypeDetails == null || !userTypeDetails.hasBadge()) {
@@ -1333,7 +1335,7 @@
@Override
public @DrawableRes int getUserIconBadgeResId(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserIconBadgeResId");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserIconBadgeResId");
final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
Slog.e(LOG_TAG, "Requested icon badge for non-badged user " + userId);
@@ -1344,7 +1346,7 @@
@Override
public @DrawableRes int getUserBadgeResId(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserBadgeResId");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserBadgeResId");
final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
Slog.e(LOG_TAG, "Requested badge for non-badged user " + userId);
@@ -1355,7 +1357,7 @@
@Override
public @DrawableRes int getUserBadgeNoBackgroundResId(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId,
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
"getUserBadgeNoBackgroundResId");
final UserTypeDetails userTypeDetails = getUserTypeDetailsNoChecks(userId);
if (userTypeDetails == null || !userTypeDetails.hasBadge()) {
@@ -1367,7 +1369,7 @@
@Override
public boolean isProfile(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isProfile");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isProfile");
synchronized (mUsersLock) {
UserInfo userInfo = getUserInfoLU(userId);
return userInfo != null && userInfo.isProfile();
@@ -1376,7 +1378,7 @@
@Override
public boolean isManagedProfile(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isManagedProfile");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isManagedProfile");
synchronized (mUsersLock) {
UserInfo userInfo = getUserInfoLU(userId);
return userInfo != null && userInfo.isManagedProfile();
@@ -1385,19 +1387,20 @@
@Override
public boolean isUserUnlockingOrUnlocked(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlockingOrUnlocked");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId,
+ "isUserUnlockingOrUnlocked");
return mLocalService.isUserUnlockingOrUnlocked(userId);
}
@Override
public boolean isUserUnlocked(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isUserUnlocked");
return mLocalService.isUserUnlocked(userId);
}
@Override
public boolean isUserRunning(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "isUserRunning");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isUserRunning");
return mLocalService.isUserRunning(userId);
}
@@ -1437,7 +1440,7 @@
}
}
- private void checkManageOrInteractPermIfCallerInOtherProfileGroup(@UserIdInt int userId,
+ private void checkManageOrInteractPermissionIfCallerInOtherProfileGroup(@UserIdInt int userId,
String name) {
final int callingUserId = UserHandle.getCallingUserId();
if (callingUserId == userId || isSameProfileGroupNoChecks(callingUserId, userId) ||
@@ -1466,11 +1469,7 @@
@Override
public boolean isPreCreated(@UserIdInt int userId) {
- final int callingUserId = UserHandle.getCallingUserId();
- if (callingUserId != userId && !hasManageUsersPermission()) {
- throw new SecurityException("You need MANAGE_USERS permission to query if u=" + userId
- + " is pre-created");
- }
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "isPreCreated");
synchronized (mUsersLock) {
UserInfo userInfo = getUserInfoLU(userId);
return userInfo != null && userInfo.preCreated;
@@ -1826,7 +1825,7 @@
/** @return a specific user restriction that's in effect currently. */
@Override
public boolean hasUserRestriction(String restrictionKey, @UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "hasUserRestriction");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "hasUserRestriction");
return mLocalService.hasUserRestriction(restrictionKey, userId);
}
@@ -1951,7 +1950,7 @@
*/
@Override
public Bundle getUserRestrictions(@UserIdInt int userId) {
- checkManageOrInteractPermIfCallerInOtherProfileGroup(userId, "getUserRestrictions");
+ checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserRestrictions");
return UserRestrictionsUtils.clone(getEffectiveUserRestrictions(userId));
}
diff --git a/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java b/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java
index d3f668c..0e294f70 100644
--- a/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java
+++ b/services/core/java/com/android/server/pm/parsing/PackageInfoUtils.java
@@ -391,8 +391,9 @@
ArrayMap<String, ProcessInfo> retProcs = new ArrayMap<>(numProcs);
for (String key : procs.keySet()) {
ParsedProcess proc = procs.get(key);
- retProcs.put(proc.getName(), new ProcessInfo(proc.getName(),
- new ArraySet<>(proc.getDeniedPermissions())));
+ retProcs.put(proc.getName(),
+ new ProcessInfo(proc.getName(), new ArraySet<>(proc.getDeniedPermissions()),
+ proc.getEnableGwpAsan()));
}
return retProcs;
}
diff --git a/services/core/java/com/android/server/pm/parsing/pkg/AndroidPackage.java b/services/core/java/com/android/server/pm/parsing/pkg/AndroidPackage.java
index 7929579..46b08df 100644
--- a/services/core/java/com/android/server/pm/parsing/pkg/AndroidPackage.java
+++ b/services/core/java/com/android/server/pm/parsing/pkg/AndroidPackage.java
@@ -25,7 +25,7 @@
import android.content.pm.PermissionGroupInfo;
import android.content.pm.SharedLibraryInfo;
import android.content.pm.parsing.ParsingPackageRead;
-import android.content.pm.parsing.component.ParsedFeature;
+import android.content.pm.parsing.component.ParsedAttribution;
import android.content.pm.parsing.component.ParsedIntentInfo;
import android.content.pm.parsing.component.ParsedPermissionGroup;
import android.os.Bundle;
@@ -147,7 +147,7 @@
List<ParsedPermissionGroup> getPermissionGroups();
@NonNull
- List<ParsedFeature> getFeatures();
+ List<ParsedAttribution> getAttributions();
/**
* Used to determine the default preferred handler of an {@link Intent}.
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 85da559..46f121d 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -19,6 +19,8 @@
import static android.Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+import static android.app.AppOpsManager.MODE_ALLOWED;
+import static android.app.AppOpsManager.MODE_IGNORED;
import static android.content.pm.PackageManager.FLAGS_PERMISSION_RESTRICTION_ANY_EXEMPT;
import static android.content.pm.PackageManager.FLAG_PERMISSION_APPLY_RESTRICTION;
import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
@@ -53,6 +55,7 @@
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
+import android.app.AppOpsManager;
import android.app.ApplicationPackageManager;
import android.app.IActivityManager;
import android.app.admin.DeviceAdminInfo;
@@ -217,6 +220,9 @@
/** Default permission policy to provide proper behaviour out-of-the-box */
private final DefaultPermissionGrantPolicy mDefaultPermissionGrantPolicy;
+ /** App ops manager */
+ private final AppOpsManager mAppOpsManager;
+
/**
* Built-in permissions. Read from system configuration files. Mapping is from
* UID to permission name.
@@ -356,6 +362,7 @@
mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
mUserManagerInt = LocalServices.getService(UserManagerInternal.class);
mSettings = new PermissionSettings(mLock);
+ mAppOpsManager = context.getSystemService(AppOpsManager.class);
mHandlerThread = new ServiceThread(TAG,
Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
@@ -1199,6 +1206,77 @@
}
@Override
+ public boolean setAutoRevokeWhitelisted(
+ @NonNull String packageName, boolean whitelisted, int userId) {
+ Objects.requireNonNull(packageName);
+
+ final AndroidPackage pkg = mPackageManagerInt.getPackage(packageName);
+ final int callingUid = Binder.getCallingUid();
+
+ if (!checkAutoRevokeAccess(pkg, callingUid)) {
+ return false;
+ }
+
+ if (mAppOpsManager
+ .checkOpNoThrow(AppOpsManager.OP_AUTO_REVOKE_MANAGED_BY_INSTALLER,
+ callingUid, packageName)
+ != MODE_ALLOWED) {
+ // Whitelist user set - don't override
+ return false;
+ }
+
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ mAppOpsManager.setMode(AppOpsManager.OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
+ callingUid, packageName,
+ whitelisted ? MODE_IGNORED : MODE_ALLOWED);
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ return true;
+ }
+
+ private boolean checkAutoRevokeAccess(AndroidPackage pkg, int callingUid) {
+ if (pkg == null) {
+ return false;
+ }
+
+ final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission(
+ Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS)
+ == PackageManager.PERMISSION_GRANTED;
+ final boolean isCallerInstallerOnRecord =
+ mPackageManagerInt.isCallerInstallerOfRecord(pkg, callingUid);
+
+ if (!isCallerPrivileged && !isCallerInstallerOnRecord) {
+ throw new SecurityException("Caller must either hold "
+ + Manifest.permission.WHITELIST_AUTO_REVOKE_PERMISSIONS
+ + " or be the installer on record");
+ }
+ return true;
+ }
+
+ @Override
+ public boolean isAutoRevokeWhitelisted(@NonNull String packageName, int userId) {
+ Objects.requireNonNull(packageName);
+
+ final AndroidPackage pkg = mPackageManagerInt.getPackage(packageName);
+ final int callingUid = Binder.getCallingUid();
+
+ if (!checkAutoRevokeAccess(pkg, callingUid)) {
+ return false;
+ }
+
+ final long identity = Binder.clearCallingIdentity();
+ try {
+ return mAppOpsManager.checkOpNoThrow(
+ AppOpsManager.OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, callingUid, packageName)
+ == MODE_IGNORED;
+ } finally {
+ Binder.restoreCallingIdentity(identity);
+ }
+ }
+
+ @Override
public void grantRuntimePermission(String packageName, String permName, final int userId) {
final int callingUid = Binder.getCallingUid();
final boolean overridePolicy =
@@ -3093,6 +3171,36 @@
}
}
+ @Override
+ public List<String> getAutoRevokeExemptionRequestedPackages(int userId) {
+ mContext.enforceCallingPermission(Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY,
+ "Must hold " + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY);
+
+ List<String> result = new ArrayList<>();
+ mPackageManagerInt.forEachInstalledPackage(pkg -> {
+ if (pkg.isDontAutoRevokePermmissions()) {
+ result.add(pkg.getPackageName());
+ }
+ }, userId);
+
+ return result;
+ }
+
+ @Override
+ public List<String> getAutoRevokeExemptionGrantedPackages(int userId) {
+ mContext.enforceCallingPermission(Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY,
+ "Must hold " + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY);
+
+ List<String> result = new ArrayList<>();
+ mPackageManagerInt.forEachInstalledPackage(pkg -> {
+ if (pkg.isAllowDontAutoRevokePermmissions()) {
+ result.add(pkg.getPackageName());
+ }
+ }, userId);
+
+ return result;
+ }
+
private boolean isNewPlatformPermissionForPackage(String perm, AndroidPackage pkg) {
boolean allowed = false;
final int NP = PackageParser.NEW_PERMISSIONS.length;
@@ -4347,6 +4455,12 @@
packageName, permissions, flags, userId);
}
@Override
+ public void setAutoRevokeWhitelisted(
+ @NonNull String packageName, boolean whitelisted, int userId) {
+ PermissionManagerService.this.setAutoRevokeWhitelisted(
+ packageName, whitelisted, userId);
+ }
+ @Override
public void updatePermissions(@NonNull String packageName, @Nullable AndroidPackage pkg) {
PermissionManagerService.this
.updatePermissions(packageName, pkg, mDefaultPermissionCallback);
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
index 32ef2ce..356d0ab 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInternal.java
@@ -189,7 +189,9 @@
/** Sets the whitelisted, restricted permissions for the given package. */
public abstract void setWhitelistedRestrictedPermissions(
@NonNull String packageName, @NonNull List<String> permissions,
- @PackageManager.PermissionWhitelistFlags int flags, @NonNull int userId);
+ @PackageManager.PermissionWhitelistFlags int flags, int userId);
+ public abstract void setAutoRevokeWhitelisted(
+ @NonNull String packageName, boolean whitelisted, int userId);
/**
* Update permissions when a package changed.
diff --git a/services/core/java/com/android/server/pm/pkg/PackageStateUnserialized.java b/services/core/java/com/android/server/pm/pkg/PackageStateUnserialized.java
index e27bf48..edb6d65 100644
--- a/services/core/java/com/android/server/pm/pkg/PackageStateUnserialized.java
+++ b/services/core/java/com/android/server/pm/pkg/PackageStateUnserialized.java
@@ -27,6 +27,7 @@
import com.android.internal.util.DataClass;
import com.android.server.pm.PackageSetting;
+import java.util.ArrayList;
import java.util.List;
/**
@@ -88,6 +89,22 @@
return latestUse;
}
+ public void updateFrom(PackageStateUnserialized other) {
+ this.hiddenUntilInstalled = other.hiddenUntilInstalled;
+
+ if (!other.usesLibraryInfos.isEmpty()) {
+ this.usesLibraryInfos = new ArrayList<>(other.usesLibraryInfos);
+ }
+
+ if (!other.usesLibraryFiles.isEmpty()) {
+ this.usesLibraryFiles = new ArrayList<>(other.usesLibraryFiles);
+ }
+
+ this.updatedSystemApp = other.updatedSystemApp;
+ this.lastPackageUsageTimeInMills = other.lastPackageUsageTimeInMills;
+ this.overrideSeInfo = other.overrideSeInfo;
+ }
+
// Code below generated by codegen v1.0.14.
diff --git a/services/core/java/com/android/server/policy/PermissionPolicyService.java b/services/core/java/com/android/server/policy/PermissionPolicyService.java
index d589353..161f304 100644
--- a/services/core/java/com/android/server/policy/PermissionPolicyService.java
+++ b/services/core/java/com/android/server/policy/PermissionPolicyService.java
@@ -32,6 +32,7 @@
import android.app.AppOpsManagerInternal;
import android.content.Context;
import android.content.Intent;
+import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
@@ -173,6 +174,65 @@
} catch (RemoteException doesNotHappen) {
Slog.wtf(LOG_TAG, "Cannot set up app-ops listener");
}
+
+ IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
+ intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+ intentFilter.addDataScheme("package");
+
+
+ /* TODO ntmyren: enable receiver when test flakes are fixed
+ getContext().registerReceiverAsUser(new BroadcastReceiver() {
+ final List<Integer> mUserSetupUids = new ArrayList<>(200);
+ final Map<UserHandle, PermissionControllerManager> mPermControllerManagers =
+ new HashMap<>();
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ boolean hasSetupRun = true;
+ try {
+ hasSetupRun = Settings.Secure.getInt(getContext().getContentResolver(),
+ Settings.Secure.USER_SETUP_COMPLETE) != 0;
+ } catch (Settings.SettingNotFoundException e) {
+ // Ignore error, assume setup has run
+ }
+ int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
+ // If there is no valid package for the given UID, return immediately
+ if (packageManagerInternal.getPackage(uid) == null) {
+ return;
+ }
+
+ if (hasSetupRun) {
+ if (!mUserSetupUids.isEmpty()) {
+ synchronized (mUserSetupUids) {
+ for (int i = mUserSetupUids.size() - 1; i >= 0; i--) {
+ updateUid(mUserSetupUids.get(i));
+ }
+ mUserSetupUids.clear();
+ }
+ }
+ updateUid(uid);
+ } else {
+ synchronized (mUserSetupUids) {
+ if (!mUserSetupUids.contains(uid)) {
+ mUserSetupUids.add(uid);
+ }
+ }
+ }
+ }
+
+ private void updateUid(int uid) {
+ UserHandle user = UserHandle.getUserHandleForUid(uid);
+ PermissionControllerManager manager = mPermControllerManagers.get(user);
+ if (manager == null) {
+ manager = new PermissionControllerManager(
+ getUserContext(getContext(), user), FgThread.getHandler());
+ mPermControllerManagers.put(user, manager);
+ }
+ manager.updateUserSensitiveForApp(uid);
+ }
+ }, UserHandle.ALL, intentFilter, null, null);
+ */
}
/**
@@ -182,7 +242,6 @@
* {@link AppOpsManager#sOpToSwitch share an op} to control the access.
*
* @param permission The permission
- *
* @return The op that controls the access of the permission
*/
private static int getSwitchOp(@NonNull String permission) {
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 1b5cc6a..1e12565 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -2139,8 +2139,10 @@
}
// check if user has enabled this operation. SecurityException will be thrown if this app
- // has not been allowed by the user
- final int mode = mAppOpsManager.noteOpNoThrow(outAppOp[0], callingUid, packageName);
+ // has not been allowed by the user. The reason to use "noteOp" (instead of checkOp) is to
+ // make sure the usage is logged.
+ final int mode = mAppOpsManager.noteOpNoThrow(outAppOp[0], callingUid, packageName,
+ null /* featureId */, "check-add");
switch (mode) {
case AppOpsManager.MODE_ALLOWED:
case AppOpsManager.MODE_IGNORED:
@@ -5202,7 +5204,7 @@
if (dock != null) {
int result = ActivityTaskManager.getService()
.startActivityAsUser(null, mContext.getBasePackageName(),
- mContext.getFeatureId(), dock,
+ mContext.getAttributionTag(), dock,
dock.resolveTypeIfNeeded(mContext.getContentResolver()),
null, null, 0,
ActivityManager.START_FLAG_ONLY_IF_NEEDED,
@@ -5214,7 +5216,7 @@
}
int result = ActivityTaskManager.getService()
.startActivityAsUser(null, mContext.getBasePackageName(),
- mContext.getFeatureId(), mHomeIntent,
+ mContext.getAttributionTag(), mHomeIntent,
mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
null, null, 0,
ActivityManager.START_FLAG_ONLY_IF_NEEDED,
diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java
index f04be0b..294deba 100644
--- a/services/core/java/com/android/server/power/PowerManagerService.java
+++ b/services/core/java/com/android/server/power/PowerManagerService.java
@@ -42,6 +42,8 @@
import android.hardware.display.AmbientDisplayConfiguration;
import android.hardware.display.DisplayManagerInternal;
import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
+import android.hardware.power.Boost;
+import android.hardware.power.Mode;
import android.hardware.power.V1_0.PowerHint;
import android.net.Uri;
import android.os.BatteryManager;
@@ -732,6 +734,16 @@
PowerManagerService.nativeSendPowerHint(hintId, data);
}
+ /** Wrapper for PowerManager.nativeSetPowerBoost */
+ public void nativeSetPowerBoost(int boost, int durationMs) {
+ PowerManagerService.nativeSetPowerBoost(boost, durationMs);
+ }
+
+ /** Wrapper for PowerManager.nativeSetPowerMode */
+ public void nativeSetPowerMode(int mode, boolean enabled) {
+ PowerManagerService.nativeSetPowerMode(mode, enabled);
+ }
+
/** Wrapper for PowerManager.nativeSetFeature */
public void nativeSetFeature(int featureId, int data) {
PowerManagerService.nativeSetFeature(featureId, data);
@@ -817,6 +829,8 @@
private static native void nativeSetInteractive(boolean enable);
private static native void nativeSetAutoSuspend(boolean enable);
private static native void nativeSendPowerHint(int hintId, int data);
+ private static native void nativeSetPowerBoost(int boost, int durationMs);
+ private static native void nativeSetPowerMode(int mode, boolean enabled);
private static native void nativeSetFeature(int featureId, int data);
private static native boolean nativeForceSuspend();
@@ -3608,6 +3622,16 @@
mNativeWrapper.nativeSendPowerHint(hintId, data);
}
+ private void setPowerBoostInternal(int boost, int durationMs) {
+ // Maybe filter the event.
+ mNativeWrapper.nativeSetPowerBoost(boost, durationMs);
+ }
+
+ private void setPowerModeInternal(int mode, boolean enabled) {
+ // Maybe filter the event.
+ mNativeWrapper.nativeSetPowerMode(mode, enabled);
+ }
+
@VisibleForTesting
boolean wasDeviceIdleForInternal(long ms) {
synchronized (mLock) {
@@ -4664,6 +4688,26 @@
}
@Override // Binder call
+ public void setPowerBoost(int boost, int durationMs) {
+ if (!mSystemReady) {
+ // Service not ready yet, so who the heck cares about power hints, bah.
+ return;
+ }
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
+ setPowerBoostInternal(boost, durationMs);
+ }
+
+ @Override // Binder call
+ public void setPowerMode(int mode, boolean enabled) {
+ if (!mSystemReady) {
+ // Service not ready yet, so who the heck cares about power hints, bah.
+ return;
+ }
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
+ setPowerModeInternal(mode, enabled);
+ }
+
+ @Override // Binder call
public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
WorkSource ws, String historyTag) {
if (lock == null) {
@@ -5457,6 +5501,15 @@
}
@Override
+ public void setPowerBoost(int boost, int durationMs) {
+ setPowerBoostInternal(boost, durationMs);
+ }
+
+ @Override
+ public void setPowerMode(int mode, boolean enabled) {
+ setPowerModeInternal(mode, enabled);
+ }
+ @Override
public boolean wasDeviceIdleFor(long ms) {
return wasDeviceIdleForInternal(ms);
}
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java b/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java
index beba106..8b6e9a4 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySaverController.java
@@ -16,11 +16,13 @@
package com.android.server.power.batterysaver;
import android.Manifest;
+import android.annotation.Nullable;
import android.app.ActivityManagerInternal;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
+import android.content.pm.PackageManagerInternal;
import android.hardware.power.V1_0.PowerHint;
import android.os.BatteryManager;
import android.os.BatterySaverPolicyConfig;
@@ -35,6 +37,7 @@
import android.util.ArrayMap;
import android.util.Slog;
+import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ArrayUtils;
@@ -49,6 +52,7 @@
import java.util.ArrayList;
import java.util.Objects;
+import java.util.Optional;
/**
* Responsible for battery saver mode transition logic.
@@ -112,6 +116,14 @@
*/
private final Plugin[] mPlugins;
+ /**
+ * Package name that will receive an explicit manifest broadcast for
+ * {@link PowerManager#ACTION_POWER_SAVE_MODE_CHANGED}. It's {@code null} if it hasn't been
+ * retrieved yet.
+ */
+ @Nullable
+ private Optional<String> mPowerSaveModeChangedListenerPackage;
+
public static final int REASON_PERCENTAGE_AUTOMATIC_ON = 0;
public static final int REASON_PERCENTAGE_AUTOMATIC_OFF = 1;
public static final int REASON_MANUAL_ON = 2;
@@ -494,6 +506,14 @@
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
+ // Send the broadcast to a manifest-registered receiver that is specified in the config.
+ if (getPowerSaveModeChangedListenerPackage().isPresent()) {
+ intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
+ .setPackage(getPowerSaveModeChangedListenerPackage().get())
+ .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+ mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
+ }
+
// Send internal version that requires signature permission.
intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
@@ -508,6 +528,20 @@
}
}
+ private Optional<String> getPowerSaveModeChangedListenerPackage() {
+ if (mPowerSaveModeChangedListenerPackage == null) {
+ String configPowerSaveModeChangedListenerPackage =
+ mContext.getString(R.string.config_powerSaveModeChangedListenerPackage);
+ mPowerSaveModeChangedListenerPackage =
+ LocalServices
+ .getService(PackageManagerInternal.class)
+ .isSystemPackage(configPowerSaveModeChangedListenerPackage)
+ ? Optional.of(configPowerSaveModeChangedListenerPackage)
+ : Optional.empty();
+ }
+ return mPowerSaveModeChangedListenerPackage;
+ }
+
private void updateBatterySavingStats() {
final PowerManager pm = getPowerManager();
if (pm == null) {
diff --git a/services/core/java/com/android/server/role/RoleUserState.java b/services/core/java/com/android/server/role/RoleUserState.java
index 97ce6bd..b33dc8f 100644
--- a/services/core/java/com/android/server/role/RoleUserState.java
+++ b/services/core/java/com/android/server/role/RoleUserState.java
@@ -364,12 +364,12 @@
(Map<String, Set<String>>) (Map<String, ?>) snapshotRolesLocked());
}
- mPersistence.writeAsUser(roles, UserHandle.of(mUserId));
+ mPersistence.writeForUser(roles, UserHandle.of(mUserId));
}
private void readFile() {
synchronized (mLock) {
- RolesState roles = mPersistence.readAsUser(UserHandle.of(mUserId));
+ RolesState roles = mPersistence.readForUser(UserHandle.of(mUserId));
if (roles == null) {
readLegacyFileLocked();
scheduleWriteFileLocked();
@@ -545,7 +545,7 @@
throw new IllegalStateException("This RoleUserState has already been destroyed");
}
mWriteHandler.removeCallbacksAndMessages(null);
- mPersistence.deleteAsUser(UserHandle.of(mUserId));
+ mPersistence.deleteForUser(UserHandle.of(mUserId));
mDestroyed = true;
}
}
diff --git a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
index 42fada1..b50c22e 100644
--- a/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
+++ b/services/core/java/com/android/server/rollback/RollbackManagerServiceImpl.java
@@ -63,6 +63,7 @@
import com.android.server.PackageWatchdog;
import com.android.server.SystemConfig;
import com.android.server.Watchdog;
+import com.android.server.pm.ApexManager;
import com.android.server.pm.Installer;
import java.io.File;
@@ -485,6 +486,8 @@
}
latch.countDown();
+
+ destroyCeSnapshotsForExpiredRollbacks(userId);
});
try {
@@ -495,6 +498,15 @@
}
@WorkerThread
+ private void destroyCeSnapshotsForExpiredRollbacks(int userId) {
+ int[] rollbackIds = new int[mRollbacks.size()];
+ for (int i = 0; i < rollbackIds.length; i++) {
+ rollbackIds[i] = mRollbacks.get(i).info.getRollbackId();
+ }
+ ApexManager.getInstance().destroyCeSnapshotsNotSpecified(userId, rollbackIds);
+ }
+
+ @WorkerThread
private void updateRollbackLifetimeDurationInMillis() {
mRollbackLifetimeDurationInMillis = DeviceConfig.getLong(
DeviceConfig.NAMESPACE_ROLLBACK_BOOT,
diff --git a/services/core/java/com/android/server/security/TEST_MAPPING b/services/core/java/com/android/server/security/TEST_MAPPING
new file mode 100644
index 0000000..9a5e90e
--- /dev/null
+++ b/services/core/java/com/android/server/security/TEST_MAPPING
@@ -0,0 +1,8 @@
+{
+ "presubmit": [
+ {
+ "name": "ApkVerityTest",
+ "file_patterns": ["VerityUtils\\.java"]
+ }
+ ]
+}
diff --git a/services/core/java/com/android/server/security/VerityUtils.java b/services/core/java/com/android/server/security/VerityUtils.java
index 856a40f..2b793c8 100644
--- a/services/core/java/com/android/server/security/VerityUtils.java
+++ b/services/core/java/com/android/server/security/VerityUtils.java
@@ -81,22 +81,18 @@
/** Returns whether the file has fs-verity enabled. */
public static boolean hasFsverity(@NonNull String filePath) {
- // NB: only measure but not check the actual measurement here. As long as this succeeds,
- // the file is on readable if the measurement can be verified against a trusted key, and
- // this is good enough for installed apps.
- int errno = measureFsverityNative(filePath);
- if (errno != 0) {
- if (errno != OsConstants.ENODATA) {
- Slog.e(TAG, "Failed to measure fs-verity, errno " + errno + ": " + filePath);
- }
+ int retval = statxForFsverityNative(filePath);
+ if (retval < 0) {
+ Slog.e(TAG, "Failed to check whether fs-verity is enabled, errno " + -retval + ": "
+ + filePath);
return false;
}
- return true;
+ return (retval == 1);
}
private static native int enableFsverityNative(@NonNull String filePath,
@NonNull byte[] pkcs7Signature);
- private static native int measureFsverityNative(@NonNull String filePath);
+ private static native int statxForFsverityNative(@NonNull String filePath);
/**
* Generates legacy Merkle tree and fs-verity metadata with Signing Block skipped.
diff --git a/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java b/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java
index 612989f..fd275d8 100644
--- a/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java
+++ b/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java
@@ -24,6 +24,8 @@
import static android.os.Process.getUidForPid;
import static android.os.storage.VolumeInfo.TYPE_PRIVATE;
import static android.os.storage.VolumeInfo.TYPE_PUBLIC;
+import static android.util.MathUtils.abs;
+import static android.util.MathUtils.constrain;
import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
import static com.android.server.stats.pull.IonMemoryUtil.readProcessSystemIonHeapSizesFromDebugfs;
@@ -146,12 +148,15 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
+import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -169,6 +174,9 @@
private static final String TAG = "StatsPullAtomService";
private static final boolean DEBUG = true;
+ // Random seed stable for StatsPullAtomService life cycle - can be used for stable sampling
+ private static final int RANDOM_SEED = new Random().nextInt();
+
/**
* Lowest available uid for apps.
*
@@ -182,7 +190,7 @@
* How long to wait on an individual subsystem to return its stats.
*/
private static final long EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS = 2000;
- private static final long NS_PER_SEC = 1000000000;
+ private static final long MILLIS_PER_SEC = 1000;
private static final long MILLI_AMP_HR_TO_NANO_AMP_SECS = 1_000_000L * 3600L;
private static final int MAX_BATTERY_STATS_HELPER_FREQUENCY_MS = 1000;
@@ -256,6 +264,8 @@
private StatsPullAtomCallbackImpl mStatsCallbackImpl;
+ private int mAppOpsSamplingRate = 0;
+
public StatsPullAtomService(Context context) {
super(context);
mContext = context;
@@ -396,8 +406,8 @@
case FrameworkStatsLog.BATTERY_VOLTAGE:
case FrameworkStatsLog.BATTERY_CYCLE_COUNT:
return pullHealthHal(atomTag, data);
- case FrameworkStatsLog.APP_FEATURES_OPS:
- return pullAppFeaturesOps(atomTag, data);
+ case FrameworkStatsLog.ATTRIBUTED_APP_OPS:
+ return pullAttributedAppOps(atomTag, data);
default:
throw new UnsupportedOperationException("Unknown tagId=" + atomTag);
}
@@ -552,7 +562,7 @@
registerAppsOnExternalStorageInfo();
registerFaceSettings();
registerAppOps();
- registerAppFeaturesOps();
+ registerAttributedAppOps();
registerRuntimeAppOpAccessMessage();
registerNotificationRemoteViews();
registerDangerousPermissionState();
@@ -680,7 +690,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {2, 3, 4, 5})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -772,7 +782,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {3, 4, 5, 6})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -810,7 +820,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {2, 3, 4, 5})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -848,7 +858,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {3, 4, 5, 6})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -886,7 +896,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {2, 3})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -955,7 +965,7 @@
private void registerKernelWakelock() {
int tagId = FrameworkStatsLog.KERNEL_WAKELOCK;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
/* PullAtomMetadata */ null,
BackgroundThread.getExecutor(),
@@ -986,7 +996,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {3})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1017,7 +1027,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {2, 3})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1046,7 +1056,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {4})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1078,7 +1088,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {2})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1105,7 +1115,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {3})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1130,7 +1140,7 @@
private void registerWifiActivityInfo() {
int tagId = FrameworkStatsLog.WIFI_ACTIVITY_INFO;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1182,7 +1192,7 @@
private void registerModemActivityInfo() {
int tagId = FrameworkStatsLog.MODEM_ACTIVITY_INFO;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1220,7 +1230,7 @@
private void registerBluetoothActivityInfo() {
int tagId = FrameworkStatsLog.BLUETOOTH_ACTIVITY_INFO;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
/* metadata */ null,
BackgroundThread.getExecutor(),
@@ -1249,10 +1259,10 @@
private void registerSystemElapsedRealtime() {
int tagId = FrameworkStatsLog.SYSTEM_ELAPSED_REALTIME;
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
- .setCoolDownNs(NS_PER_SEC)
- .setTimeoutNs(NS_PER_SEC / 2)
+ .setCoolDownMillis(MILLIS_PER_SEC)
+ .setTimeoutMillis(MILLIS_PER_SEC / 2)
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1271,7 +1281,7 @@
private void registerSystemUptime() {
int tagId = FrameworkStatsLog.SYSTEM_UPTIME;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1293,7 +1303,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {4, 5, 6, 7, 8})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1336,7 +1346,7 @@
private void registerProcessMemoryHighWaterMark() {
int tagId = FrameworkStatsLog.PROCESS_MEMORY_HIGH_WATER_MARK;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1389,7 +1399,7 @@
private void registerProcessMemorySnapshot() {
int tagId = FrameworkStatsLog.PROCESS_MEMORY_SNAPSHOT;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1449,7 +1459,7 @@
private void registerSystemIonHeapSize() {
int tagId = FrameworkStatsLog.SYSTEM_ION_HEAP_SIZE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1472,7 +1482,7 @@
return;
}
int tagId = FrameworkStatsLog.ION_HEAP_SIZE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
/* PullAtomMetadata */ null,
BackgroundThread.getExecutor(),
@@ -1492,7 +1502,7 @@
private void registerProcessSystemIonHeapSize() {
int tagId = FrameworkStatsLog.PROCESS_SYSTEM_ION_HEAP_SIZE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1518,7 +1528,7 @@
private void registerTemperature() {
int tagId = FrameworkStatsLog.TEMPERATURE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1556,7 +1566,7 @@
private void registerCoolingDevice() {
int tagId = FrameworkStatsLog.COOLING_DEVICE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1596,7 +1606,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {4, 5, 6, 8, 12})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1639,7 +1649,7 @@
private void registerBinderCallsStatsExceptions() {
int tagId = FrameworkStatsLog.BINDER_CALLS_EXCEPTIONS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1674,7 +1684,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {5, 6, 7, 8, 9})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -1716,7 +1726,7 @@
private void registerDiskStats() {
int tagId = FrameworkStatsLog.DISK_STATS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1782,7 +1792,7 @@
private void registerDirectoryUsage() {
int tagId = FrameworkStatsLog.DIRECTORY_USAGE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1823,7 +1833,7 @@
private void registerAppSize() {
int tagId = FrameworkStatsLog.APP_SIZE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1867,7 +1877,7 @@
private void registerCategorySize() {
int tagId = FrameworkStatsLog.CATEGORY_SIZE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1971,7 +1981,7 @@
private void registerNumFingerprintsEnrolled() {
int tagId = FrameworkStatsLog.NUM_FINGERPRINTS_ENROLLED;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -1981,7 +1991,7 @@
private void registerNumFacesEnrolled() {
int tagId = FrameworkStatsLog.NUM_FACES_ENROLLED;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2039,7 +2049,7 @@
private void registerProcStats() {
int tagId = FrameworkStatsLog.PROC_STATS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2049,7 +2059,7 @@
private void registerProcStatsPkgProc() {
int tagId = FrameworkStatsLog.PROC_STATS_PKG_PROC;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2120,9 +2130,9 @@
int tagId = FrameworkStatsLog.DISK_IO;
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {2, 3, 4, 5, 6, 7, 8, 9, 10, 11})
- .setCoolDownNs(3 * NS_PER_SEC)
+ .setCoolDownMillis(3 * MILLIS_PER_SEC)
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -2155,7 +2165,7 @@
private void registerPowerProfile() {
int tagId = FrameworkStatsLog.POWER_PROFILE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
/* PullAtomMetadata */ null,
BackgroundThread.getExecutor(),
@@ -2180,9 +2190,9 @@
int tagId = FrameworkStatsLog.PROCESS_CPU_TIME;
// Min cool-down is 5 sec, in line with what ActivityManagerService uses.
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
- .setCoolDownNs(5 * NS_PER_SEC)
+ .setCoolDownMillis(5 * MILLIS_PER_SEC)
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -2217,7 +2227,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {7, 9, 11, 13, 15, 17, 19, 21})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -2310,7 +2320,7 @@
private void registerDeviceCalculatedPowerUse() {
int tagId = FrameworkStatsLog.DEVICE_CALCULATED_POWER_USE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2330,7 +2340,7 @@
private void registerDeviceCalculatedPowerBlameUid() {
int tagId = FrameworkStatsLog.DEVICE_CALCULATED_POWER_BLAME_UID;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2360,7 +2370,7 @@
private void registerDeviceCalculatedPowerBlameOther() {
int tagId = FrameworkStatsLog.DEVICE_CALCULATED_POWER_BLAME_OTHER;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2396,7 +2406,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {1, 2, 3, 4})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -2447,7 +2457,7 @@
PullAtomMetadata metadata = new PullAtomMetadata.Builder()
.setAdditiveFields(new int[] {1, 2, 3, 4})
.build();
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
metadata,
BackgroundThread.getExecutor(),
@@ -2485,7 +2495,7 @@
private void registerBuildInformation() {
int tagId = FrameworkStatsLog.BUILD_INFORMATION;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2512,7 +2522,7 @@
private void registerRoleHolder() {
int tagId = FrameworkStatsLog.ROLE_HOLDER;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2570,7 +2580,7 @@
private void registerDangerousPermissionState() {
int tagId = FrameworkStatsLog.DANGEROUS_PERMISSION_STATE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2660,7 +2670,7 @@
private void registerTimeZoneDataInfo() {
int tagId = FrameworkStatsLog.TIME_ZONE_DATA_INFO;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2687,7 +2697,7 @@
private void registerExternalStorageInfo() {
int tagId = FrameworkStatsLog.EXTERNAL_STORAGE_INFO;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2737,7 +2747,7 @@
private void registerAppsOnExternalStorageInfo() {
int tagId = FrameworkStatsLog.APPS_ON_EXTERNAL_STORAGE_INFO;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2793,7 +2803,7 @@
private void registerFaceSettings() {
int tagId = FrameworkStatsLog.FACE_SETTINGS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2847,7 +2857,7 @@
private void registerAppOps() {
int tagId = FrameworkStatsLog.APP_OPS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2857,7 +2867,7 @@
private void registerRuntimeAppOpAccessMessage() {
int tagId = FrameworkStatsLog.RUNTIME_APP_OP_ACCESS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2877,6 +2887,7 @@
HistoricalOps histOps = ops.get(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS,
TimeUnit.MILLISECONDS);
+ processHistoricalOps(histOps, atomTag, pulledData);
for (int uidIdx = 0; uidIdx < histOps.getUidCount(); uidIdx++) {
final HistoricalUidOps uidOps = histOps.getUidOpsAt(uidIdx);
@@ -2890,7 +2901,7 @@
e.setAtomId(atomTag);
e.writeInt(uid);
e.writeString(packageOps.getPackageName());
- e.writeInt(op.getOpCode());
+ e.writeInt(op.getLoggingOpCode());
e.writeLong(op.getForegroundAccessCount(OP_FLAGS_PULLED));
e.writeLong(op.getBackgroundAccessCount(OP_FLAGS_PULLED));
e.writeLong(op.getForegroundRejectCount(OP_FLAGS_PULLED));
@@ -2925,9 +2936,9 @@
return StatsManager.PULL_SUCCESS;
}
- private void registerAppFeaturesOps() {
- int tagId = FrameworkStatsLog.APP_FEATURES_OPS;
- mStatsManager.registerPullAtomCallback(
+ private void registerAttributedAppOps() {
+ int tagId = FrameworkStatsLog.ATTRIBUTED_APP_OPS;
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -2935,7 +2946,7 @@
);
}
- int pullAppFeaturesOps(int atomTag, List<StatsEvent> pulledData) {
+ int pullAttributedAppOps(int atomTag, List<StatsEvent> pulledData) {
final long token = Binder.clearCallingIdentity();
try {
AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
@@ -2945,54 +2956,12 @@
new HistoricalOpsRequest.Builder(0, Long.MAX_VALUE).setFlags(
OP_FLAGS_PULLED).build();
appOps.getHistoricalOps(histOpsRequest, mContext.getMainExecutor(), ops::complete);
-
HistoricalOps histOps = ops.get(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS,
TimeUnit.MILLISECONDS);
-
- for (int uidIdx = 0; uidIdx < histOps.getUidCount(); uidIdx++) {
- final HistoricalUidOps uidOps = histOps.getUidOpsAt(uidIdx);
- final int uid = uidOps.getUid();
- for (int pkgIdx = 0; pkgIdx < uidOps.getPackageCount(); pkgIdx++) {
- final HistoricalPackageOps packageOps = uidOps.getPackageOpsAt(pkgIdx);
- for (int featureIdx = 0; featureIdx < packageOps.getFeatureCount();
- featureIdx++) {
- final AppOpsManager.HistoricalFeatureOps featureOps =
- packageOps.getFeatureOpsAt(featureIdx);
- for (int opIdx = 0; opIdx < featureOps.getOpCount(); opIdx++) {
- final AppOpsManager.HistoricalOp op = featureOps.getOpAt(opIdx);
- StatsEvent.Builder e = StatsEvent.newBuilder();
- e.setAtomId(atomTag);
- e.writeInt(uid);
- e.writeString(packageOps.getPackageName());
- e.writeString(featureOps.getFeatureId());
- e.writeString(op.getOpName());
- e.writeLong(op.getForegroundAccessCount(OP_FLAGS_PULLED));
- e.writeLong(op.getBackgroundAccessCount(OP_FLAGS_PULLED));
- e.writeLong(op.getForegroundRejectCount(OP_FLAGS_PULLED));
- e.writeLong(op.getBackgroundRejectCount(OP_FLAGS_PULLED));
- e.writeLong(op.getForegroundAccessDuration(OP_FLAGS_PULLED));
- e.writeLong(op.getBackgroundAccessDuration(OP_FLAGS_PULLED));
-
- String perm = AppOpsManager.opToPermission(op.getOpCode());
- if (perm == null) {
- e.writeBoolean(false);
- } else {
- PermissionInfo permInfo;
- try {
- permInfo = mContext.getPackageManager().getPermissionInfo(perm,
- 0);
- e.writeBoolean(
- permInfo.getProtection() == PROTECTION_DANGEROUS);
- } catch (PackageManager.NameNotFoundException exception) {
- e.writeBoolean(false);
- }
- }
- pulledData.add(e.build());
- }
-
- }
- }
+ if (mAppOpsSamplingRate == 0) {
+ mAppOpsSamplingRate = constrain((5000 * 100) / estimateAppOpsSize(), 1, 100);
}
+ processHistoricalOps(histOps, atomTag, pulledData);
} catch (Throwable t) {
// TODO: catch exceptions at a more granular level
Slog.e(TAG, "Could not read appops", t);
@@ -3003,6 +2972,108 @@
return StatsManager.PULL_SUCCESS;
}
+ private int estimateAppOpsSize() throws Exception {
+ AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
+
+ CompletableFuture<HistoricalOps> ops = new CompletableFuture<>();
+ HistoricalOpsRequest histOpsRequest =
+ new HistoricalOpsRequest.Builder(
+ Instant.now().minus(1, ChronoUnit.DAYS).toEpochMilli(),
+ Long.MAX_VALUE).setFlags(
+ OP_FLAGS_PULLED).build();
+ appOps.getHistoricalOps(histOpsRequest, mContext.getMainExecutor(), ops::complete);
+ HistoricalOps histOps = ops.get(EXTERNAL_STATS_SYNC_TIMEOUT_MILLIS,
+ TimeUnit.MILLISECONDS);
+ return processHistoricalOps(histOps, FrameworkStatsLog.ATTRIBUTED_APP_OPS, null);
+ }
+
+ int processHistoricalOps(HistoricalOps histOps, int atomTag, List<StatsEvent> pulledData) {
+ int counter = 0;
+ for (int uidIdx = 0; uidIdx < histOps.getUidCount(); uidIdx++) {
+ final HistoricalUidOps uidOps = histOps.getUidOpsAt(uidIdx);
+ final int uid = uidOps.getUid();
+ for (int pkgIdx = 0; pkgIdx < uidOps.getPackageCount(); pkgIdx++) {
+ final HistoricalPackageOps packageOps = uidOps.getPackageOpsAt(pkgIdx);
+ if (atomTag == FrameworkStatsLog.ATTRIBUTED_APP_OPS) {
+ for (int attributionIdx = 0;
+ attributionIdx < packageOps.getAttributedOpsCount(); attributionIdx++) {
+ final AppOpsManager.AttributedHistoricalOps attributedOps =
+ packageOps.getAttributedOpsAt(attributionIdx);
+ for (int opIdx = 0; opIdx < attributedOps.getOpCount(); opIdx++) {
+ final AppOpsManager.HistoricalOp op = attributedOps.getOpAt(opIdx);
+ counter += processHistoricalOp(op, atomTag, pulledData, uid,
+ packageOps.getPackageName(), attributedOps.getTag());
+ }
+ }
+ } else if (atomTag == FrameworkStatsLog.APP_OPS) {
+ for (int opIdx = 0; opIdx < packageOps.getOpCount(); opIdx++) {
+ final AppOpsManager.HistoricalOp op = packageOps.getOpAt(opIdx);
+ counter += processHistoricalOp(op, atomTag, pulledData, uid,
+ packageOps.getPackageName(), null);
+ }
+ }
+ }
+ }
+ return counter;
+ }
+
+ private int processHistoricalOp(AppOpsManager.HistoricalOp op, int atomTag,
+ @Nullable List<StatsEvent> pulledData, int uid, String packageName,
+ @Nullable String attributionTag) {
+ if (atomTag == FrameworkStatsLog.ATTRIBUTED_APP_OPS) {
+ if (pulledData == null) { // this is size estimation call
+ if (op.getForegroundAccessCount(OP_FLAGS_PULLED) + op.getBackgroundAccessCount(
+ OP_FLAGS_PULLED) == 0) {
+ return 0;
+ } else {
+ return 32 + packageName.length() + (attributionTag == null ? 1
+ : attributionTag.length());
+ }
+ } else {
+ if (abs((op.getOpCode() + attributionTag + packageName).hashCode() + RANDOM_SEED)
+ % 100 >= mAppOpsSamplingRate) {
+ return 0;
+ }
+ }
+ }
+
+ StatsEvent.Builder e = StatsEvent.newBuilder();
+ e.setAtomId(atomTag);
+ e.writeInt(uid);
+ e.writeString(packageName);
+ if (atomTag == FrameworkStatsLog.ATTRIBUTED_APP_OPS) {
+ e.writeString(attributionTag);
+ }
+ e.writeInt(op.getLoggingOpCode());
+ e.writeLong(op.getForegroundAccessCount(OP_FLAGS_PULLED));
+ e.writeLong(op.getBackgroundAccessCount(OP_FLAGS_PULLED));
+ e.writeLong(op.getForegroundRejectCount(OP_FLAGS_PULLED));
+ e.writeLong(op.getBackgroundRejectCount(OP_FLAGS_PULLED));
+ e.writeLong(op.getForegroundAccessDuration(OP_FLAGS_PULLED));
+ e.writeLong(op.getBackgroundAccessDuration(OP_FLAGS_PULLED));
+
+ String perm = AppOpsManager.opToPermission(op.getOpCode());
+ if (perm == null) {
+ e.writeBoolean(false);
+ } else {
+ PermissionInfo permInfo;
+ try {
+ permInfo = mContext.getPackageManager().getPermissionInfo(
+ perm,
+ 0);
+ e.writeBoolean(
+ permInfo.getProtection() == PROTECTION_DANGEROUS);
+ } catch (PackageManager.NameNotFoundException exception) {
+ e.writeBoolean(false);
+ }
+ }
+ if (atomTag == FrameworkStatsLog.ATTRIBUTED_APP_OPS) {
+ e.writeInt(mAppOpsSamplingRate);
+ }
+ pulledData.add(e.build());
+ return 0;
+ }
+
int pullRuntimeAppOpAccessMessage(int atomTag, List<StatsEvent> pulledData) {
final long token = Binder.clearCallingIdentity();
try {
@@ -3019,10 +3090,10 @@
e.writeInt(message.getUid());
e.writeString(message.getPackageName());
e.writeString(message.getOp());
- if (message.getFeatureId() == null) {
+ if (message.getAttributionTag() == null) {
e.writeString("");
} else {
- e.writeString(message.getFeatureId());
+ e.writeString(message.getAttributionTag());
}
e.writeString(message.getMessage());
e.writeInt(message.getSamplingStrategy());
@@ -3080,7 +3151,7 @@
private void registerNotificationRemoteViews() {
int tagId = FrameworkStatsLog.NOTIFICATION_REMOTE_VIEWS;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -3124,7 +3195,7 @@
private void registerDangerousPermissionStateSampled() {
int tagId = FrameworkStatsLog.DANGEROUS_PERMISSION_STATE_SAMPLED;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -3134,7 +3205,7 @@
private void registerBatteryLevel() {
int tagId = FrameworkStatsLog.BATTERY_LEVEL;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -3144,7 +3215,7 @@
private void registerRemainingBatteryCapacity() {
int tagId = FrameworkStatsLog.REMAINING_BATTERY_CAPACITY;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -3154,7 +3225,7 @@
private void registerFullBatteryCapacity() {
int tagId = FrameworkStatsLog.FULL_BATTERY_CAPACITY;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -3164,7 +3235,7 @@
private void registerBatteryVoltage() {
int tagId = FrameworkStatsLog.BATTERY_VOLTAGE;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
@@ -3174,7 +3245,7 @@
private void registerBatteryCycleCount() {
int tagId = FrameworkStatsLog.BATTERY_CYCLE_COUNT;
- mStatsManager.registerPullAtomCallback(
+ mStatsManager.setPullAtomCallback(
tagId,
null, // use default PullAtomMetadata values
BackgroundThread.getExecutor(),
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index feb3e06..78ef68c 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -60,6 +60,7 @@
import com.android.internal.util.DumpUtils;
import com.android.internal.view.AppearanceRegion;
import com.android.server.LocalServices;
+import com.android.server.UiThread;
import com.android.server.notification.NotificationDelegate;
import com.android.server.policy.GlobalActionsProvider;
import com.android.server.power.ShutdownThread;
@@ -663,12 +664,13 @@
@Override
public void showAuthenticationDialog(Bundle bundle, IBiometricServiceReceiverInternal receiver,
- int biometricModality, boolean requireConfirmation, int userId, String opPackageName) {
+ int biometricModality, boolean requireConfirmation, int userId, String opPackageName,
+ long operationId) {
enforceBiometricDialog();
if (mBar != null) {
try {
mBar.showAuthenticationDialog(bundle, receiver, biometricModality,
- requireConfirmation, userId, opPackageName);
+ requireConfirmation, userId, opPackageName, operationId);
} catch (RemoteException ex) {
}
}
@@ -1118,7 +1120,7 @@
}
private void notifyBarAttachChanged() {
- mHandler.post(() -> {
+ UiThread.getHandler().post(() -> {
if (mGlobalActionListener == null) return;
mGlobalActionListener.onGlobalActionsAvailableChanged(mBar != null);
});
diff --git a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
index 8164526..74a6383 100644
--- a/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
+++ b/services/core/java/com/android/server/textclassifier/TextClassificationManagerService.java
@@ -41,6 +41,7 @@
import android.util.SparseArray;
import android.view.textclassifier.ConversationActions;
import android.view.textclassifier.SelectionEvent;
+import android.view.textclassifier.SystemTextClassifierMetadata;
import android.view.textclassifier.TextClassification;
import android.view.textclassifier.TextClassificationConstants;
import android.view.textclassifier.TextClassificationContext;
@@ -179,12 +180,12 @@
TextSelection.Request request, ITextClassifierCallback callback)
throws RemoteException {
Objects.requireNonNull(request);
+ Objects.requireNonNull(request.getSystemTextClassifierMetadata());
handleRequest(
- request.getUserId(),
- request.getCallingPackageName(),
+ request.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ true,
/* attemptToBind= */ true,
- request.getUseDefaultTextClassifier(),
service -> service.onSuggestSelection(sessionId, request, callback),
"onSuggestSelection",
callback);
@@ -196,12 +197,12 @@
TextClassification.Request request, ITextClassifierCallback callback)
throws RemoteException {
Objects.requireNonNull(request);
+ Objects.requireNonNull(request.getSystemTextClassifierMetadata());
handleRequest(
- request.getUserId(),
- request.getCallingPackageName(),
+ request.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ true,
/* attemptToBind= */ true,
- request.getUseDefaultTextClassifier(),
service -> service.onClassifyText(sessionId, request, callback),
"onClassifyText",
callback);
@@ -213,12 +214,12 @@
TextLinks.Request request, ITextClassifierCallback callback)
throws RemoteException {
Objects.requireNonNull(request);
+ Objects.requireNonNull(request.getSystemTextClassifierMetadata());
handleRequest(
- request.getUserId(),
- request.getCallingPackageName(),
+ request.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ true,
/* attemptToBind= */ true,
- request.getUseDefaultTextClassifier(),
service -> service.onGenerateLinks(sessionId, request, callback),
"onGenerateLinks",
callback);
@@ -229,12 +230,12 @@
@Nullable TextClassificationSessionId sessionId, SelectionEvent event)
throws RemoteException {
Objects.requireNonNull(event);
+ Objects.requireNonNull(event.getSystemTextClassifierMetadata());
handleRequest(
- event.getUserId(),
- /* callingPackageName= */ null,
+ event.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ false,
/* attemptToBind= */ false,
- event.getUseDefaultTextClassifier(),
service -> service.onSelectionEvent(sessionId, event),
"onSelectionEvent",
NO_OP_CALLBACK);
@@ -246,18 +247,14 @@
TextClassifierEvent event) throws RemoteException {
Objects.requireNonNull(event);
- final int userId = event.getEventContext() == null
- ? UserHandle.getCallingUserId()
- : event.getEventContext().getUserId();
- final boolean useDefaultTextClassifier =
- event.getEventContext() != null
- ? event.getEventContext().getUseDefaultTextClassifier()
- : true;
+ final TextClassificationContext eventContext = event.getEventContext();
+ final SystemTextClassifierMetadata systemTcMetadata =
+ eventContext != null ? eventContext.getSystemTextClassifierMetadata() : null;
+
handleRequest(
- userId,
- /* callingPackageName= */ null,
+ systemTcMetadata,
+ /* verifyCallingPackage= */ false,
/* attemptToBind= */ false,
- useDefaultTextClassifier,
service -> service.onTextClassifierEvent(sessionId, event),
"onTextClassifierEvent",
NO_OP_CALLBACK);
@@ -269,12 +266,12 @@
TextLanguage.Request request,
ITextClassifierCallback callback) throws RemoteException {
Objects.requireNonNull(request);
+ Objects.requireNonNull(request.getSystemTextClassifierMetadata());
handleRequest(
- request.getUserId(),
- request.getCallingPackageName(),
+ request.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ true,
/* attemptToBind= */ true,
- request.getUseDefaultTextClassifier(),
service -> service.onDetectLanguage(sessionId, request, callback),
"onDetectLanguage",
callback);
@@ -286,12 +283,12 @@
ConversationActions.Request request,
ITextClassifierCallback callback) throws RemoteException {
Objects.requireNonNull(request);
+ Objects.requireNonNull(request.getSystemTextClassifierMetadata());
handleRequest(
- request.getUserId(),
- request.getCallingPackageName(),
+ request.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ true,
/* attemptToBind= */ true,
- request.getUseDefaultTextClassifier(),
service -> service.onSuggestConversationActions(sessionId, request, callback),
"onSuggestConversationActions",
callback);
@@ -303,13 +300,12 @@
throws RemoteException {
Objects.requireNonNull(sessionId);
Objects.requireNonNull(classificationContext);
+ Objects.requireNonNull(classificationContext.getSystemTextClassifierMetadata());
- final int userId = classificationContext.getUserId();
handleRequest(
- userId,
- classificationContext.getPackageName(),
+ classificationContext.getSystemTextClassifierMetadata(),
+ /* verifyCallingPackage= */ true,
/* attemptToBind= */ false,
- classificationContext.getUseDefaultTextClassifier(),
service -> {
service.onCreateTextClassificationSession(classificationContext, sessionId);
mSessionCache.put(sessionId, classificationContext);
@@ -333,11 +329,13 @@
textClassificationContext != null
? textClassificationContext.useDefaultTextClassifier
: true;
+ final SystemTextClassifierMetadata sysTcMetadata = new SystemTextClassifierMetadata(
+ "", userId, useDefaultTextClassifier);
+
handleRequest(
- userId,
- /* callingPackageName= */ null,
+ sysTcMetadata,
+ /* verifyCallingPackage= */ false,
/* attemptToBind= */ false,
- useDefaultTextClassifier,
service -> {
service.onDestroyTextClassificationSession(sessionId);
mSessionCache.remove(sessionId);
@@ -412,10 +410,9 @@
}
private void handleRequest(
- @UserIdInt int userId,
- @Nullable String callingPackageName,
+ @Nullable SystemTextClassifierMetadata sysTcMetadata,
+ boolean verifyCallingPackage,
boolean attemptToBind,
- boolean useDefaultTextClassifier,
@NonNull ThrowingConsumer<ITextClassifierService> textClassifierServiceConsumer,
@NonNull String methodName,
@NonNull ITextClassifierCallback callback) throws RemoteException {
@@ -423,8 +420,17 @@
Objects.requireNonNull(methodName);
Objects.requireNonNull(callback);
+ final int userId =
+ sysTcMetadata == null ? UserHandle.getCallingUserId() : sysTcMetadata.getUserId();
+ final String callingPackageName =
+ sysTcMetadata == null ? null : sysTcMetadata.getCallingPackageName();
+ final boolean useDefaultTextClassifier =
+ sysTcMetadata == null ? true : sysTcMetadata.useDefaultTextClassifier();
+
try {
- validateCallingPackage(callingPackageName);
+ if (verifyCallingPackage) {
+ validateCallingPackage(callingPackageName);
+ }
validateUser(userId);
} catch (Exception e) {
throw new RemoteException("Invalid request: " + e.getMessage(), e,
@@ -636,8 +642,10 @@
public final boolean useDefaultTextClassifier;
StrippedTextClassificationContext(TextClassificationContext textClassificationContext) {
- userId = textClassificationContext.getUserId();
- useDefaultTextClassifier = textClassificationContext.getUseDefaultTextClassifier();
+ SystemTextClassifierMetadata sysTcMetadata =
+ textClassificationContext.getSystemTextClassifierMetadata();
+ userId = sysTcMetadata.getUserId();
+ useDefaultTextClassifier = sysTcMetadata.useDefaultTextClassifier();
}
}
diff --git a/services/core/java/com/android/server/tv/UinputBridge.java b/services/core/java/com/android/server/tv/UinputBridge.java
index 752aa66..a2fe5fc 100644
--- a/services/core/java/com/android/server/tv/UinputBridge.java
+++ b/services/core/java/com/android/server/tv/UinputBridge.java
@@ -28,7 +28,7 @@
public final class UinputBridge {
private final CloseGuard mCloseGuard = CloseGuard.get();
private long mPtr;
- private IBinder mToken = null;
+ private IBinder mToken;
private static native long nativeOpen(String name, String uniqueId, int width, int height,
int maxPointers);
@@ -39,6 +39,25 @@
private static native void nativeSendPointerUp(long ptr, int pointerId);
private static native void nativeSendPointerSync(long ptr);
+ /** Opens a gamepad - will support gamepad key and axis sending */
+ private static native long nativeGamepadOpen(String name, String uniqueId);
+
+ /** Marks the specified key up/down for a gamepad */
+ private static native void nativeSendGamepadKey(long ptr, int keyIndex, boolean down);
+
+ /**
+ * Gamepads pre-define the following axes:
+ * - Left joystick X, axis == ABS_X == 0, range [0, 254]
+ * - Left joystick Y, axis == ABS_Y == 1, range [0, 254]
+ * - Right joystick X, axis == ABS_RX == 3, range [0, 254]
+ * - Right joystick Y, axis == ABS_RY == 4, range [0, 254]
+ * - Left trigger, axis == ABS_Z == 2, range [0, 254]
+ * - Right trigger, axis == ABS_RZ == 5, range [0, 254]
+ * - DPad X, axis == ABS_HAT0X == 0x10, range [-1, 1]
+ * - DPad Y, axis == ABS_HAT0Y == 0x11, range [-1, 1]
+ */
+ private static native void nativeSendGamepadAxisValue(long ptr, int axis, int value);
+
public UinputBridge(IBinder token, String name, int width, int height, int maxPointers)
throws IOException {
if (width < 1 || height < 1) {
@@ -58,12 +77,31 @@
mCloseGuard.open("close");
}
+ /** Constructor used by static factory methods */
+ private UinputBridge(IBinder token, long ptr) {
+ mPtr = ptr;
+ mToken = token;
+ mCloseGuard.open("close");
+ }
+
+ /** Opens a UinputBridge that supports gamepad buttons and axes. */
+ public static UinputBridge openGamepad(IBinder token, String name)
+ throws IOException {
+ if (token == null) {
+ throw new IllegalArgumentException("Token cannot be null");
+ }
+ long ptr = nativeGamepadOpen(name, token.toString());
+ if (ptr == 0) {
+ throw new IOException("Could not open uinput device " + name);
+ }
+
+ return new UinputBridge(token, ptr);
+ }
+
@Override
protected void finalize() throws Throwable {
try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
+ mCloseGuard.warnIfOpen();
close(mToken);
} finally {
mToken = null;
@@ -119,7 +157,35 @@
if (isTokenValid(token)) {
nativeSendPointerSync(mPtr);
}
+ }
+ /** Send a gamepad key
+ * @param keyIndex - the index of the w3-spec key
+ * @param down - is the key pressed ?
+ */
+ public void sendGamepadKey(IBinder token, int keyIndex, boolean down) {
+ if (isTokenValid(token)) {
+ nativeSendGamepadKey(mPtr, keyIndex, down);
+ }
+ }
+
+ /** Send a gamepad axis value.
+ * - Left joystick X, axis == ABS_X == 0, range [0, 254]
+ * - Left joystick Y, axis == ABS_Y == 1, range [0, 254]
+ * - Right joystick X, axis == ABS_RX == 3, range [0, 254]
+ * - Right joystick Y, axis == ABS_RY == 4, range [0, 254]
+ * - Left trigger, axis == ABS_Z == 2, range [0, 254]
+ * - Right trigger, axis == ABS_RZ == 5, range [0, 254]
+ * - DPad X, axis == ABS_HAT0X == 0x10, range [-1, 1]
+ * - DPad Y, axis == ABS_HAT0Y == 0x11, range [-1, 1]
+ *
+ * @param axis is the axis index
+ * @param value is the value to set for that axis
+ */
+ public void sendGamepadAxisValue(IBinder token, int axis, int value) {
+ if (isTokenValid(token)) {
+ nativeSendGamepadAxisValue(mPtr, axis, value);
+ }
}
public void clear(IBinder token) {
diff --git a/services/core/java/com/android/server/tv/tunerresourcemanager/ClientProfile.java b/services/core/java/com/android/server/tv/tunerresourcemanager/ClientProfile.java
index 4eff954f..e100ff8 100644
--- a/services/core/java/com/android/server/tv/tunerresourcemanager/ClientProfile.java
+++ b/services/core/java/com/android/server/tv/tunerresourcemanager/ClientProfile.java
@@ -15,8 +15,8 @@
*/
package com.android.server.tv.tunerresourcemanager;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
/**
* A client profile object used by the Tuner Resource Manager to record the registered clients'
@@ -65,7 +65,7 @@
/**
* List of the frontend ids that are used by the current client.
*/
- private List<Integer> mUsingFrontendIds = new ArrayList<>();
+ private Set<Integer> mUsingFrontendIds = new HashSet<>();
/**
* Optional arbitrary priority value given by the client.
@@ -131,7 +131,7 @@
mUsingFrontendIds.add(frontendId);
}
- public List<Integer> getInUseFrontendIds() {
+ public Iterable<Integer> getInUseFrontendIds() {
return mUsingFrontendIds;
}
diff --git a/services/core/java/com/android/server/tv/tunerresourcemanager/FrontendResource.java b/services/core/java/com/android/server/tv/tunerresourcemanager/FrontendResource.java
index a109265..56f6159 100644
--- a/services/core/java/com/android/server/tv/tunerresourcemanager/FrontendResource.java
+++ b/services/core/java/com/android/server/tv/tunerresourcemanager/FrontendResource.java
@@ -15,12 +15,11 @@
*/
package com.android.server.tv.tunerresourcemanager;
-import android.annotation.Nullable;
import android.media.tv.tuner.frontend.FrontendSettings.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
/**
* A frontend resource object used by the Tuner Resource Manager to record the tuner frontend
@@ -50,7 +49,7 @@
/**
* An array to save all the FE ids under the same exclisive group.
*/
- private List<Integer> mExclusiveGroupMemberFeIds = new ArrayList<>();
+ private Set<Integer> mExclusiveGroupMemberFeIds = new HashSet<>();
/**
* If the current resource is in use. Once resources under the same exclusive group id is in use
@@ -82,12 +81,12 @@
return mExclusiveGroupId;
}
- public List<Integer> getExclusiveGroupMemberFeIds() {
+ public Set<Integer> getExclusiveGroupMemberFeIds() {
return mExclusiveGroupMemberFeIds;
}
/**
- * Add one id into the exclusive group member id list.
+ * Add one id into the exclusive group member id collection.
*
* @param id the id to be added.
*/
@@ -96,21 +95,21 @@
}
/**
- * Add one id list to the exclusive group member id list.
+ * Add one id collection to the exclusive group member id collection.
*
- * @param ids the id list to be added.
+ * @param ids the id collection to be added.
*/
- public void addExclusiveGroupMemberFeId(List<Integer> ids) {
+ public void addExclusiveGroupMemberFeIds(Collection<Integer> ids) {
mExclusiveGroupMemberFeIds.addAll(ids);
}
/**
- * Remove one id from the exclusive group member id list.
+ * Remove one id from the exclusive group member id collection.
*
* @param id the id to be removed.
*/
public void removeExclusiveGroupMemberFeId(int id) {
- mExclusiveGroupMemberFeIds.remove(new Integer(id));
+ mExclusiveGroupMemberFeIds.remove(id);
}
public boolean isInUse() {
@@ -143,22 +142,10 @@
public String toString() {
return "FrontendResource[id=" + this.mId + ", type=" + this.mType
+ ", exclusiveGId=" + this.mExclusiveGroupId + ", exclusiveGMemeberIds="
- + Arrays.toString(this.mExclusiveGroupMemberFeIds.toArray())
+ + this.mExclusiveGroupMemberFeIds
+ ", isInUse=" + this.mIsInUse + ", ownerClientId=" + this.mOwnerClientId + "]";
}
- @Override
- public boolean equals(@Nullable Object o) {
- if (o instanceof FrontendResource) {
- FrontendResource fe = (FrontendResource) o;
- return mId == fe.getId() && mType == fe.getType()
- && mExclusiveGroupId == fe.getExclusiveGroupId()
- && mExclusiveGroupMemberFeIds.equals(fe.getExclusiveGroupMemberFeIds())
- && mIsInUse == fe.isInUse() && mOwnerClientId == fe.getOwnerClientId();
- }
- return false;
- }
-
/**
* Builder class for {@link FrontendResource}.
*/
diff --git a/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java b/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java
index cb31a50..bd63b2d 100644
--- a/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java
+++ b/services/core/java/com/android/server/tv/tunerresourcemanager/TunerResourceManagerService.java
@@ -16,6 +16,7 @@
package com.android.server.tv.tunerresourcemanager;
+import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
@@ -24,21 +25,28 @@
import android.media.tv.tunerresourcemanager.IResourcesReclaimListener;
import android.media.tv.tunerresourcemanager.ITunerResourceManager;
import android.media.tv.tunerresourcemanager.ResourceClientProfile;
+import android.media.tv.tunerresourcemanager.TunerDemuxRequest;
+import android.media.tv.tunerresourcemanager.TunerDescramblerRequest;
import android.media.tv.tunerresourcemanager.TunerFrontendInfo;
import android.media.tv.tunerresourcemanager.TunerFrontendRequest;
import android.media.tv.tunerresourcemanager.TunerLnbRequest;
import android.media.tv.tunerresourcemanager.TunerResourceManager;
import android.os.Binder;
+import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.util.Slog;
-import android.util.SparseArray;
+import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.SystemService;
-import java.util.ArrayList;
-import java.util.List;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
/**
* This class provides a system service that manages the TV tuner resources.
@@ -52,25 +60,44 @@
public static final int INVALID_CLIENT_ID = -1;
private static final int MAX_CLIENT_PRIORITY = 1000;
- // Array of the registered client profiles
- @VisibleForTesting private SparseArray<ClientProfile> mClientProfiles = new SparseArray<>();
+ // Map of the registered client profiles
+ private Map<Integer, ClientProfile> mClientProfiles = new HashMap<>();
private int mNextUnusedClientId = 0;
- private List<Integer> mRegisteredClientIds = new ArrayList<Integer>();
- // Array of the current available frontend resources
- @VisibleForTesting
- private SparseArray<FrontendResource> mFrontendResources = new SparseArray<>();
- // Array of the current available frontend ids
- private List<Integer> mAvailableFrontendIds = new ArrayList<Integer>();
+ // Map of the current available frontend resources
+ private Map<Integer, FrontendResource> mFrontendResources = new HashMap<>();
- private SparseArray<IResourcesReclaimListener> mListeners = new SparseArray<>();
+ @GuardedBy("mLock")
+ private Map<Integer, ResourcesReclaimListenerRecord> mListeners = new HashMap<>();
private TvInputManager mManager;
private UseCasePriorityHints mPriorityCongfig = new UseCasePriorityHints();
+ // An internal resource request count to help generate resource handle.
+ private int mResourceRequestCount = 0;
+
// Used to synchronize the access to the service.
private final Object mLock = new Object();
+ /**
+ * Tuner resource type to help generate resource handle
+ */
+ @IntDef({
+ TUNER_RESOURCE_TYPE_FRONTEND,
+ TUNER_RESOURCE_TYPE_DEMUX,
+ TUNER_RESOURCE_TYPE_DESCRAMBLER,
+ TUNER_RESOURCE_TYPE_LNB,
+ TUNER_RESOURCE_TYPE_CAS_SESSION,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface TunerResourceType {}
+
+ public static final int TUNER_RESOURCE_TYPE_FRONTEND = 0;
+ public static final int TUNER_RESOURCE_TYPE_DEMUX = 1;
+ public static final int TUNER_RESOURCE_TYPE_DESCRAMBLER = 2;
+ public static final int TUNER_RESOURCE_TYPE_LNB = 3;
+ public static final int TUNER_RESOURCE_TYPE_CAS_SESSION = 4;
+
public TunerResourceManagerService(@Nullable Context context) {
super(context);
}
@@ -94,7 +121,7 @@
public void registerClientProfile(@NonNull ResourceClientProfile profile,
@NonNull IResourcesReclaimListener listener, @NonNull int[] clientId)
throws RemoteException {
- enforceAccessPermission();
+ enforceTrmAccessPermission("registerClientProfile");
if (profile == null) {
throw new RemoteException("ResourceClientProfile can't be null");
}
@@ -103,6 +130,10 @@
throw new RemoteException("clientId can't be null!");
}
+ if (listener == null) {
+ throw new RemoteException("IResourcesReclaimListener can't be null!");
+ }
+
if (!mPriorityCongfig.isDefinedUseCase(profile.getUseCase())) {
throw new RemoteException("Use undefined client use case:" + profile.getUseCase());
}
@@ -114,7 +145,7 @@
@Override
public void unregisterClientProfile(int clientId) throws RemoteException {
- enforceAccessPermission();
+ enforceTrmAccessPermission("unregisterClientProfile");
synchronized (mLock) {
if (!checkClientExists(clientId)) {
Slog.e(TAG, "Unregistering non exists client:" + clientId);
@@ -126,7 +157,7 @@
@Override
public boolean updateClientPriority(int clientId, int priority, int niceValue) {
- enforceAccessPermission();
+ enforceTrmAccessPermission("updateClientPriority");
synchronized (mLock) {
return updateClientPriorityInternal(clientId, priority, niceValue);
}
@@ -134,7 +165,7 @@
@Override
public void setFrontendInfoList(@NonNull TunerFrontendInfo[] infos) throws RemoteException {
- enforceAccessPermission();
+ enforceTrmAccessPermission("setFrontendInfoList");
if (infos == null) {
throw new RemoteException("TunerFrontendInfo can't be null");
}
@@ -145,6 +176,7 @@
@Override
public void updateCasInfo(int casSystemId, int maxSessionNum) {
+ enforceTrmAccessPermission("updateCasInfo");
if (DEBUG) {
Slog.d(TAG,
"updateCasInfo(casSystemId=" + casSystemId
@@ -154,6 +186,7 @@
@Override
public void setLnbInfoList(int[] lnbIds) {
+ enforceTrmAccessPermission("setLnbInfoList");
if (DEBUG) {
for (int i = 0; i < lnbIds.length; i++) {
Slog.d(TAG, "updateLnbInfo(lnbId=" + lnbIds[i] + ")");
@@ -163,14 +196,15 @@
@Override
public boolean requestFrontend(@NonNull TunerFrontendRequest request,
- @NonNull int[] frontendId) throws RemoteException {
- enforceAccessPermission();
- if (frontendId == null) {
- throw new RemoteException("frontendId can't be null");
+ @NonNull int[] frontendHandle) throws RemoteException {
+ enforceTunerAccessPermission("requestFrontend");
+ enforceTrmAccessPermission("requestFrontend");
+ if (frontendHandle == null) {
+ throw new RemoteException("frontendHandle can't be null");
}
synchronized (mLock) {
try {
- return requestFrontendInternal(request, frontendId);
+ return requestFrontendInternal(request, frontendHandle);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -179,14 +213,43 @@
@Override
public void shareFrontend(int selfClientId, int targetClientId) {
+ enforceTunerAccessPermission("shareFrontend");
+ enforceTrmAccessPermission("shareFrontend");
if (DEBUG) {
Slog.d(TAG, "shareFrontend from " + selfClientId + " with " + targetClientId);
}
}
@Override
+ public boolean requestDemux(@NonNull TunerDemuxRequest request,
+ @NonNull int[] demuxHandle) throws RemoteException {
+ enforceTunerAccessPermission("requestDemux");
+ enforceTrmAccessPermission("requestDemux");
+ if (demuxHandle == null) {
+ throw new RemoteException("demuxHandle can't be null");
+ }
+ synchronized (mLock) {
+ return requestDemuxInternal(request, demuxHandle);
+ }
+ }
+
+ @Override
+ public boolean requestDescrambler(@NonNull TunerDescramblerRequest request,
+ @NonNull int[] descrambleHandle) throws RemoteException {
+ enforceDescramblerAccessPermission("requestDescrambler");
+ enforceTrmAccessPermission("requestDescrambler");
+ if (descrambleHandle == null) {
+ throw new RemoteException("descrambleHandle can't be null");
+ }
+ synchronized (mLock) {
+ return requestDescramblerInternal(request, descrambleHandle);
+ }
+ }
+
+ @Override
public boolean requestCasSession(
- @NonNull CasSessionRequest request, @NonNull int[] sessionResourceId) {
+ @NonNull CasSessionRequest request, @NonNull int[] sessionResourceHandle) {
+ enforceTrmAccessPermission("requestCasSession");
if (DEBUG) {
Slog.d(TAG, "requestCasSession(request=" + request + ")");
}
@@ -195,7 +258,9 @@
}
@Override
- public boolean requestLnb(@NonNull TunerLnbRequest request, @NonNull int[] lnbId) {
+ public boolean requestLnb(@NonNull TunerLnbRequest request, @NonNull int[] lnbHandle) {
+ enforceTunerAccessPermission("requestLnb");
+ enforceTrmAccessPermission("requestLnb");
if (DEBUG) {
Slog.d(TAG, "requestLnb(request=" + request + ")");
}
@@ -204,13 +269,34 @@
@Override
public void releaseFrontend(int frontendId) {
+ enforceTunerAccessPermission("releaseFrontend");
+ enforceTrmAccessPermission("releaseFrontend");
if (DEBUG) {
Slog.d(TAG, "releaseFrontend(id=" + frontendId + ")");
}
}
@Override
+ public void releaseDemux(int demuxHandle) {
+ enforceTunerAccessPermission("releaseDemux");
+ enforceTrmAccessPermission("releaseDemux");
+ if (DEBUG) {
+ Slog.d(TAG, "releaseDemux(demuxHandle=" + demuxHandle + ")");
+ }
+ }
+
+ @Override
+ public void releaseDescrambler(int descramblerHandle) {
+ enforceTunerAccessPermission("releaseDescrambler");
+ enforceTrmAccessPermission("releaseDescrambler");
+ if (DEBUG) {
+ Slog.d(TAG, "releaseDescrambler(descramblerHandle=" + descramblerHandle + ")");
+ }
+ }
+
+ @Override
public void releaseCasSession(int sessionResourceId) {
+ enforceTrmAccessPermission("releaseCasSession");
if (DEBUG) {
Slog.d(TAG, "releaseCasSession(sessionResourceId=" + sessionResourceId + ")");
}
@@ -218,6 +304,8 @@
@Override
public void releaseLnb(int lnbId) {
+ enforceTunerAccessPermission("releaseLnb");
+ enforceTrmAccessPermission("releaseLnb");
if (DEBUG) {
Slog.d(TAG, "releaseLnb(lnbId=" + lnbId + ")");
}
@@ -226,6 +314,7 @@
@Override
public boolean isHigherPriority(
ResourceClientProfile challengerProfile, ResourceClientProfile holderProfile) {
+ enforceTrmAccessPermission("isHigherPriority");
if (DEBUG) {
Slog.d(TAG,
"isHigherPriority(challengerProfile=" + challengerProfile
@@ -261,9 +350,7 @@
.build();
clientProfile.setPriority(getClientPriority(profile.getUseCase(), pid));
- mClientProfiles.append(clientId[0], clientProfile);
- mListeners.append(clientId[0], listener);
- mRegisteredClientIds.add(clientId[0]);
+ addClientProfile(clientId[0], clientProfile, listener);
}
@VisibleForTesting
@@ -271,15 +358,7 @@
if (DEBUG) {
Slog.d(TAG, "unregisterClientProfile(clientId=" + clientId + ")");
}
- for (int id : getClientProfile(clientId).getInUseFrontendIds()) {
- getFrontendResource(id).removeOwner();
- for (int groupMemberId : getFrontendResource(id).getExclusiveGroupMemberFeIds()) {
- getFrontendResource(groupMemberId).removeOwner();
- }
- }
- mClientProfiles.remove(clientId);
- mListeners.remove(clientId);
- mRegisteredClientIds.remove(clientId);
+ removeClientProfile(clientId);
}
@VisibleForTesting
@@ -313,67 +392,43 @@
}
}
- // An arrayList to record the frontends pending on updating. Ids will be removed
- // from this list once its updating finished. Any frontend left in this list when all
- // the updates are done will be removed from mAvailableFrontendIds and
- // mFrontendResources.
- List<Integer> updatingFrontendIds = new ArrayList<>(mAvailableFrontendIds);
+ // A set to record the frontends pending on updating. Ids will be removed
+ // from this set once its updating finished. Any frontend left in this set when all
+ // the updates are done will be removed from mFrontendResources.
+ Set<Integer> updatingFrontendIds = new HashSet<>(getFrontendResources().keySet());
- // Update frontendResources sparse array and other mappings accordingly
+ // Update frontendResources map and other mappings accordingly
for (int i = 0; i < infos.length; i++) {
if (getFrontendResource(infos[i].getId()) != null) {
if (DEBUG) {
Slog.d(TAG, "Frontend id=" + infos[i].getId() + "exists.");
}
- updatingFrontendIds.remove(new Integer(infos[i].getId()));
+ updatingFrontendIds.remove(infos[i].getId());
} else {
// Add a new fe resource
FrontendResource newFe = new FrontendResource.Builder(infos[i].getId())
.type(infos[i].getFrontendType())
.exclusiveGroupId(infos[i].getExclusiveGroupId())
.build();
- // Update the exclusive group member list in all the existing Frontend resource
- for (Integer feId : mAvailableFrontendIds) {
- FrontendResource fe = getFrontendResource(feId.intValue());
- if (fe.getExclusiveGroupId() == newFe.getExclusiveGroupId()) {
- newFe.addExclusiveGroupMemberFeId(fe.getId());
- newFe.addExclusiveGroupMemberFeId(fe.getExclusiveGroupMemberFeIds());
- for (Integer excGroupmemberFeId : fe.getExclusiveGroupMemberFeIds()) {
- getFrontendResource(excGroupmemberFeId.intValue())
- .addExclusiveGroupMemberFeId(newFe.getId());
- }
- fe.addExclusiveGroupMemberFeId(newFe.getId());
- break;
- }
- }
- // Update resource list and available id list
- mFrontendResources.append(newFe.getId(), newFe);
- mAvailableFrontendIds.add(newFe.getId());
+ addFrontendResource(newFe);
}
}
// TODO check if the removing resource is in use or not. Handle the conflict.
- for (Integer removingId : updatingFrontendIds) {
- // update the exclusive group id memver list
- FrontendResource fe = getFrontendResource(removingId.intValue());
- fe.removeExclusiveGroupMemberFeId(new Integer(fe.getId()));
- for (Integer excGroupmemberFeId : fe.getExclusiveGroupMemberFeIds()) {
- getFrontendResource(excGroupmemberFeId.intValue())
- .removeExclusiveGroupMemberFeId(new Integer(fe.getId()));
- }
- mFrontendResources.remove(removingId.intValue());
- mAvailableFrontendIds.remove(removingId);
+ for (int removingId : updatingFrontendIds) {
+ // update the exclusive group id member list
+ removeFrontendResource(removingId);
}
}
@VisibleForTesting
- protected boolean requestFrontendInternal(TunerFrontendRequest request, int[] frontendId)
+ protected boolean requestFrontendInternal(TunerFrontendRequest request, int[] frontendHandle)
throws RemoteException {
if (DEBUG) {
Slog.d(TAG, "requestFrontend(request=" + request + ")");
}
- frontendId[0] = TunerResourceManager.INVALID_FRONTEND_ID;
+ frontendHandle[0] = TunerResourceManager.INVALID_RESOURCE_HANDLE;
if (!checkClientExists(request.getClientId())) {
Slog.e(TAG, "Request frontend from unregistered client:" + request.getClientId());
return false;
@@ -383,25 +438,24 @@
int inUseLowestPriorityFrId = -1;
// Priority max value is 1000
int currentLowestPriority = MAX_CLIENT_PRIORITY + 1;
- for (int id : mAvailableFrontendIds) {
- FrontendResource fr = getFrontendResource(id);
+ for (FrontendResource fr : getFrontendResources().values()) {
if (fr.getType() == request.getFrontendType()) {
if (!fr.isInUse()) {
// Grant unused frontend with no exclusive group members first.
- if (fr.getExclusiveGroupMemberFeIds().size() == 0) {
- grantingFrontendId = id;
+ if (fr.getExclusiveGroupMemberFeIds().isEmpty()) {
+ grantingFrontendId = fr.getId();
break;
} else if (grantingFrontendId < 0) {
// Grant the unused frontend with lower id first if all the unused
// frontends have exclusive group members.
- grantingFrontendId = id;
+ grantingFrontendId = fr.getId();
}
} else if (grantingFrontendId < 0) {
// Record the frontend id with the lowest client priority among all the
// in use frontends when no available frontend has been found.
- int priority = getOwnerClientPriority(id);
+ int priority = getOwnerClientPriority(fr);
if (currentLowestPriority > priority) {
- inUseLowestPriorityFrId = id;
+ inUseLowestPriorityFrId = fr.getId();
currentLowestPriority = priority;
}
}
@@ -410,17 +464,20 @@
// Grant frontend when there is unused resource.
if (grantingFrontendId > -1) {
- frontendId[0] = grantingFrontendId;
- updateFrontendClientMappingOnNewGrant(frontendId[0], request.getClientId());
+ frontendHandle[0] = generateResourceHandle(
+ TUNER_RESOURCE_TYPE_FRONTEND, grantingFrontendId);
+ updateFrontendClientMappingOnNewGrant(grantingFrontendId, request.getClientId());
return true;
}
// When all the resources are occupied, grant the lowest priority resource if the
// request client has higher priority.
if (inUseLowestPriorityFrId > -1 && (requestClient.getPriority() > currentLowestPriority)) {
- frontendId[0] = inUseLowestPriorityFrId;
- reclaimFrontendResource(getFrontendResource(frontendId[0]).getOwnerClientId());
- updateFrontendClientMappingOnNewGrant(frontendId[0], request.getClientId());
+ frontendHandle[0] = generateResourceHandle(
+ TUNER_RESOURCE_TYPE_FRONTEND, inUseLowestPriorityFrId);
+ reclaimFrontendResource(getFrontendResource(
+ inUseLowestPriorityFrId).getOwnerClientId());
+ updateFrontendClientMappingOnNewGrant(inUseLowestPriorityFrId, request.getClientId());
return true;
}
@@ -428,6 +485,80 @@
}
@VisibleForTesting
+ boolean requestDemuxInternal(TunerDemuxRequest request, int[] demuxHandle) {
+ if (DEBUG) {
+ Slog.d(TAG, "requestDemux(request=" + request + ")");
+ }
+ demuxHandle[0] = generateResourceHandle(TUNER_RESOURCE_TYPE_DEMUX, 0);
+ return true;
+ }
+
+ @VisibleForTesting
+ boolean requestDescramblerInternal(TunerDescramblerRequest request, int[] descramblerHandle) {
+ if (DEBUG) {
+ Slog.d(TAG, "requestDescrambler(request=" + request + ")");
+ }
+ descramblerHandle[0] = generateResourceHandle(TUNER_RESOURCE_TYPE_DESCRAMBLER, 0);
+ return true;
+ }
+
+ @VisibleForTesting
+ protected class ResourcesReclaimListenerRecord implements IBinder.DeathRecipient {
+ private final IResourcesReclaimListener mListener;
+ private final int mClientId;
+
+ public ResourcesReclaimListenerRecord(IResourcesReclaimListener listener, int clientId) {
+ mListener = listener;
+ mClientId = clientId;
+ }
+
+ @Override
+ public void binderDied() {
+ synchronized (mLock) {
+ removeClientProfile(mClientId);
+ }
+ }
+
+ public int getId() {
+ return mClientId;
+ }
+
+ public IResourcesReclaimListener getListener() {
+ return mListener;
+ }
+ }
+
+ private void addResourcesReclaimListener(int clientId, IResourcesReclaimListener listener) {
+ if (listener == null) {
+ if (DEBUG) {
+ Slog.w(TAG, "Listener is null when client " + clientId + " registered!");
+ }
+ return;
+ }
+
+ ResourcesReclaimListenerRecord record =
+ new ResourcesReclaimListenerRecord(listener, clientId);
+
+ try {
+ listener.asBinder().linkToDeath(record, 0);
+ } catch (RemoteException e) {
+ Slog.w(TAG, "Listener already died.");
+ return;
+ }
+
+ mListeners.put(clientId, record);
+ }
+
+ @VisibleForTesting
+ protected void reclaimFrontendResource(int reclaimingId) {
+ try {
+ mListeners.get(reclaimingId).getListener().onReclaimResources();
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Failed to reclaim resources on client " + reclaimingId, e);
+ }
+ }
+
+ @VisibleForTesting
protected int getClientPriority(int useCase, int pid) {
if (DEBUG) {
Slog.d(TAG, "getClientPriority useCase=" + useCase
@@ -446,17 +577,6 @@
return true;
}
- @VisibleForTesting
- protected void reclaimFrontendResource(int reclaimingId) throws RemoteException {
- if (mListeners.get(reclaimingId) != null) {
- try {
- mListeners.get(reclaimingId).onReclaimResources();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
private void updateFrontendClientMappingOnNewGrant(int grantingId, int ownerClientId) {
FrontendResource grantingFrontend = getFrontendResource(grantingId);
ClientProfile ownerProfile = getClientProfile(ownerClientId);
@@ -471,37 +591,97 @@
/**
* Get the owner client's priority from the frontend id.
*
- * @param frontendId an in use frontend id.
+ * @param frontend an in use frontend.
* @return the priority of the owner client of the frontend.
*/
- private int getOwnerClientPriority(int frontendId) {
- return getClientProfile(getFrontendResource(frontendId).getOwnerClientId()).getPriority();
+ private int getOwnerClientPriority(FrontendResource frontend) {
+ return getClientProfile(frontend.getOwnerClientId()).getPriority();
}
- private ClientProfile getClientProfile(int clientId) {
- return mClientProfiles.get(clientId);
- }
-
+ @VisibleForTesting
+ @Nullable
protected FrontendResource getFrontendResource(int frontendId) {
return mFrontendResources.get(frontendId);
}
@VisibleForTesting
- protected SparseArray<ClientProfile> getClientProfiles() {
- return mClientProfiles;
- }
-
- @VisibleForTesting
- protected SparseArray<FrontendResource> getFrontendResources() {
+ protected Map<Integer, FrontendResource> getFrontendResources() {
return mFrontendResources;
}
- private boolean checkClientExists(int clientId) {
- return mRegisteredClientIds.contains(clientId);
+ private void addFrontendResource(FrontendResource newFe) {
+ // Update the exclusive group member list in all the existing Frontend resource
+ for (FrontendResource fe : getFrontendResources().values()) {
+ if (fe.getExclusiveGroupId() == newFe.getExclusiveGroupId()) {
+ newFe.addExclusiveGroupMemberFeId(fe.getId());
+ newFe.addExclusiveGroupMemberFeIds(fe.getExclusiveGroupMemberFeIds());
+ for (int excGroupmemberFeId : fe.getExclusiveGroupMemberFeIds()) {
+ getFrontendResource(excGroupmemberFeId)
+ .addExclusiveGroupMemberFeId(newFe.getId());
+ }
+ fe.addExclusiveGroupMemberFeId(newFe.getId());
+ break;
+ }
+ }
+ // Update resource list and available id list
+ mFrontendResources.put(newFe.getId(), newFe);
}
- private void enforceAccessPermission() {
- getContext().enforceCallingOrSelfPermission(
- "android.permission.TUNER_RESOURCE_ACCESS", TAG);
+ private void removeFrontendResource(int removingId) {
+ FrontendResource fe = getFrontendResource(removingId);
+ for (int excGroupmemberFeId : fe.getExclusiveGroupMemberFeIds()) {
+ getFrontendResource(excGroupmemberFeId)
+ .removeExclusiveGroupMemberFeId(fe.getId());
+ }
+ mFrontendResources.remove(removingId);
+ }
+
+ @VisibleForTesting
+ @Nullable
+ protected ClientProfile getClientProfile(int clientId) {
+ return mClientProfiles.get(clientId);
+ }
+
+ private void addClientProfile(int clientId, ClientProfile profile,
+ IResourcesReclaimListener listener) {
+ mClientProfiles.put(clientId, profile);
+ addResourcesReclaimListener(clientId, listener);
+ }
+
+ private void removeClientProfile(int clientId) {
+ for (int id : getClientProfile(clientId).getInUseFrontendIds()) {
+ getFrontendResource(id).removeOwner();
+ for (int groupMemberId : getFrontendResource(id).getExclusiveGroupMemberFeIds()) {
+ getFrontendResource(groupMemberId).removeOwner();
+ }
+ }
+ mClientProfiles.remove(clientId);
+ mListeners.remove(clientId);
+ }
+
+ @VisibleForTesting
+ protected boolean checkClientExists(int clientId) {
+ return mClientProfiles.keySet().contains(clientId);
+ }
+
+ private int generateResourceHandle(@TunerResourceType int resourceType, int resourceId) {
+ return (resourceType & 0x000000ff) << 24
+ | (resourceId << 16)
+ | (mResourceRequestCount++ & 0xffff);
+ }
+
+ private void enforceTrmAccessPermission(String apiName) {
+ getContext().enforceCallingPermission("android.permission.TUNER_RESOURCE_ACCESS",
+ TAG + ": " + "apiName");
+ }
+
+ private void enforceTunerAccessPermission(String apiName) {
+ getContext().enforceCallingPermission("android.Manifest.permission.ACCESS_TV_TUNER",
+ TAG + ": " + "apiName");
+ }
+
+ private void enforceDescramblerAccessPermission(String apiName) {
+ getContext().enforceCallingPermission("android.Manifest.permission.ACCESS_TV_DESCRAMBLER",
+ TAG + ": " + "apiName");
}
}
diff --git a/services/core/java/com/android/server/tv/tunerresourcemanager/UseCasePriorityHints.java b/services/core/java/com/android/server/tv/tunerresourcemanager/UseCasePriorityHints.java
index 8c2de47..367b966 100644
--- a/services/core/java/com/android/server/tv/tunerresourcemanager/UseCasePriorityHints.java
+++ b/services/core/java/com/android/server/tv/tunerresourcemanager/UseCasePriorityHints.java
@@ -31,8 +31,8 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
/**
* This class provides the Tuner Resource Manager use case priority hints config info including a
@@ -56,7 +56,7 @@
*/
SparseArray<int[]> mPriorityHints = new SparseArray<>();
- List<Integer> mVendorDefinedUseCase = new ArrayList<>();
+ Set<Integer> mVendorDefinedUseCase = new HashSet<>();
private int mDefaultForeground = 150;
private int mDefaultBackground = 50;
diff --git a/services/core/java/com/android/server/twilight/TwilightService.java b/services/core/java/com/android/server/twilight/TwilightService.java
index 761fbf8..88a60dd 100644
--- a/services/core/java/com/android/server/twilight/TwilightService.java
+++ b/services/core/java/com/android/server/twilight/TwilightService.java
@@ -50,7 +50,7 @@
implements AlarmManager.OnAlarmListener, Handler.Callback, LocationListener {
private static final String TAG = "TwilightService";
- private static final String FEATURE_ID = "TwilightService";
+ private static final String ATTRIBUTION_TAG = "TwilightService";
private static final boolean DEBUG = false;
private static final int MSG_START_LISTENING = 1;
@@ -74,7 +74,7 @@
protected TwilightState mLastTwilightState;
public TwilightService(Context context) {
- super(context.createFeatureContext(FEATURE_ID));
+ super(context.createAttributionContext(ATTRIBUTION_TAG));
mHandler = new Handler(Looper.getMainLooper(), this);
}
diff --git a/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java b/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
index 73bb4bf..948439d 100644
--- a/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
+++ b/services/core/java/com/android/server/updates/ConfigUpdateInstallReceiver.java
@@ -20,6 +20,7 @@
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
+import android.os.Binder;
import android.util.EventLog;
import android.util.Slog;
@@ -134,7 +135,12 @@
private BufferedInputStream getAltContent(Context c, Intent i) throws IOException {
Uri content = getContentFromIntent(i);
- return new BufferedInputStream(c.getContentResolver().openInputStream(content));
+ Binder.allowBlockingForCurrentThread();
+ try {
+ return new BufferedInputStream(c.getContentResolver().openInputStream(content));
+ } finally {
+ Binder.defaultBlockingForCurrentThread();
+ }
}
private byte[] getCurrentContent() {
diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
index 6eb3c0f..a298b89 100644
--- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
+++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
@@ -2184,47 +2184,6 @@
}
}
- /**
- * Called when the wallpaper needs to zoom out.
- *
- * @param zoom from 0 to 1 (inclusive) where 1 means fully zoomed out, 0 means fully zoomed in.
- * @param callingPackage package name calling this API.
- * @param displayId id of the display whose zoom is updating.
- */
- public void setWallpaperZoomOut(float zoom, String callingPackage, int displayId) {
- if (!isWallpaperSupported(callingPackage)) {
- return;
- }
- synchronized (mLock) {
- if (!isValidDisplay(displayId)) {
- throw new IllegalArgumentException("Cannot find display with id=" + displayId);
- }
- int userId = UserHandle.getCallingUserId();
- if (mCurrentUserId != userId) {
- return; // Don't change the properties now
- }
- WallpaperData wallpaper = getWallpaperSafeLocked(userId, FLAG_SYSTEM);
- if (zoom < 0 || zoom > 1f) {
- throw new IllegalArgumentException("zoom must be between 0 and one: " + zoom);
- }
-
- if (wallpaper.connection != null) {
- final WallpaperConnection.DisplayConnector connector = wallpaper.connection
- .getDisplayConnectorOrCreate(displayId);
- final IWallpaperEngine engine = connector != null ? connector.mEngine : null;
- if (engine != null) {
- try {
- engine.setZoomOut(zoom);
- } catch (RemoteException e) {
- if (DEBUG) {
- Slog.w(TAG, "Couldn't set wallpaper zoom", e);
- }
- }
- }
- }
- }
- }
-
@Deprecated
@Override
public ParcelFileDescriptor getWallpaper(String callingPkg, IWallpaperManagerCallback cb,
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index d7a80bf..68224b5 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -27,7 +27,6 @@
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.NonNull;
-import android.app.Service;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
@@ -127,7 +126,7 @@
public boolean setWindowsForAccessibilityCallbackLocked(int displayId,
WindowsForAccessibilityCallback callback) {
if (callback != null) {
- final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
+ final DisplayContent dc = mService.mRoot.getDisplayContentOrCreate(displayId);
if (dc == null) {
return false;
}
diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
index 7a30211..c4545fa 100644
--- a/services/core/java/com/android/server/wm/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -200,6 +200,7 @@
import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
+import static com.android.server.wm.WindowContainerChildProto.ACTIVITY;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW_VERBOSE;
@@ -1350,11 +1351,16 @@
mLetterbox.attachInput(w);
}
getPosition(mTmpPoint);
- // Get the bounds of the "space-to-fill". In multi-window mode, the task-level
- // represents this. In fullscreen-mode, the stack does (since the orientation letterbox
- // is also applied to the task).
- Rect spaceToFill = (inMultiWindowMode() || getStack() == null)
- ? task.getDisplayedBounds() : getStack().getDisplayedBounds();
+ // Get the bounds of the "space-to-fill". The transformed bounds have the highest
+ // priority because the activity is launched in a rotated environment. In multi-window
+ // mode, the task-level represents this. In fullscreen-mode, the task container does
+ // (since the orientation letterbox is also applied to the task).
+ final Rect transformedBounds = getFixedRotationTransformDisplayBounds();
+ final Rect spaceToFill = transformedBounds != null
+ ? transformedBounds
+ : inMultiWindowMode()
+ ? task.getDisplayedBounds()
+ : getRootTask().getParent().getDisplayedBounds();
mLetterbox.layout(spaceToFill, w.getFrameLw(), mTmpPoint);
} else if (mLetterbox != null) {
mLetterbox.hide();
@@ -1588,6 +1594,11 @@
info.taskAffinity = uid + ":" + info.taskAffinity;
}
taskAffinity = info.taskAffinity;
+ if (info.windowLayout != null && info.windowLayout.windowLayoutAffinity != null
+ && !info.windowLayout.windowLayoutAffinity.startsWith(uid)) {
+ info.windowLayout.windowLayoutAffinity =
+ uid + ":" + info.windowLayout.windowLayoutAffinity;
+ }
stateNotNeeded = (aInfo.flags & FLAG_STATE_NOT_NEEDED) != 0;
nonLocalizedLabel = aInfo.nonLocalizedLabel;
labelRes = aInfo.labelRes;
@@ -3150,7 +3161,7 @@
// Reset the last saved PiP snap fraction on removal.
mDisplayContent.mPinnedStackControllerLocked.resetReentryBounds(mActivityComponent);
-
+ mWmService.mEmbeddedWindowController.onActivityRemoved(this);
mRemovingFromDisplay = false;
}
@@ -6356,33 +6367,17 @@
if (mCompatDisplayInsets != null) {
resolveSizeCompatModeConfiguration(newParentConfiguration);
} else {
- // We ignore activities' requested orientation in multi-window modes. Task level may
- // take them into consideration when calculating bounds.
if (inMultiWindowMode()) {
+ // We ignore activities' requested orientation in multi-window modes. Task level may
+ // take them into consideration when calculating bounds.
resolvedConfig.orientation = Configuration.ORIENTATION_UNDEFINED;
- }
- final Rect parentAppBounds = newParentConfiguration.windowConfiguration.getAppBounds();
- final Rect parentBounds = newParentConfiguration.windowConfiguration.getBounds();
- // Use tmp bounds to calculate aspect ratio so we can know whether the activity should
- // use restricted size (resolvedBounds may be the requested override bounds).
- mTmpBounds.setEmpty();
- applyAspectRatio(mTmpBounds, parentAppBounds, parentBounds);
- // If the out bounds is not empty, it means the activity cannot fill parent's app
- // bounds, then the relative configuration (e.g. screen size, layout) needs to be
- // resolved according to the bounds.
- if (!mTmpBounds.isEmpty()) {
- final Rect resolvedBounds = resolvedConfig.windowConfiguration.getBounds();
- resolvedBounds.set(mTmpBounds);
- // Exclude the horizontal decor area because the activity will be centered
- // horizontally in parent's app bounds to balance the visual appearance.
- resolvedBounds.left = parentAppBounds.left;
- task.computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
- getFixedRotationTransformDisplayInfo());
- final int offsetX = getHorizontalCenterOffset(
- parentAppBounds.width(), resolvedBounds.width());
- if (offsetX > 0) {
- offsetBounds(resolvedConfig, offsetX - resolvedBounds.left, 0 /* offsetY */);
+ // If the activity has requested override bounds, the configuration needs to be
+ // computed accordingly.
+ if (!matchParentBounds()) {
+ task.computeConfigResourceOverrides(resolvedConfig, newParentConfiguration);
}
+ } else {
+ resolveFullscreenConfiguration(newParentConfiguration);
}
}
@@ -6394,6 +6389,43 @@
}
/**
+ * Resolves the configuration of activity in fullscreen mode. If the bounds are restricted by
+ * aspect ratio, the position will be centered horizontally in parent's app bounds to balance
+ * the visual appearance. The policy of aspect ratio has higher priority than the requested
+ * override bounds.
+ */
+ private void resolveFullscreenConfiguration(Configuration newParentConfiguration) {
+ final Configuration resolvedConfig = getResolvedOverrideConfiguration();
+ final Rect parentAppBounds = newParentConfiguration.windowConfiguration.getAppBounds();
+ final Rect parentBounds = newParentConfiguration.windowConfiguration.getBounds();
+ final Rect resolvedBounds = resolvedConfig.windowConfiguration.getBounds();
+ // Use tmp bounds to calculate aspect ratio so we can know whether the activity should use
+ // restricted size (resolved bounds may be the requested override bounds).
+ mTmpBounds.setEmpty();
+ applyAspectRatio(mTmpBounds, parentAppBounds, parentBounds);
+ // If the out bounds is not empty, it means the activity cannot fill parent's app bounds,
+ // then there is space to be centered.
+ final boolean needToBeCentered = !mTmpBounds.isEmpty();
+ if (needToBeCentered) {
+ resolvedBounds.set(mTmpBounds);
+ // Exclude the horizontal decor area.
+ resolvedBounds.left = parentAppBounds.left;
+ }
+ if (!resolvedBounds.isEmpty() && !resolvedBounds.equals(parentBounds)) {
+ // Compute the configuration based on the resolved bounds. If aspect ratio doesn't
+ // restrict, the bounds should be the requested override bounds.
+ task.computeConfigResourceOverrides(resolvedConfig, newParentConfiguration,
+ getFixedRotationTransformDisplayInfo());
+ }
+ if (needToBeCentered) {
+ // Offset to center relative to parent's app bounds.
+ final int offsetX = getHorizontalCenterOffset(
+ parentAppBounds.width(), resolvedBounds.width());
+ offsetBounds(resolvedConfig, offsetX, 0 /* offsetY */);
+ }
+ }
+
+ /**
* Resolves consistent screen configuration for orientation and rotation changes without
* inheriting the parent bounds.
*/
@@ -6501,7 +6533,7 @@
// Above coordinates are in "@" space, now place "*" and "#" to screen space.
final int screenPosX = parentAppBounds.left + offsetX;
final int screenPosY = parentBounds.top;
- if (screenPosX > 0 || screenPosY > 0) {
+ if (screenPosX != 0 || screenPosY != 0) {
if (mSizeCompatBounds != null) {
mSizeCompatBounds.offset(screenPosX, screenPosY);
}
@@ -7450,6 +7482,11 @@
}
@Override
+ long getProtoFieldId() {
+ return ACTIVITY;
+ }
+
+ @Override
public void dumpDebug(ProtoOutputStream proto, long fieldId,
@WindowTraceLogLevel int logLevel) {
// Critical log level logs only visible elements to mitigate performance overheard
@@ -7620,7 +7657,7 @@
return new RemoteAnimationTarget(task.mTaskId, record.getMode(),
record.mAdapter.mCapturedLeash, !fillsParent(),
mainWindow.mWinAnimator.mLastClipRect, insets,
- getPrefixOrderIndex(), record.mAdapter.mPosition,
+ getPrefixOrderIndex(), record.mAdapter.mPosition, record.mAdapter.mLocalBounds,
record.mAdapter.mStackBounds, task.getWindowConfiguration(),
false /*isNotInRecents*/,
record.mThumbnailAdapter != null ? record.mThumbnailAdapter.mCapturedLeash : null,
diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
index bc12923..4ebb423 100644
--- a/services/core/java/com/android/server/wm/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -90,7 +90,6 @@
import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_ACTIVITY_STACK_MSG;
import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
-import static com.android.server.wm.TaskProto.ACTIVITIES;
import static com.android.server.wm.TaskProto.ACTIVITY_TYPE;
import static com.android.server.wm.TaskProto.ANIMATING_BOUNDS;
import static com.android.server.wm.TaskProto.BOUNDS;
@@ -109,7 +108,6 @@
import static com.android.server.wm.TaskProto.ROOT_TASK_ID;
import static com.android.server.wm.TaskProto.SURFACE_HEIGHT;
import static com.android.server.wm.TaskProto.SURFACE_WIDTH;
-import static com.android.server.wm.TaskProto.TASKS;
import static com.android.server.wm.TaskProto.WINDOW_CONTAINER;
import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
@@ -155,7 +153,6 @@
import android.util.proto.ProtoOutputStream;
import android.view.Display;
import android.view.DisplayInfo;
-import android.view.ITaskOrganizer;
import android.view.SurfaceControl;
import com.android.internal.annotations.GuardedBy;
@@ -309,8 +306,6 @@
// TODO(task-hierarchy): remove when tiles can be actual parents
TaskTile mTile = null;
- private int mLastTaskOrganizerWindowingMode = -1;
-
private final Handler mHandler;
private class ActivityStackHandler extends Handler {
@@ -637,8 +632,6 @@
super.onConfigurationChanged(newParentConfig);
- updateTaskOrganizerState();
-
// Only need to update surface size here since the super method will handle updating
// surface position.
updateSurfaceSize(getPendingTransaction());
@@ -649,14 +642,6 @@
if (prevWindowingMode != getWindowingMode()) {
mDisplayContent.onStackWindowingModeChanged(this);
-
- if (inSplitScreenSecondaryWindowingMode()) {
- // When the stack is resized due to entering split screen secondary, offset the
- // windows to compensate for the new stack position.
- forAllWindows(w -> {
- w.mWinAnimator.setOffsetPositionForStackResize(true);
- }, true);
- }
}
final DisplayContent display = getDisplay();
@@ -702,30 +687,6 @@
}
}
- void updateTaskOrganizerState() {
- if (!isRootTask()) {
- return;
- }
-
- final int windowingMode = getWindowingMode();
- if (windowingMode == mLastTaskOrganizerWindowingMode) {
- // If our windowing mode hasn't actually changed, then just stick
- // with our old organizer. This lets us implement the semantic
- // where SysUI can continue to manage it's old tasks
- // while CTS temporarily takes over the registration.
- return;
- }
- /*
- * Different windowing modes may be managed by different task organizers. If
- * getTaskOrganizer returns null, we still call setTaskOrganizer to
- * make sure we clear it.
- */
- final ITaskOrganizer org =
- mWmService.mAtmService.mTaskOrganizerController.getTaskOrganizer(windowingMode);
- setTaskOrganizer(org);
- mLastTaskOrganizerWindowingMode = windowingMode;
- }
-
@Override
public void setWindowingMode(int windowingMode) {
// Calling Task#setWindowingMode() for leaf task since this is the a specialization of
@@ -1469,11 +1430,11 @@
if (resumeNext) {
final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
- if (!topStack.shouldSleepOrShutDownActivities()) {
+ if (topStack != null && !topStack.shouldSleepOrShutDownActivities()) {
mRootWindowContainer.resumeFocusedStacksTopActivities(topStack, prev, null);
} else {
checkReadyForSleep();
- ActivityRecord top = topStack.topRunningActivity();
+ final ActivityRecord top = topStack != null ? topStack.topRunningActivity() : null;
if (top == null || (prev != null && top != prev)) {
// If there are no more activities available to run, do resume anyway to start
// something. Also if the top activity on the stack is not the just paused
@@ -2395,8 +2356,10 @@
}
Task task = null;
if (!newTask && isOrhasTask) {
+ // Starting activity cannot be occluding activity, otherwise starting window could be
+ // remove immediately without transferring to starting activity.
final ActivityRecord occludingActivity = getActivity(
- (ar) -> !ar.finishing && ar.occludesParent(), true, rTask);
+ (ar) -> !ar.finishing && ar.occludesParent(), true, r);
if (occludingActivity != null) {
// Here it is! Now, if this is not yet visible (occluded by another task) to the
// user, then just add it without starting; it will get started when the user
@@ -3883,9 +3846,10 @@
return;
}
if (mTile != null) {
- reparentSurfaceControl(getPendingTransaction(), mTile.getSurfaceControl());
+ // don't use reparentSurfaceControl because we need to bypass taskorg check
+ mSurfaceAnimator.reparent(getPendingTransaction(), mTile.getSurfaceControl());
} else if (mTile == null && origTile != null) {
- reparentSurfaceControl(getPendingTransaction(), getParentSurfaceControl());
+ mSurfaceAnimator.reparent(getPendingTransaction(), getParentSurfaceControl());
}
}
@@ -3918,17 +3882,6 @@
proto.write(DISPLAY_ID, getDisplayId());
proto.write(ROOT_TASK_ID, getRootTaskId());
- for (int i = mChildren.size() - 1; i >= 0; --i) {
- final WindowContainer child = mChildren.get(i);
- if (child instanceof Task) {
- child.dumpDebug(proto, TASKS, logLevel);
- } else if (child instanceof ActivityRecord) {
- child.dumpDebug(proto, ACTIVITIES, logLevel);
- } else {
- throw new IllegalStateException("Unknown child type: " + child);
- }
- }
-
if (mResumedActivity != null) {
mResumedActivity.writeIdentifierToProto(proto, RESUMED_ACTIVITY);
}
diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
index 3210304..c7a1391 100644
--- a/services/core/java/com/android/server/wm/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -29,7 +29,6 @@
import static android.app.ActivityManager.START_TASK_TO_FRONT;
import static android.app.WaitResult.LAUNCH_STATE_COLD;
import static android.app.WaitResult.LAUNCH_STATE_HOT;
-import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
@@ -178,6 +177,9 @@
private Intent mNewTaskIntent;
private ActivityStack mSourceStack;
private ActivityStack mTargetStack;
+ // The task that the last activity was started into. We currently reset the actual start
+ // activity's task and as a result may not have a reference to the task in all cases
+ private Task mTargetTask;
private boolean mMovedToFront;
private boolean mNoAnimation;
private boolean mKeepCurTransition;
@@ -545,6 +547,7 @@
mNewTaskIntent = starter.mNewTaskIntent;
mSourceStack = starter.mSourceStack;
+ mTargetTask = starter.mTargetTask;
mTargetStack = starter.mTargetStack;
mMovedToFront = starter.mMovedToFront;
mNoAnimation = starter.mNoAnimation;
@@ -615,12 +618,15 @@
int res;
synchronized (mService.mGlobalLock) {
- final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
- stack.mConfigWillChange = mRequest.globalConfig != null
+ final boolean globalConfigWillChange = mRequest.globalConfig != null
&& mService.getGlobalConfiguration().diff(mRequest.globalConfig) != 0;
+ final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
+ if (stack != null) {
+ stack.mConfigWillChange = globalConfigWillChange;
+ }
if (DEBUG_CONFIGURATION) {
Slog.v(TAG_CONFIGURATION, "Starting activity when config will change = "
- + stack.mConfigWillChange);
+ + globalConfigWillChange);
}
final long origId = Binder.clearCallingIdentity();
@@ -633,7 +639,7 @@
Binder.restoreCallingIdentity(origId);
- if (stack.mConfigWillChange) {
+ if (globalConfigWillChange) {
// If the caller also wants to switch to a new configuration, do so now.
// This allows a clean switch, as we are waiting for the current activity
// to pause (so we will not destroy it), and have not yet started the
@@ -641,7 +647,9 @@
mService.mAmInternal.enforceCallingPermission(
android.Manifest.permission.CHANGE_CONFIGURATION,
"updateConfiguration()");
- stack.mConfigWillChange = false;
+ if (stack != null) {
+ stack.mConfigWillChange = false;
+ }
if (DEBUG_CONFIGURATION) {
Slog.v(TAG_CONFIGURATION,
"Updating to new configuration after starting activity.");
@@ -1363,7 +1371,10 @@
// it waits for the new activity to become visible instead, {@link #waitResultIfNeeded}.
mSupervisor.reportWaitingActivityLaunchedIfNeeded(r, result);
- if (startedActivityStack == null) {
+ final Task targetTask = r.getTask() != null
+ ? r.getTask()
+ : mTargetTask;
+ if (startedActivityStack == null || targetTask == null) {
return;
}
@@ -1374,19 +1385,10 @@
// The activity was already running so it wasn't started, but either brought to the
// front or the new intent was delivered to it since it was already in front. Notify
// anyone interested in this piece of information.
- switch (startedActivityStack.getWindowingMode()) {
- case WINDOWING_MODE_PINNED:
- mService.getTaskChangeNotificationController().notifyPinnedActivityRestartAttempt(
- clearedTask);
- break;
- case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
- final ActivityStack homeStack =
- startedActivityStack.getDisplay().getOrCreateRootHomeTask();
- if (homeStack != null && homeStack.shouldBeVisible(null /* starting */)) {
- mService.mWindowManager.showRecentApps();
- }
- break;
- }
+ final ActivityStack homeStack = targetTask.getDisplayContent().getRootHomeTask();
+ final boolean homeTaskVisible = homeStack != null && homeStack.shouldBeVisible(null);
+ mService.getTaskChangeNotificationController().notifyActivityRestartAttempt(
+ targetTask.getTaskInfo(), homeTaskVisible, clearedTask);
}
}
@@ -1512,6 +1514,7 @@
// Compute if there is an existing task that should be used for.
final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
final boolean newTask = targetTask == null;
+ mTargetTask = targetTask;
computeLaunchParams(r, sourceRecord, targetTask);
@@ -1536,9 +1539,11 @@
// If the activity being launched is the same as the one currently at the top, then
// we need to check if it should only be launched once.
final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
- startResult = deliverToCurrentTopIfNeeded(topStack);
- if (startResult != START_SUCCESS) {
- return startResult;
+ if (topStack != null) {
+ startResult = deliverToCurrentTopIfNeeded(topStack);
+ if (startResult != START_SUCCESS) {
+ return startResult;
+ }
}
if (mTargetStack == null) {
@@ -1563,10 +1568,16 @@
mService.mUgmInternal.grantUriPermissionFromIntent(mCallingUid, mStartActivity.packageName,
mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.mUserId);
- mService.getPackageManagerInternalLocked().grantImplicitAccess(
- mStartActivity.mUserId, mIntent,
- UserHandle.getAppId(mStartActivity.info.applicationInfo.uid), mCallingUid,
- true /*direct*/);
+ if (mStartActivity.resultTo != null && mStartActivity.resultTo.info != null) {
+ // we need to resolve resultTo to a uid as grantImplicitAccess deals explicitly in UIDs
+ final PackageManagerInternal pmInternal =
+ mService.getPackageManagerInternalLocked();
+ final int resultToUid = pmInternal.getPackageUidInternal(
+ mStartActivity.resultTo.info.packageName, 0, mStartActivity.mUserId);
+ pmInternal.grantImplicitAccess(mStartActivity.mUserId, mIntent,
+ UserHandle.getAppId(mStartActivity.info.applicationInfo.uid) /*recipient*/,
+ resultToUid /*visible*/, true /*direct*/);
+ }
if (newTask) {
EventLogTags.writeWmCreateTask(mStartActivity.mUserId,
mStartActivity.getTask().mTaskId);
@@ -2005,6 +2016,7 @@
mSourceStack = null;
mTargetStack = null;
+ mTargetTask = null;
mMovedToFront = false;
mNoAnimation = false;
mKeepCurTransition = false;
@@ -2126,10 +2138,13 @@
if ((startFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
ActivityRecord checkedCaller = sourceRecord;
if (checkedCaller == null) {
- checkedCaller = mRootWindowContainer.getTopDisplayFocusedStack()
- .topRunningNonDelayedActivityLocked(mNotTop);
+ ActivityStack topFocusedStack = mRootWindowContainer.getTopDisplayFocusedStack();
+ if (topFocusedStack != null) {
+ checkedCaller = topFocusedStack.topRunningNonDelayedActivityLocked(mNotTop);
+ }
}
- if (!checkedCaller.mActivityComponent.equals(r.mActivityComponent)) {
+ if (checkedCaller == null
+ || !checkedCaller.mActivityComponent.equals(r.mActivityComponent)) {
// Caller is not the same as launcher, so always needed.
mStartFlags &= ~START_FLAG_ONLY_IF_NEEDED;
}
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 98c8b61..7bacc42 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -288,6 +288,7 @@
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
@@ -355,6 +356,8 @@
ActivityManagerInternal mAmInternal;
UriGrantsManagerInternal mUgmInternal;
private PackageManagerInternal mPmInternal;
+ /** The cached sys ui service component name from package manager. */
+ private ComponentName mSysUiServiceComponent;
private PermissionPolicyInternal mPermissionPolicyInternal;
@VisibleForTesting
final ActivityTaskManagerInternal mInternal;
@@ -680,12 +683,15 @@
}
@Override
- public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
- if (mFontScaleUri.equals(uri)) {
- updateFontScaleIfNeeded(userId);
- } else if (mHideErrorDialogsUri.equals(uri)) {
- synchronized (mGlobalLock) {
- updateShouldShowDialogsLocked(getGlobalConfiguration());
+ public void onChange(boolean selfChange, Collection<Uri> uris, int flags,
+ @UserIdInt int userId) {
+ for (Uri uri : uris) {
+ if (mFontScaleUri.equals(uri)) {
+ updateFontScaleIfNeeded(userId);
+ } else if (mHideErrorDialogsUri.equals(uri)) {
+ synchronized (mGlobalLock) {
+ updateShouldShowDialogsLocked(getGlobalConfiguration());
+ }
}
}
}
@@ -1104,8 +1110,8 @@
// If this is coming from the currently resumed activity, it is
// effectively saying that app switches are allowed at this point.
final ActivityStack stack = getTopDisplayFocusedStack();
- if (stack.mResumedActivity != null &&
- stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
+ if (stack != null && stack.mResumedActivity != null
+ && stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
mAppSwitchesAllowedTime = 0;
}
}
@@ -1951,8 +1957,13 @@
public boolean isTopActivityImmersive() {
enforceNotIsolatedCaller("isTopActivityImmersive");
synchronized (mGlobalLock) {
- final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
- return (r != null) ? r.immersive : false;
+ final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
+ if (topFocusedStack == null) {
+ return false;
+ }
+
+ final ActivityRecord r = topFocusedStack.topRunningActivity();
+ return r != null && r.immersive;
}
}
@@ -1981,7 +1992,8 @@
public int getFrontActivityScreenCompatMode() {
enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
synchronized (mGlobalLock) {
- final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
+ final ActivityStack stack = getTopDisplayFocusedStack();
+ final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
if (r == null) {
return ActivityManager.COMPAT_MODE_UNKNOWN;
}
@@ -1995,7 +2007,8 @@
"setFrontActivityScreenCompatMode");
ApplicationInfo ai;
synchronized (mGlobalLock) {
- final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
+ final ActivityStack stack = getTopDisplayFocusedStack();
+ final ActivityRecord r = stack != null ? stack.topRunningActivity() : null;
if (r == null) {
Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
return;
@@ -2383,7 +2396,10 @@
synchronized (mGlobalLock) {
final long origId = Binder.clearCallingIdentity();
try {
- getTopDisplayFocusedStack().unhandledBackLocked();
+ final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
+ if (topFocusedStack != null) {
+ topFocusedStack.unhandledBackLocked();
+ }
} finally {
Binder.restoreCallingIdentity(origId);
}
@@ -3616,7 +3632,8 @@
"enqueueAssistContext()");
synchronized (mGlobalLock) {
- ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
+ final ActivityStack stack = getTopDisplayFocusedStack();
+ ActivityRecord activity = stack != null ? stack.getTopNonFinishingActivity() : null;
if (activity == null) {
Slog.w(TAG, "getAssistContextExtras failed: no top activity");
return null;
@@ -5854,6 +5871,14 @@
return mPmInternal;
}
+ ComponentName getSysUiServiceComponentLocked() {
+ if (mSysUiServiceComponent == null) {
+ final PackageManagerInternal pm = getPackageManagerInternalLocked();
+ mSysUiServiceComponent = pm.getSystemUiServiceComponent();
+ }
+ return mSysUiServiceComponent;
+ }
+
PermissionPolicyInternal getPermissionPolicyInternal() {
if (mPermissionPolicyInternal == null) {
mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
@@ -7037,9 +7062,9 @@
mRootWindowContainer.dumpDisplayConfigs(pw, " ");
}
if (dumpAll) {
- if (dumpPackage == null) {
- pw.println(" mConfigWillChange: "
- + getTopDisplayFocusedStack().mConfigWillChange);
+ final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
+ if (dumpPackage == null && topFocusedStack != null) {
+ pw.println(" mConfigWillChange: " + topFocusedStack.mConfigWillChange);
}
if (mCompatModePackages.getPackages().size() > 0) {
boolean printed = false;
@@ -7120,7 +7145,10 @@
synchronized (mGlobalLock) {
if (dumpPackage == null) {
getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
- proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
+ final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
+ if (topFocusedStack != null) {
+ proto.write(CONFIG_WILL_CHANGE, topFocusedStack.mConfigWillChange);
+ }
writeSleepStateToProto(proto, wakeFullness, testPssMode);
if (mRunningVoice != null) {
final long vrToken = proto.start(
diff --git a/services/core/java/com/android/server/wm/BLASTSyncEngine.java b/services/core/java/com/android/server/wm/BLASTSyncEngine.java
index 94decc7..c18ed7d 100644
--- a/services/core/java/com/android/server/wm/BLASTSyncEngine.java
+++ b/services/core/java/com/android/server/wm/BLASTSyncEngine.java
@@ -114,7 +114,6 @@
return st.addToSync(wc);
}
- // TODO(b/148476626): TIMEOUTS!
void setReady(int id) {
final SyncState st = mPendingSyncs.get(id);
st.setReady();
diff --git a/services/core/java/com/android/server/wm/DisplayArea.java b/services/core/java/com/android/server/wm/DisplayArea.java
index 0d365b1..d9e41af 100644
--- a/services/core/java/com/android/server/wm/DisplayArea.java
+++ b/services/core/java/com/android/server/wm/DisplayArea.java
@@ -23,13 +23,10 @@
import static android.view.WindowManagerPolicyConstants.APPLICATION_LAYER;
import static com.android.internal.util.Preconditions.checkState;
-import static com.android.server.wm.DisplayAreaChildProto.DISPLAY_AREA;
-import static com.android.server.wm.DisplayAreaChildProto.UNKNOWN;
-import static com.android.server.wm.DisplayAreaChildProto.WINDOW;
-import static com.android.server.wm.DisplayAreaProto.CHILDREN;
import static com.android.server.wm.DisplayAreaProto.NAME;
import static com.android.server.wm.DisplayAreaProto.WINDOW_CONTAINER;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
+import static com.android.server.wm.WindowContainerChildProto.DISPLAY_AREA;
import android.graphics.Rect;
import android.util.proto.ProtoOutputStream;
@@ -111,24 +108,14 @@
final long token = proto.start(fieldId);
super.dumpDebug(proto, WINDOW_CONTAINER, logLevel);
proto.write(NAME, mName);
- for (int i = 0; i < getChildCount(); i++) {
- final long childToken = proto.start(CHILDREN);
- final T child = getChildAt(i);
- if (child instanceof ActivityStack) {
- // TODO(display-area): Dump stacks & tasks here, instead of in DisplayContent's
- // dumpDebug. For now, skip them here to avoid dumping them as UNKNOWN.
- } else if (child instanceof WindowToken) {
- ((WindowToken) child).dumpDebug(proto, WINDOW, logLevel);
- } else if (child instanceof DisplayArea) {
- child.dumpDebug(proto, DISPLAY_AREA, logLevel);
- } else {
- proto.write(UNKNOWN, child.getClass().getSimpleName());
- }
- proto.end(childToken);
- }
proto.end(token);
}
+ @Override
+ long getProtoFieldId() {
+ return DISPLAY_AREA;
+ }
+
/**
* DisplayArea that contains WindowTokens, and orders them according to their type.
*/
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 55ce84e..aad242d 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -94,6 +94,7 @@
import static com.android.server.wm.DisplayContentProto.CLOSING_APPS;
import static com.android.server.wm.DisplayContentProto.DISPLAY_FRAMES;
import static com.android.server.wm.DisplayContentProto.DISPLAY_INFO;
+import static com.android.server.wm.DisplayContentProto.DISPLAY_READY;
import static com.android.server.wm.DisplayContentProto.DPI;
import static com.android.server.wm.DisplayContentProto.FOCUSED_APP;
import static com.android.server.wm.DisplayContentProto.FOCUSED_ROOT_TASK_ID;
@@ -105,7 +106,6 @@
import static com.android.server.wm.DisplayContentProto.ROTATION;
import static com.android.server.wm.DisplayContentProto.SCREEN_ROTATION_ANIMATION;
import static com.android.server.wm.DisplayContentProto.SINGLE_TASK_INSTANCE;
-import static com.android.server.wm.DisplayContentProto.TASKS;
import static com.android.server.wm.DisplayContentProto.WINDOW_CONTAINER;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_APP_TRANSITIONS;
@@ -117,6 +117,7 @@
import static com.android.server.wm.RootWindowContainer.TAG_STATES;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
+import static com.android.server.wm.WindowContainerChildProto.DISPLAY_CONTENT;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_DISPLAY;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_INPUT_METHOD;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
@@ -374,7 +375,7 @@
*/
final DisplayMetrics mRealDisplayMetrics = new DisplayMetrics();
- /** @see #computeCompatSmallestWidth(boolean, int, int, int, DisplayCutout) */
+ /** @see #computeCompatSmallestWidth(boolean, int, int, int) */
private final DisplayMetrics mTmpDisplayMetrics = new DisplayMetrics();
/**
@@ -1813,7 +1814,7 @@
final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270);
outConfig.compatSmallestScreenWidthDp = computeCompatSmallestWidth(rotated, uiMode, dw,
- dh, displayCutout);
+ dh);
}
/**
@@ -1921,8 +1922,7 @@
mWmService.mPolicy.adjustConfigurationLw(config, keyboardPresence, navigationPresence);
}
- private int computeCompatSmallestWidth(boolean rotated, int uiMode, int dw, int dh,
- DisplayCutout displayCutout) {
+ private int computeCompatSmallestWidth(boolean rotated, int uiMode, int dw, int dh) {
mTmpDisplayMetrics.setTo(mDisplayMetrics);
final DisplayMetrics tmpDm = mTmpDisplayMetrics;
final int unrotDw, unrotDh;
@@ -1933,19 +1933,21 @@
unrotDw = dw;
unrotDh = dh;
}
- int sw = reduceCompatConfigWidthSize(0, Surface.ROTATION_0, uiMode, tmpDm, unrotDw, unrotDh,
- displayCutout);
- sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_90, uiMode, tmpDm, unrotDh, unrotDw,
- displayCutout);
- sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_180, uiMode, tmpDm, unrotDw, unrotDh,
- displayCutout);
- sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_270, uiMode, tmpDm, unrotDh, unrotDw,
- displayCutout);
+ int sw = reduceCompatConfigWidthSize(0, Surface.ROTATION_0, uiMode, tmpDm, unrotDw,
+ unrotDh);
+ sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_90, uiMode, tmpDm, unrotDh,
+ unrotDw);
+ sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_180, uiMode, tmpDm, unrotDw,
+ unrotDh);
+ sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_270, uiMode, tmpDm, unrotDh,
+ unrotDw);
return sw;
}
private int reduceCompatConfigWidthSize(int curSize, int rotation, int uiMode,
- DisplayMetrics dm, int dw, int dh, DisplayCutout displayCutout) {
+ DisplayMetrics dm, int dw, int dh) {
+ final DisplayCutout displayCutout = calculateDisplayCutoutForRotation(
+ rotation).getDisplayCutout();
dm.noncompatWidthPixels = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode,
displayCutout);
dm.noncompatHeightPixels = mDisplayPolicy.getNonDecorDisplayHeight(dw, dh, rotation, uiMode,
@@ -1986,20 +1988,20 @@
return;
}
int sl = Configuration.resetScreenLayout(outConfig.screenLayout);
- sl = reduceConfigLayout(sl, Surface.ROTATION_0, density, unrotDw, unrotDh, uiMode,
- displayInfo.displayCutout);
- sl = reduceConfigLayout(sl, Surface.ROTATION_90, density, unrotDh, unrotDw, uiMode,
- displayInfo.displayCutout);
- sl = reduceConfigLayout(sl, Surface.ROTATION_180, density, unrotDw, unrotDh, uiMode,
- displayInfo.displayCutout);
- sl = reduceConfigLayout(sl, Surface.ROTATION_270, density, unrotDh, unrotDw, uiMode,
- displayInfo.displayCutout);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_0, density, unrotDw, unrotDh, uiMode);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_90, density, unrotDh, unrotDw, uiMode);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_180, density, unrotDw, unrotDh, uiMode);
+ sl = reduceConfigLayout(sl, Surface.ROTATION_270, density, unrotDh, unrotDw, uiMode);
outConfig.smallestScreenWidthDp = (int)(displayInfo.smallestNominalAppWidth / density);
outConfig.screenLayout = sl;
}
private int reduceConfigLayout(int curLayout, int rotation, float density, int dw, int dh,
- int uiMode, DisplayCutout displayCutout) {
+ int uiMode) {
+ // Get the display cutout at this rotation.
+ final DisplayCutout displayCutout = calculateDisplayCutoutForRotation(
+ rotation).getDisplayCutout();
+
// Get the app screen size at this rotation.
int w = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode, displayCutout);
int h = mDisplayPolicy.getNonDecorDisplayHeight(dw, dh, rotation, uiMode, displayCutout);
@@ -2223,9 +2225,7 @@
.addTaggedData(MetricsEvent.FIELD_DISPLAY_ID, getDisplayId()));
}
- // If there was no pinned stack, we still need to notify the controller of the display info
- // update as a result of the config change.
- if (mPinnedStackControllerLocked != null && !hasPinnedTask()) {
+ if (mPinnedStackControllerLocked != null) {
mPinnedStackControllerLocked.onDisplayInfoChanged(getDisplayInfo());
}
}
@@ -2837,10 +2837,6 @@
proto.write(ID, mDisplayId);
mRootDisplayArea.dumpDebug(proto, ROOT_DISPLAY_AREA, logLevel);
- for (int i = mTaskContainers.getChildCount() - 1; i >= 0; --i) {
- final ActivityStack stack = mTaskContainers.getChildAt(i);
- stack.dumpDebug(proto, TASKS, logLevel);
- }
for (int i = mOverlayContainers.getChildCount() - 1; i >= 0; --i) {
final WindowToken windowToken = mOverlayContainers.getChildAt(i);
windowToken.dumpDebug(proto, OVERLAY_WINDOWS, logLevel);
@@ -2875,11 +2871,17 @@
} else {
proto.write(FOCUSED_ROOT_TASK_ID, INVALID_TASK_ID);
}
+ proto.write(DISPLAY_READY, isReady());
proto.end(token);
}
@Override
+ long getProtoFieldId() {
+ return DISPLAY_CONTENT;
+ }
+
+ @Override
public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
super.dump(pw, prefix, dumpAll);
pw.print(prefix);
@@ -4931,6 +4933,12 @@
scheduleAnimation();
}
}
+
+ @Override
+ boolean shouldMagnify() {
+ // Omitted from Screen-Magnification
+ return false;
+ }
}
/**
@@ -6516,6 +6524,7 @@
lastReparentedStack.postReparent();
}
releaseSelfIfNeeded();
+ mDisplayPolicy.release();
if (!mAllSleepTokens.isEmpty()) {
mRootWindowContainer.mSleepTokens.removeAll(mAllSleepTokens);
diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java
index 00f892f..ab96c61 100644
--- a/services/core/java/com/android/server/wm/DisplayPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayPolicy.java
@@ -28,6 +28,7 @@
import static android.view.InsetsState.ITYPE_BOTTOM_DISPLAY_CUTOUT;
import static android.view.InsetsState.ITYPE_BOTTOM_GESTURES;
import static android.view.InsetsState.ITYPE_BOTTOM_TAPPABLE_ELEMENT;
+import static android.view.InsetsState.ITYPE_IME;
import static android.view.InsetsState.ITYPE_LEFT_DISPLAY_CUTOUT;
import static android.view.InsetsState.ITYPE_LEFT_GESTURES;
import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
@@ -42,7 +43,10 @@
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_NONE;
+import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS;
import static android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS;
+import static android.view.WindowInsetsController.APPEARANCE_OPAQUE_NAVIGATION_BARS;
+import static android.view.WindowInsetsController.APPEARANCE_OPAQUE_STATUS_BARS;
import static android.view.WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE;
import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
import static android.view.WindowManager.INPUT_CONSUMER_NAVIGATION;
@@ -175,6 +179,7 @@
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.policy.GestureNavigationSettingsObserver;
import com.android.internal.policy.ScreenDecorationsUtils;
import com.android.internal.util.ScreenshotHelper;
import com.android.internal.util.function.TriConsumer;
@@ -255,7 +260,9 @@
@Px
private int mBottomGestureAdditionalInset;
@Px
- private int mSideGestureInset;
+ private int mLeftGestureInset;
+ @Px
+ private int mRightGestureInset;
StatusBarManagerInternal getStatusBarManagerInternal() {
synchronized (mServiceAcquireLock) {
@@ -423,6 +430,8 @@
private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
+ private final GestureNavigationSettingsObserver mGestureNavigationSettingsObserver;
+
private class PolicyHandler extends Handler {
PolicyHandler(Looper looper) {
@@ -436,10 +445,12 @@
updateDreamingSleepToken(msg.arg1 != 0);
break;
case MSG_REQUEST_TRANSIENT_BARS:
- WindowState targetBar = (msg.arg1 == MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS)
- ? mStatusBar : mNavigationBar;
- if (targetBar != null) {
- requestTransientBars(targetBar);
+ synchronized (mLock) {
+ WindowState targetBar = (msg.arg1 == MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS)
+ ? mStatusBar : mNavigationBar;
+ if (targetBar != null) {
+ requestTransientBars(targetBar);
+ }
}
break;
case MSG_DISPOSE_INPUT_CONSUMER:
@@ -495,15 +506,20 @@
new SystemGesturesPointerEventListener.Callbacks() {
@Override
public void onSwipeFromTop() {
- if (mStatusBar != null) {
- requestTransientBars(mStatusBar);
+ synchronized (mLock) {
+ if (mStatusBar != null) {
+ requestTransientBars(mStatusBar);
+ }
}
}
@Override
public void onSwipeFromBottom() {
- if (mNavigationBar != null && mNavigationBarPosition == NAV_BAR_BOTTOM) {
- requestTransientBars(mNavigationBar);
+ synchronized (mLock) {
+ if (mNavigationBar != null
+ && mNavigationBarPosition == NAV_BAR_BOTTOM) {
+ requestTransientBars(mNavigationBar);
+ }
}
}
@@ -513,12 +529,13 @@
synchronized (mLock) {
mDisplayContent.calculateSystemGestureExclusion(
excludedRegion, null /* outUnrestricted */);
- }
- final boolean sideAllowed = mNavigationBarAlwaysShowOnSideGesture
- || mNavigationBarPosition == NAV_BAR_RIGHT;
- if (mNavigationBar != null && sideAllowed
- && !mSystemGestures.currentGestureStartedInRegion(excludedRegion)) {
- requestTransientBars(mNavigationBar);
+ final boolean sideAllowed = mNavigationBarAlwaysShowOnSideGesture
+ || mNavigationBarPosition == NAV_BAR_RIGHT;
+ if (mNavigationBar != null && sideAllowed
+ && !mSystemGestures.currentGestureStartedInRegion(
+ excludedRegion)) {
+ requestTransientBars(mNavigationBar);
+ }
}
excludedRegion.recycle();
}
@@ -529,12 +546,13 @@
synchronized (mLock) {
mDisplayContent.calculateSystemGestureExclusion(
excludedRegion, null /* outUnrestricted */);
- }
- final boolean sideAllowed = mNavigationBarAlwaysShowOnSideGesture
- || mNavigationBarPosition == NAV_BAR_LEFT;
- if (mNavigationBar != null && sideAllowed
- && !mSystemGestures.currentGestureStartedInRegion(excludedRegion)) {
- requestTransientBars(mNavigationBar);
+ final boolean sideAllowed = mNavigationBarAlwaysShowOnSideGesture
+ || mNavigationBarPosition == NAV_BAR_LEFT;
+ if (mNavigationBar != null && sideAllowed
+ && !mSystemGestures.currentGestureStartedInRegion(
+ excludedRegion)) {
+ requestTransientBars(mNavigationBar);
+ }
}
excludedRegion.recycle();
}
@@ -638,6 +656,16 @@
mRefreshRatePolicy = new RefreshRatePolicy(mService,
mDisplayContent.getDisplayInfo(),
mService.mHighRefreshRateBlacklist);
+
+ mGestureNavigationSettingsObserver = new GestureNavigationSettingsObserver(mHandler,
+ mContext, () -> {
+ synchronized (mLock) {
+ onConfigurationChanged();
+ mSystemGestures.onConfigurationChanged();
+ mDisplayContent.updateSystemGestureExclusion();
+ }
+ });
+ mHandler.post(mGestureNavigationSettingsObserver::register);
}
void systemReady() {
@@ -710,7 +738,7 @@
}
boolean hasSideGestures() {
- return mHasNavigationBar && mSideGestureInset > 0;
+ return mHasNavigationBar && (mLeftGestureInset > 0 || mRightGestureInset > 0);
}
public boolean navigationBarCanMove() {
@@ -1063,11 +1091,12 @@
inOutFrame.left = 0;
inOutFrame.top = 0;
inOutFrame.bottom = displayFrames.mDisplayHeight;
- inOutFrame.right = displayFrames.mUnrestricted.left + mSideGestureInset;
+ inOutFrame.right = displayFrames.mUnrestricted.left + mLeftGestureInset;
});
mDisplayContent.setInsetProvider(ITYPE_RIGHT_GESTURES, win,
(displayFrames, windowState, inOutFrame) -> {
- inOutFrame.left = displayFrames.mUnrestricted.right - mSideGestureInset;
+ inOutFrame.left = displayFrames.mUnrestricted.right
+ - mRightGestureInset;
inOutFrame.top = 0;
inOutFrame.bottom = displayFrames.mDisplayHeight;
inOutFrame.right = displayFrames.mDisplayWidth;
@@ -1466,8 +1495,14 @@
*/
public void beginLayoutLw(DisplayFrames displayFrames, int uiMode) {
displayFrames.onBeginLayout();
- updateInsetsStateForDisplayCutout(displayFrames,
- mDisplayContent.getInsetsStateController().getRawInsetsState());
+ final InsetsState insetsState =
+ mDisplayContent.getInsetsStateController().getRawInsetsState();
+
+ // Reset the frame of IME so that the layout of windows above IME won't get influenced.
+ // Once we layout the IME, frames will be set again on the source.
+ insetsState.getSource(ITYPE_IME).setFrame(0, 0, 0, 0);
+
+ updateInsetsStateForDisplayCutout(displayFrames, insetsState);
mSystemGestures.screenWidth = displayFrames.mUnrestricted.width();
mSystemGestures.screenHeight = displayFrames.mUnrestricted.height();
@@ -2800,7 +2835,8 @@
}
mNavBarOpacityMode = res.getInteger(R.integer.config_navBarOpacityMode);
- mSideGestureInset = res.getDimensionPixelSize(R.dimen.config_backGestureInset);
+ mLeftGestureInset = mGestureNavigationSettingsObserver.getLeftSensitivity(res);
+ mRightGestureInset = mGestureNavigationSettingsObserver.getRightSensitivity(res);
mNavigationBarLetsThroughTaps = res.getBoolean(R.bool.config_navBarTapThrough);
mNavigationBarAlwaysShowOnSideGesture =
res.getBoolean(R.bool.config_navBarAlwaysShowOnSideEdgeGesture);
@@ -3146,47 +3182,46 @@
}
private void requestTransientBars(WindowState swipeTarget) {
- synchronized (mLock) {
- if (!mService.mPolicy.isUserSetupComplete()) {
- // Swipe-up for navigation bar is disabled during setup
+ if (!mService.mPolicy.isUserSetupComplete()) {
+ // Swipe-up for navigation bar is disabled during setup
+ return;
+ }
+ if (ViewRootImpl.sNewInsetsMode == NEW_INSETS_MODE_FULL) {
+ if (swipeTarget == mNavigationBar
+ && !getInsetsPolicy().isHidden(ITYPE_NAVIGATION_BAR)) {
+ // Don't show status bar when swiping on already visible navigation bar
return;
}
- if (ViewRootImpl.sNewInsetsMode == NEW_INSETS_MODE_FULL) {
- if (swipeTarget == mNavigationBar
- && !getInsetsPolicy().isHidden(ITYPE_NAVIGATION_BAR)) {
- // Don't show status bar when swiping on already visible navigation bar
- return;
- }
- final InsetsControlTarget controlTarget =
- swipeTarget.getControllableInsetProvider().getControlTarget();
+ final InsetsSourceProvider provider = swipeTarget.getControllableInsetProvider();
+ final InsetsControlTarget controlTarget = provider != null
+ ? provider.getControlTarget() : null;
- // No transient mode on lockscreen (in notification shade window).
- if (controlTarget == null || controlTarget == getNotificationShade()) {
+ // No transient mode on lockscreen (in notification shade window).
+ if (controlTarget == null || controlTarget == getNotificationShade()) {
+ return;
+ }
+ if (controlTarget.canShowTransient()) {
+ mDisplayContent.getInsetsPolicy().showTransient(IntArray.wrap(
+ new int[]{ITYPE_STATUS_BAR, ITYPE_NAVIGATION_BAR}));
+ } else {
+ controlTarget.showInsets(Type.systemBars(), false);
+ }
+ } else {
+ boolean sb = mStatusBarController.checkShowTransientBarLw();
+ boolean nb = mNavigationBarController.checkShowTransientBarLw()
+ && !isNavBarEmpty(mLastSystemUiFlags);
+ if (sb || nb) {
+ // Don't show status bar when swiping on already visible navigation bar
+ if (!nb && swipeTarget == mNavigationBar) {
+ if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
return;
}
- if (controlTarget.canShowTransient()) {
- mDisplayContent.getInsetsPolicy().showTransient(IntArray.wrap(
- new int[]{ITYPE_STATUS_BAR, ITYPE_NAVIGATION_BAR}));
- } else {
- controlTarget.showInsets(Type.systemBars(), false);
- }
- } else {
- boolean sb = mStatusBarController.checkShowTransientBarLw();
- boolean nb = mNavigationBarController.checkShowTransientBarLw()
- && !isNavBarEmpty(mLastSystemUiFlags);
- if (sb || nb) {
- // Don't show status bar when swiping on already visible navigation bar
- if (!nb && swipeTarget == mNavigationBar) {
- if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
- return;
- }
- if (sb) mStatusBarController.showTransient();
- if (nb) mNavigationBarController.showTransient();
- updateSystemUiVisibilityLw();
- }
+ if (sb) mStatusBarController.showTransient();
+ if (nb) mNavigationBarController.showTransient();
+ updateSystemUiVisibilityLw();
}
- mImmersiveModeConfirmation.confirmCurrentPrompt();
}
+ mImmersiveModeConfirmation.confirmCurrentPrompt();
}
private void disposeInputConsumer(InputConsumer inputConsumer) {
@@ -3269,11 +3304,19 @@
mService.getStackBounds(inSplitScreen ? WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
: WINDOWING_MODE_FULLSCREEN,
ACTIVITY_TYPE_UNDEFINED, mNonDockedStackBounds);
- final Pair<Integer, Boolean> result =
+ final Pair<Integer, WindowState> result =
updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
final int visibility = result.first;
- final int appearance = win.mAttrs.insetsFlags.appearance
- | InsetsFlags.getAppearance(visibility);
+ final WindowState navColorWin = result.second;
+ final boolean isNavbarColorManagedByIme =
+ navColorWin != null && navColorWin == mDisplayContent.mInputMethodWindow;
+ final int opaqueAppearance = InsetsFlags.getAppearance(visibility)
+ & (APPEARANCE_OPAQUE_STATUS_BARS | APPEARANCE_OPAQUE_NAVIGATION_BARS);
+ final int appearance = ViewRootImpl.sNewInsetsMode == NEW_INSETS_MODE_FULL
+ ? updateLightNavigationBarAppearanceLw(win.mAttrs.insetsFlags.appearance,
+ mTopFullscreenOpaqueWindowState, mTopFullscreenOpaqueOrDimmingWindowState,
+ mDisplayContent.mInputMethodWindow, navColorWin) | opaqueAppearance
+ : InsetsFlags.getAppearance(visibility);
final int diff = visibility ^ mLastSystemUiFlags;
final InsetsPolicy insetsPolicy = getInsetsPolicy();
final boolean isFullscreen = (visibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
@@ -3320,7 +3363,6 @@
new AppearanceRegion(dockedAppearance, dockedStackBounds)}
: new AppearanceRegion[]{
new AppearanceRegion(fullscreenAppearance, fullscreenStackBounds)};
- final boolean isNavbarColorManagedByIme = result.second;
String cause = win.toString();
mHandler.post(() -> {
StatusBarManagerInternal statusBar = getStatusBarManagerInternal();
@@ -3448,7 +3490,25 @@
return vis;
}
- private Pair<Integer, Boolean> updateSystemBarsLw(WindowState win, int oldVis, int vis) {
+ @VisibleForTesting
+ static int updateLightNavigationBarAppearanceLw(int appearance, WindowState opaque,
+ WindowState opaqueOrDimming, WindowState imeWindow, WindowState navColorWin) {
+
+ if (navColorWin != null) {
+ if (navColorWin == imeWindow || navColorWin == opaque) {
+ // Respect the light flag.
+ appearance &= ~APPEARANCE_LIGHT_NAVIGATION_BARS;
+ appearance |= navColorWin.mAttrs.insetsFlags.appearance
+ & APPEARANCE_LIGHT_NAVIGATION_BARS;
+ } else if (navColorWin == opaqueOrDimming && navColorWin.isDimming()) {
+ // Clear the light flag for dimming window.
+ appearance &= ~APPEARANCE_LIGHT_NAVIGATION_BARS;
+ }
+ }
+ return appearance;
+ }
+
+ private Pair<Integer, WindowState> updateSystemBarsLw(WindowState win, int oldVis, int vis) {
final boolean dockedStackVisible =
mDisplayContent.isStackVisible(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY);
final boolean freeformStackVisible =
@@ -3587,11 +3647,8 @@
vis = updateLightNavigationBarLw(vis, mTopFullscreenOpaqueWindowState,
mTopFullscreenOpaqueOrDimmingWindowState,
mDisplayContent.mInputMethodWindow, navColorWin);
- // Navbar color is controlled by the IME.
- final boolean isManagedByIme =
- navColorWin != null && navColorWin == mDisplayContent.mInputMethodWindow;
- return Pair.create(vis, isManagedByIme);
+ return Pair.create(vis, navColorWin);
}
private boolean drawsBarBackground(int vis, WindowState win, BarController controller,
@@ -3913,6 +3970,10 @@
return false;
}
+ void release() {
+ mHandler.post(mGestureNavigationSettingsObserver::unregister);
+ }
+
@VisibleForTesting
static boolean isOverlappingWithNavBar(WindowState targetWindow, WindowState navBarWindow) {
if (navBarWindow == null || !navBarWindow.isVisibleLw()
diff --git a/services/core/java/com/android/server/wm/EmbeddedWindowController.java b/services/core/java/com/android/server/wm/EmbeddedWindowController.java
index 884f769..484a5a8 100644
--- a/services/core/java/com/android/server/wm/EmbeddedWindowController.java
+++ b/services/core/java/com/android/server/wm/EmbeddedWindowController.java
@@ -17,11 +17,15 @@
package com.android.server.wm;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
import android.annotation.Nullable;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
import android.util.ArrayMap;
+import android.util.Slog;
import android.view.IWindow;
import android.view.InputApplicationHandle;
@@ -33,12 +37,15 @@
* the host window to send pointerDownOutsideFocus.
*/
class EmbeddedWindowController {
+ private static final String TAG = TAG_WITH_CLASS_NAME ? "EmbeddedWindowController" : TAG_WM;
/* maps input token to an embedded window */
private ArrayMap<IBinder /*input token */, EmbeddedWindow> mWindows = new ArrayMap<>();
- private final Object mWmLock;
+ private final Object mGlobalLock;
+ private final ActivityTaskManagerService mAtmService;
- EmbeddedWindowController(Object wmLock) {
- mWmLock = wmLock;
+ EmbeddedWindowController(ActivityTaskManagerService atmService) {
+ mAtmService = atmService;
+ mGlobalLock = atmService.getGlobalLock();
}
/**
@@ -46,13 +53,14 @@
*
* @param inputToken input channel token passed in by the embedding process when it requests
* the server to add an input channel to the embedded surface.
- * @param embeddedWindow An {@link EmbeddedWindow} object to add to this controller.
+ * @param window An {@link EmbeddedWindow} object to add to this controller.
*/
- void add(IBinder inputToken, EmbeddedWindow embeddedWindow) {
+ void add(IBinder inputToken, EmbeddedWindow window) {
try {
- mWindows.put(inputToken, embeddedWindow);
- embeddedWindow.mClient.asBinder().linkToDeath(()-> {
- synchronized (mWmLock) {
+ mWindows.put(inputToken, window);
+ updateProcessController(window);
+ window.mClient.asBinder().linkToDeath(()-> {
+ synchronized (mGlobalLock) {
mWindows.remove(inputToken);
}
}, 0);
@@ -62,6 +70,23 @@
}
}
+ /**
+ * Track the host activity in the embedding process so we can determine if the
+ * process is currently showing any UI to the user.
+ */
+ private void updateProcessController(EmbeddedWindow window) {
+ if (window.mHostActivityRecord == null) {
+ return;
+ }
+ final WindowProcessController processController =
+ mAtmService.getProcessController(window.mOwnerPid, window.mOwnerUid);
+ if (processController == null) {
+ Slog.w(TAG, "Could not find the embedding process.");
+ } else {
+ processController.addHostActivity(window.mHostActivityRecord);
+ }
+ }
+
WindowState getHostWindow(IBinder inputToken) {
EmbeddedWindow embeddedWindow = mWindows.get(inputToken);
return embeddedWindow != null ? embeddedWindow.mHostWindowState : null;
@@ -76,7 +101,7 @@
}
}
- void removeWindowsWithHost(WindowState host) {
+ void onWindowRemoved(WindowState host) {
for (int i = mWindows.size() - 1; i >= 0; i--) {
if (mWindows.valueAt(i).mHostWindowState == host) {
mWindows.removeAt(i);
@@ -88,9 +113,23 @@
return mWindows.get(inputToken);
}
+ void onActivityRemoved(ActivityRecord activityRecord) {
+ for (int i = mWindows.size() - 1; i >= 0; i--) {
+ final EmbeddedWindow window = mWindows.valueAt(i);
+ if (window.mHostActivityRecord == activityRecord) {
+ final WindowProcessController processController =
+ mAtmService.getProcessController(window.mOwnerPid, window.mOwnerUid);
+ if (processController != null) {
+ processController.removeHostActivity(activityRecord);
+ }
+ }
+ }
+ }
+
static class EmbeddedWindow {
final IWindow mClient;
@Nullable final WindowState mHostWindowState;
+ @Nullable final ActivityRecord mHostActivityRecord;
final int mOwnerUid;
final int mOwnerPid;
@@ -107,6 +146,8 @@
int ownerPid) {
mClient = clientToken;
mHostWindowState = hostWindowState;
+ mHostActivityRecord = (mHostWindowState != null) ? mHostWindowState.mActivityRecord
+ : null;
mOwnerUid = ownerUid;
mOwnerPid = ownerPid;
}
diff --git a/services/core/java/com/android/server/wm/InsetsPolicy.java b/services/core/java/com/android/server/wm/InsetsPolicy.java
index 01f9888..30912e5 100644
--- a/services/core/java/com/android/server/wm/InsetsPolicy.java
+++ b/services/core/java/com/android/server/wm/InsetsPolicy.java
@@ -36,6 +36,7 @@
import android.util.SparseArray;
import android.view.InsetsAnimationControlCallbacks;
import android.view.InsetsAnimationControlImpl;
+import android.view.InsetsAnimationControlRunner;
import android.view.InsetsController;
import android.view.InsetsSourceControl;
import android.view.InsetsState;
@@ -44,6 +45,7 @@
import android.view.SyncRtSurfaceTransactionApplier;
import android.view.ViewRootImpl;
import android.view.WindowInsetsAnimation;
+import android.view.WindowInsetsAnimation.Bounds;
import android.view.WindowInsetsAnimationControlListener;
import com.android.internal.annotations.VisibleForTesting;
@@ -327,7 +329,7 @@
InsetsPolicyAnimationControlCallbacks mControlCallbacks;
InsetsPolicyAnimationControlListener(boolean show, Runnable finishCallback) {
- super(show);
+ super(show, true /* useSfVsync */);
mFinishCallback = finishCallback;
mControlCallbacks = new InsetsPolicyAnimationControlCallbacks(this);
}
@@ -360,8 +362,6 @@
mFocusedWin.getDisplayContent().getBounds(), getState(),
mListener, typesReady, this, mListener.getDurationMs(),
InsetsController.INTERPOLATOR, true,
- show ? LAYOUT_INSETS_DURING_ANIMATION_SHOWN
- : LAYOUT_INSETS_DURING_ANIMATION_HIDDEN,
show ? ANIMATION_TYPE_SHOW : ANIMATION_TYPE_HIDE);
SurfaceAnimationThread.getHandler().post(
() -> mListener.onReady(mAnimationControl, typesReady));
@@ -377,7 +377,7 @@
}
@Override
- public void notifyFinished(InsetsAnimationControlImpl controller, boolean shown) {
+ public void notifyFinished(InsetsAnimationControlRunner runner, boolean shown) {
// Nothing's needed here. Finish steps is handled in the listener
// onAnimationFinished callback.
}
@@ -406,14 +406,21 @@
applyParams(t, surfaceParams, mTmpFloat9);
}
t.apply();
+ t.close();
+ }
+
+ // Since we don't push applySurfaceParams to a Handler-queue we don't need
+ // to push release in this case.
+ @Override
+ public void releaseSurfaceControlFromRt(SurfaceControl sc) {
+ sc.release();
}
@Override
public void startAnimation(InsetsAnimationControlImpl controller,
WindowInsetsAnimationControlListener listener, int types,
WindowInsetsAnimation animation,
- WindowInsetsAnimation.Bounds bounds,
- int layoutDuringAnimation) {
+ Bounds bounds) {
}
}
}
diff --git a/services/core/java/com/android/server/wm/InsetsSourceProvider.java b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
index 58aefdc..ada6d47 100644
--- a/services/core/java/com/android/server/wm/InsetsSourceProvider.java
+++ b/services/core/java/com/android/server/wm/InsetsSourceProvider.java
@@ -274,7 +274,7 @@
// window crop of the surface controls (including the leash) until the client finishes
// drawing the new frame of the new orientation. Although we cannot defer the reparent
// operation, it is fine, because reparent won't cause any visual effect.
- final SurfaceControl barrier = mWin.getDeferTransactionBarrier();
+ final SurfaceControl barrier = mWin.getClientViewRootSurface();
t.deferTransactionUntil(mWin.getSurfaceControl(), barrier, frameNumber);
t.deferTransactionUntil(leash, barrier, frameNumber);
}
diff --git a/services/core/java/com/android/server/wm/InsetsStateController.java b/services/core/java/com/android/server/wm/InsetsStateController.java
index e1906da..ee36db9 100644
--- a/services/core/java/com/android/server/wm/InsetsStateController.java
+++ b/services/core/java/com/android/server/wm/InsetsStateController.java
@@ -16,15 +16,22 @@
package com.android.server.wm;
+import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
import static android.view.InsetsState.ITYPE_CAPTION_BAR;
import static android.view.InsetsState.ITYPE_IME;
+import static android.view.InsetsState.ITYPE_INVALID;
import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
import static android.view.InsetsState.ITYPE_STATUS_BAR;
import static android.view.ViewRootImpl.NEW_INSETS_MODE_FULL;
import static android.view.ViewRootImpl.sNewInsetsMode;
+import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
+import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
+import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.app.WindowConfiguration;
+import android.app.WindowConfiguration.WindowingMode;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.SparseArray;
@@ -32,6 +39,7 @@
import android.view.InsetsSourceControl;
import android.view.InsetsState;
import android.view.InsetsState.InternalInsetsType;
+import android.view.WindowManager;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -69,47 +77,82 @@
/**
* When dispatching window state to the client, we'll need to exclude the source that represents
- * the window that is being dispatched.
+ * the window that is being dispatched. We also need to exclude certain types of insets source
+ * for client within specific windowing modes.
*
* @param target The client we dispatch the state to.
* @return The state stripped of the necessary information.
*/
- InsetsState getInsetsForDispatch(WindowState target) {
+ InsetsState getInsetsForDispatch(@NonNull WindowState target) {
final InsetsSourceProvider provider = target.getControllableInsetProvider();
- if (provider == null) {
- return mState;
+ final @InternalInsetsType int type = provider != null
+ ? provider.getSource().getType() : ITYPE_INVALID;
+ return getInsetsForTypeAndWindowingMode(type, target.getWindowingMode());
+ }
+
+ InsetsState getInsetsForWindowMetrics(@NonNull WindowManager.LayoutParams attrs) {
+ final @InternalInsetsType int type = getInsetsTypeForWindowType(attrs.type);
+ final WindowToken token = mDisplayContent.getWindowToken(attrs.token);
+ final @WindowingMode int windowingMode = token != null
+ ? token.getWindowingMode() : WINDOWING_MODE_UNDEFINED;
+ return getInsetsForTypeAndWindowingMode(type, windowingMode);
+ }
+
+ private static @InternalInsetsType int getInsetsTypeForWindowType(int type) {
+ switch(type) {
+ case TYPE_STATUS_BAR:
+ return ITYPE_STATUS_BAR;
+ case TYPE_NAVIGATION_BAR:
+ return ITYPE_NAVIGATION_BAR;
+ case TYPE_INPUT_METHOD:
+ return ITYPE_IME;
+ default:
+ return ITYPE_INVALID;
}
+ }
- final InsetsState state = new InsetsState();
- state.set(mState);
- final int type = provider.getSource().getType();
- state.removeSource(type);
+ /** @see #getInsetsForDispatch */
+ private InsetsState getInsetsForTypeAndWindowingMode(@InternalInsetsType int type,
+ @WindowingMode int windowingMode) {
+ InsetsState state = mState;
- // Navigation bar doesn't get influenced by anything else
- if (type == ITYPE_NAVIGATION_BAR) {
- state.removeSource(ITYPE_IME);
- state.removeSource(ITYPE_STATUS_BAR);
- state.removeSource(ITYPE_CAPTION_BAR);
- }
+ if (type != ITYPE_INVALID) {
+ state = new InsetsState(state);
+ state.removeSource(type);
- // Status bar doesn't get influenced by caption bar
- if (type == ITYPE_STATUS_BAR) {
- state.removeSource(ITYPE_CAPTION_BAR);
- }
+ // Navigation bar doesn't get influenced by anything else
+ if (type == ITYPE_NAVIGATION_BAR) {
+ state.removeSource(ITYPE_IME);
+ state.removeSource(ITYPE_STATUS_BAR);
+ state.removeSource(ITYPE_CAPTION_BAR);
+ }
- // IME needs different frames for certain cases (e.g. navigation bar in gesture nav).
- if (type == ITYPE_IME) {
- for (int i = mProviders.size() - 1; i >= 0; i--) {
- InsetsSourceProvider otherProvider = mProviders.valueAt(i);
- if (otherProvider.overridesImeFrame()) {
- InsetsSource override =
- new InsetsSource(state.getSource(otherProvider.getSource().getType()));
- override.setFrame(otherProvider.getImeOverrideFrame());
- state.addSource(override);
+ // Status bar doesn't get influenced by caption bar
+ if (type == ITYPE_STATUS_BAR) {
+ state.removeSource(ITYPE_CAPTION_BAR);
+ }
+
+ // IME needs different frames for certain cases (e.g. navigation bar in gesture nav).
+ if (type == ITYPE_IME) {
+ for (int i = mProviders.size() - 1; i >= 0; i--) {
+ InsetsSourceProvider otherProvider = mProviders.valueAt(i);
+ if (otherProvider.overridesImeFrame()) {
+ InsetsSource override =
+ new InsetsSource(
+ state.getSource(otherProvider.getSource().getType()));
+ override.setFrame(otherProvider.getImeOverrideFrame());
+ state.addSource(override);
+ }
}
}
}
+ if (WindowConfiguration.isFloating(windowingMode)) {
+ state = new InsetsState(state);
+ state.removeSource(ITYPE_STATUS_BAR);
+ state.removeSource(ITYPE_NAVIGATION_BAR);
+ }
+
return state;
}
diff --git a/services/core/java/com/android/server/wm/LaunchParamsPersister.java b/services/core/java/com/android/server/wm/LaunchParamsPersister.java
index 660706e..9371c0e 100644
--- a/services/core/java/com/android/server/wm/LaunchParamsPersister.java
+++ b/services/core/java/com/android/server/wm/LaunchParamsPersister.java
@@ -16,7 +16,9 @@
package com.android.server.wm;
+import android.annotation.Nullable;
import android.content.ComponentName;
+import android.content.pm.ActivityInfo;
import android.content.pm.PackageManagerInternal;
import android.graphics.Rect;
import android.os.Environment;
@@ -87,9 +89,17 @@
* launching activity of tasks) to {@link PersistableLaunchParams} that stores launch metadata
* that are stable across reboots.
*/
- private final SparseArray<ArrayMap<ComponentName, PersistableLaunchParams>> mMap =
+ private final SparseArray<ArrayMap<ComponentName, PersistableLaunchParams>> mLaunchParamsMap =
new SparseArray<>();
+ /**
+ * A map from {@link android.content.pm.ActivityInfo.WindowLayout#windowLayoutAffinity} to
+ * activity's component name for reverse queries from window layout affinities to activities.
+ * Used to decide if we should use another activity's record with the same affinity.
+ */
+ private final ArrayMap<String, ArraySet<ComponentName>> mWindowLayoutAffinityMap =
+ new ArrayMap<>();
+
LaunchParamsPersister(PersisterQueue persisterQueue, ActivityStackSupervisor supervisor) {
this(persisterQueue, supervisor, Environment::getDataSystemCeDirectory);
}
@@ -112,7 +122,7 @@
}
void onCleanupUser(int userId) {
- mMap.remove(userId);
+ mLaunchParamsMap.remove(userId);
}
private void loadLaunchParams(int userId) {
@@ -128,7 +138,7 @@
final File[] paramsFiles = launchParamsFolder.listFiles();
final ArrayMap<ComponentName, PersistableLaunchParams> map =
new ArrayMap<>(paramsFiles.length);
- mMap.put(userId, map);
+ mLaunchParamsMap.put(userId, map);
for (File paramsFile : paramsFiles) {
if (!paramsFile.isFile()) {
@@ -179,10 +189,12 @@
continue;
}
- params.restoreFromXml(parser);
+ params.restore(paramsFile, parser);
}
map.put(name, params);
+ addComponentNameToLaunchParamAffinityMapIfNotNull(
+ name, params.mWindowLayoutAffinity);
} catch (Exception e) {
Slog.w(TAG, "Failed to restore launch params for " + name, e);
filesToDelete.add(paramsFile);
@@ -204,19 +216,17 @@
final ComponentName name = task.realActivity;
final int userId = task.mUserId;
PersistableLaunchParams params;
- ArrayMap<ComponentName, PersistableLaunchParams> map = mMap.get(userId);
+ ArrayMap<ComponentName, PersistableLaunchParams> map = mLaunchParamsMap.get(userId);
if (map == null) {
map = new ArrayMap<>();
- mMap.put(userId, map);
+ mLaunchParamsMap.put(userId, map);
}
- params = map.get(name);
- if (params == null) {
- params = new PersistableLaunchParams();
- map.put(name, params);
- }
+ params = map.computeIfAbsent(name, componentName -> new PersistableLaunchParams());
final boolean changed = saveTaskToLaunchParam(task, display, params);
+ addComponentNameToLaunchParamAffinityMapIfNotNull(name, params.mWindowLayoutAffinity);
+
if (changed) {
mPersisterQueue.updateLastOrAddItem(
new LaunchParamsWriteQueueItem(userId, name, params),
@@ -243,19 +253,63 @@
params.mBounds.setEmpty();
}
+ String launchParamAffinity = task.mWindowLayoutAffinity;
+ changed |= Objects.equals(launchParamAffinity, params.mWindowLayoutAffinity);
+ params.mWindowLayoutAffinity = launchParamAffinity;
+
+ if (changed) {
+ params.mTimestamp = System.currentTimeMillis();
+ }
+
return changed;
}
+ private void addComponentNameToLaunchParamAffinityMapIfNotNull(
+ ComponentName name, String launchParamAffinity) {
+ if (launchParamAffinity == null) {
+ return;
+ }
+ mWindowLayoutAffinityMap.computeIfAbsent(launchParamAffinity, affinity -> new ArraySet<>())
+ .add(name);
+ }
+
void getLaunchParams(Task task, ActivityRecord activity, LaunchParams outParams) {
final ComponentName name = task != null ? task.realActivity : activity.mActivityComponent;
final int userId = task != null ? task.mUserId : activity.mUserId;
+ final String windowLayoutAffinity;
+ if (task != null) {
+ windowLayoutAffinity = task.mWindowLayoutAffinity;
+ } else {
+ ActivityInfo.WindowLayout layout = activity.info.windowLayout;
+ windowLayoutAffinity = layout == null ? null : layout.windowLayoutAffinity;
+ }
outParams.reset();
- Map<ComponentName, PersistableLaunchParams> map = mMap.get(userId);
+ Map<ComponentName, PersistableLaunchParams> map = mLaunchParamsMap.get(userId);
if (map == null) {
return;
}
- final PersistableLaunchParams persistableParams = map.get(name);
+
+ // First use its own record as a reference.
+ PersistableLaunchParams persistableParams = map.get(name);
+ // Next we'll compare these params against all existing params with the same affinity and
+ // use the newest one.
+ if (windowLayoutAffinity != null
+ && mWindowLayoutAffinityMap.get(windowLayoutAffinity) != null) {
+ ArraySet<ComponentName> candidates = mWindowLayoutAffinityMap.get(windowLayoutAffinity);
+ for (int i = 0; i < candidates.size(); ++i) {
+ ComponentName candidate = candidates.valueAt(i);
+ final PersistableLaunchParams candidateParams = map.get(candidate);
+ if (candidateParams == null) {
+ continue;
+ }
+
+ if (persistableParams == null
+ || candidateParams.mTimestamp > persistableParams.mTimestamp) {
+ persistableParams = candidateParams;
+ }
+ }
+ }
if (persistableParams == null) {
return;
@@ -272,10 +326,10 @@
void removeRecordForPackage(String packageName) {
final List<File> fileToDelete = new ArrayList<>();
- for (int i = 0; i < mMap.size(); ++i) {
- int userId = mMap.keyAt(i);
+ for (int i = 0; i < mLaunchParamsMap.size(); ++i) {
+ int userId = mLaunchParamsMap.keyAt(i);
final File launchParamsFolder = getLaunchParamFolder(userId);
- ArrayMap<ComponentName, PersistableLaunchParams> map = mMap.valueAt(i);
+ ArrayMap<ComponentName, PersistableLaunchParams> map = mLaunchParamsMap.valueAt(i);
for (int j = map.size() - 1; j >= 0; --j) {
final ComponentName name = map.keyAt(j);
if (name.getPackageName().equals(packageName)) {
@@ -409,6 +463,7 @@
private static final String ATTR_WINDOWING_MODE = "windowing_mode";
private static final String ATTR_DISPLAY_UNIQUE_ID = "display_unique_id";
private static final String ATTR_BOUNDS = "bounds";
+ private static final String ATTR_WINDOW_LAYOUT_AFFINITY = "window_layout_affinity";
/** The bounds within the parent container. */
final Rect mBounds = new Rect();
@@ -419,14 +474,29 @@
/** The windowing mode to be in. */
int mWindowingMode;
+ /**
+ * Last {@link android.content.pm.ActivityInfo.WindowLayout#windowLayoutAffinity} of the
+ * window.
+ */
+ @Nullable String mWindowLayoutAffinity;
+
+ /**
+ * Timestamp from {@link System#currentTimeMillis()} when this record is captured, or last
+ * modified time when the record is restored from storage.
+ */
+ long mTimestamp;
+
void saveToXml(XmlSerializer serializer) throws IOException {
serializer.attribute(null, ATTR_DISPLAY_UNIQUE_ID, mDisplayUniqueId);
serializer.attribute(null, ATTR_WINDOWING_MODE,
Integer.toString(mWindowingMode));
serializer.attribute(null, ATTR_BOUNDS, mBounds.flattenToString());
+ if (mWindowLayoutAffinity != null) {
+ serializer.attribute(null, ATTR_WINDOW_LAYOUT_AFFINITY, mWindowLayoutAffinity);
+ }
}
- void restoreFromXml(XmlPullParser parser) {
+ void restore(File xmlFile, XmlPullParser parser) {
for (int i = 0; i < parser.getAttributeCount(); ++i) {
final String attrValue = parser.getAttributeValue(i);
switch (parser.getAttributeName(i)) {
@@ -443,16 +513,28 @@
}
break;
}
+ case ATTR_WINDOW_LAYOUT_AFFINITY:
+ mWindowLayoutAffinity = attrValue;
+ break;
}
}
+
+ // The modified time could be a few seconds later than the timestamp when the record is
+ // captured, which is a good enough estimate to the capture time after a reboot or a
+ // user switch.
+ mTimestamp = xmlFile.lastModified();
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("PersistableLaunchParams{");
- builder.append("windowingMode=" + mWindowingMode);
+ builder.append(" windowingMode=" + mWindowingMode);
builder.append(" displayUniqueId=" + mDisplayUniqueId);
builder.append(" bounds=" + mBounds);
+ if (mWindowLayoutAffinity != null) {
+ builder.append(" launchParamsAffinity=" + mWindowLayoutAffinity);
+ }
+ builder.append(" timestamp=" + mTimestamp);
builder.append(" }");
return builder.toString();
}
diff --git a/services/core/java/com/android/server/wm/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java
index fc358ce..bd5666d 100644
--- a/services/core/java/com/android/server/wm/RecentTasks.java
+++ b/services/core/java/com/android/server/wm/RecentTasks.java
@@ -846,10 +846,9 @@
@VisibleForTesting
Set<Integer> getProfileIds(int userId) {
Set<Integer> userIds = new ArraySet<>();
- final List<UserInfo> profiles = mService.getUserManager().getProfiles(userId,
- false /* enabledOnly */);
- for (int i = profiles.size() - 1; i >= 0; --i) {
- userIds.add(profiles.get(i).id);
+ int[] profileIds = mService.getUserManager().getProfileIds(userId, false /* enabledOnly */);
+ for (int i = 0; i < profileIds.length; i++) {
+ userIds.add(Integer.valueOf(profileIds[i]));
}
return userIds;
}
diff --git a/services/core/java/com/android/server/wm/RecentsAnimationController.java b/services/core/java/com/android/server/wm/RecentsAnimationController.java
index 5cd0169..3e5cb50 100644
--- a/services/core/java/com/android/server/wm/RecentsAnimationController.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimationController.java
@@ -820,15 +820,19 @@
private @AnimationType int mLastAnimationType;
private final boolean mIsRecentTaskInvisible;
private RemoteAnimationTarget mTarget;
- private final Point mPosition = new Point();
private final Rect mBounds = new Rect();
+ // The bounds of the target relative to its parent.
+ private Rect mLocalBounds = new Rect();
TaskAnimationAdapter(Task task, boolean isRecentTaskInvisible) {
mTask = task;
mIsRecentTaskInvisible = isRecentTaskInvisible;
- final WindowContainer container = mTask.getParent();
- mBounds.set(container.getDisplayedBounds());
- mPosition.set(mBounds.left, mBounds.top);
+ mBounds.set(mTask.getDisplayedBounds());
+
+ mLocalBounds.set(mBounds);
+ Point tmpPos = new Point();
+ mTask.getRelativeDisplayedPosition(tmpPos);
+ mLocalBounds.offsetTo(tmpPos.x, tmpPos.y);
}
RemoteAnimationTarget createRemoteAnimationTarget() {
@@ -847,8 +851,9 @@
: MODE_CLOSING;
mTarget = new RemoteAnimationTarget(mTask.mTaskId, mode, mCapturedLeash,
!topApp.fillsParent(), mainWindow.mWinAnimator.mLastClipRect,
- insets, mTask.getPrefixOrderIndex(), mPosition, mBounds,
- mTask.getWindowConfiguration(), mIsRecentTaskInvisible, null, null);
+ insets, mTask.getPrefixOrderIndex(), new Point(mBounds.left, mBounds.top),
+ mLocalBounds, mBounds, mTask.getWindowConfiguration(),
+ mIsRecentTaskInvisible, null, null);
return mTarget;
}
@@ -862,8 +867,8 @@
@AnimationType int type, OnAnimationFinishedCallback finishCallback) {
// Restore z-layering, position and stack crop until client has a chance to modify it.
t.setLayer(animationLeash, mTask.getPrefixOrderIndex());
- t.setPosition(animationLeash, mPosition.x, mPosition.y);
- mTmpRect.set(mBounds);
+ t.setPosition(animationLeash, mLocalBounds.left, mLocalBounds.top);
+ mTmpRect.set(mLocalBounds);
mTmpRect.offsetTo(0, 0);
t.setWindowCrop(animationLeash, mTmpRect);
mCapturedLeash = animationLeash;
@@ -897,7 +902,7 @@
pw.print(prefix); pw.println("Target: null");
}
pw.println("mIsRecentTaskInvisible=" + mIsRecentTaskInvisible);
- pw.println("mPosition=" + mPosition);
+ pw.println("mLocalBounds=" + mLocalBounds);
pw.println("mBounds=" + mBounds);
pw.println("mIsRecentTaskInvisible=" + mIsRecentTaskInvisible);
}
diff --git a/services/core/java/com/android/server/wm/RemoteAnimationController.java b/services/core/java/com/android/server/wm/RemoteAnimationController.java
index 0eb9daf..35f8d34 100644
--- a/services/core/java/com/android/server/wm/RemoteAnimationController.java
+++ b/services/core/java/com/android/server/wm/RemoteAnimationController.java
@@ -80,16 +80,17 @@
*
* @param windowContainer The windows to animate.
* @param position The position app bounds, in screen coordinates.
+ * @param localBounds The bounds of the app relative to its parent.
* @param stackBounds The stack bounds of the app relative to position.
* @param startBounds The stack bounds before the transition, in screen coordinates
* @return The record representing animation(s) to run on the app.
*/
RemoteAnimationRecord createRemoteAnimationRecord(WindowContainer windowContainer,
- Point position, Rect stackBounds, Rect startBounds) {
+ Point position, Rect localBounds, Rect stackBounds, Rect startBounds) {
ProtoLog.d(WM_DEBUG_REMOTE_ANIMATIONS, "createAnimationAdapter(): container=%s",
windowContainer);
- final RemoteAnimationRecord adapters =
- new RemoteAnimationRecord(windowContainer, position, stackBounds, startBounds);
+ final RemoteAnimationRecord adapters = new RemoteAnimationRecord(windowContainer, position,
+ localBounds, stackBounds, startBounds);
mPendingAnimations.add(adapters);
return adapters;
}
@@ -355,17 +356,18 @@
final WindowContainer mWindowContainer;
final Rect mStartBounds;
- RemoteAnimationRecord(WindowContainer windowContainer, Point endPos, Rect endBounds,
- Rect startBounds) {
+ RemoteAnimationRecord(WindowContainer windowContainer, Point endPos, Rect localBounds,
+ Rect endBounds, Rect startBounds) {
mWindowContainer = windowContainer;
- mAdapter = new RemoteAnimationAdapterWrapper(this, endPos, endBounds);
+ mAdapter = new RemoteAnimationAdapterWrapper(this, endPos, localBounds, endBounds);
if (startBounds != null) {
mStartBounds = new Rect(startBounds);
mTmpRect.set(startBounds);
mTmpRect.offsetTo(0, 0);
if (mRemoteAnimationAdapter.getChangeNeedsSnapshot()) {
mThumbnailAdapter =
- new RemoteAnimationAdapterWrapper(this, new Point(0, 0), mTmpRect);
+ new RemoteAnimationAdapterWrapper(this, new Point(0, 0), localBounds,
+ mTmpRect);
}
} else {
mStartBounds = null;
@@ -401,12 +403,14 @@
private OnAnimationFinishedCallback mCapturedFinishCallback;
private @AnimationType int mAnimationType;
final Point mPosition = new Point();
+ final Rect mLocalBounds;
final Rect mStackBounds = new Rect();
RemoteAnimationAdapterWrapper(RemoteAnimationRecord record, Point position,
- Rect stackBounds) {
+ Rect localBounds, Rect stackBounds) {
mRecord = record;
mPosition.set(position.x, position.y);
+ mLocalBounds = localBounds;
mStackBounds.set(stackBounds);
}
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index ada5685..ebf1bc9 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -66,11 +66,9 @@
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
import static com.android.server.wm.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC;
import static com.android.server.wm.ProtoLogGroup.WM_SHOW_TRANSACTIONS;
-import static com.android.server.wm.RootWindowContainerProto.DISPLAYS;
import static com.android.server.wm.RootWindowContainerProto.IS_HOME_RECENTS_COMPONENT;
import static com.android.server.wm.RootWindowContainerProto.KEYGUARD_CONTROLLER;
import static com.android.server.wm.RootWindowContainerProto.PENDING_ACTIVITIES;
-import static com.android.server.wm.RootWindowContainerProto.WINDOWS;
import static com.android.server.wm.RootWindowContainerProto.WINDOW_CONTAINER;
import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
import static com.android.server.wm.Task.REPARENT_MOVE_STACK_TO_FRONT;
@@ -1278,18 +1276,6 @@
final long token = proto.start(fieldId);
super.dumpDebug(proto, WINDOW_CONTAINER, logLevel);
- if (mWmService.mDisplayReady) {
- final int count = mChildren.size();
- for (int i = 0; i < count; ++i) {
- final DisplayContent displayContent = mChildren.get(i);
- displayContent.dumpDebug(proto, DISPLAYS, logLevel);
- }
- }
- if (logLevel == WindowTraceLogLevel.ALL) {
- forAllWindows((w) -> {
- w.dumpDebug(proto, WINDOWS, logLevel);
- }, true);
- }
mStackSupervisor.getKeyguardController().dumpDebug(proto, KEYGUARD_CONTROLLER);
proto.write(IS_HOME_RECENTS_COMPONENT,
@@ -1980,7 +1966,9 @@
}
boolean switchUser(int userId, UserState uss) {
- final int focusStackId = getTopDisplayFocusedStack().getRootTaskId();
+ final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
+ final int focusStackId = topFocusedStack != null
+ ? topFocusedStack.getRootTaskId() : INVALID_TASK_ID;
// We dismiss the docked stack whenever we switch users.
final ActivityStack dockedStack = getDefaultDisplay().getRootSplitScreenPrimaryTask();
if (dockedStack != null) {
@@ -2263,8 +2251,8 @@
final ActivityStack focusedStack = display.getFocusedStack();
if (focusedStack != null) {
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
- } else if (targetStack == null && display.getStackCount() == 0) {
- result |= resumeHomeActivity(null /* prev */, "empty-display",
+ } else if (targetStack == null) {
+ result |= resumeHomeActivity(null /* prev */, "no-focusable-task",
display.mDisplayId);
}
}
@@ -2707,7 +2695,9 @@
return true;
}
} else {
- if (r.intent.getComponent().equals(cls)) {
+ // Compare the target component instead of intent component so we don't miss if the
+ // activity uses alias.
+ if (r.mActivityComponent.equals(cls)) {
return true;
}
}
@@ -3455,7 +3445,12 @@
ArrayList<ActivityRecord> getDumpActivities(String name, boolean dumpVisibleStacksOnly,
boolean dumpFocusedStackOnly) {
if (dumpFocusedStackOnly) {
- return getTopDisplayFocusedStack().getDumpActivitiesLocked(name);
+ final ActivityStack topFocusedStack = getTopDisplayFocusedStack();
+ if (topFocusedStack != null) {
+ return topFocusedStack.getDumpActivitiesLocked(name);
+ } else {
+ return new ArrayList<>();
+ }
} else {
ArrayList<ActivityRecord> activities = new ArrayList<>();
int numDisplays = getChildCount();
diff --git a/services/core/java/com/android/server/wm/SeamlessRotator.java b/services/core/java/com/android/server/wm/SeamlessRotator.java
index 024da88..8e1c632 100644
--- a/services/core/java/com/android/server/wm/SeamlessRotator.java
+++ b/services/core/java/com/android/server/wm/SeamlessRotator.java
@@ -118,9 +118,9 @@
finish(t, win);
if (win.mWinAnimator.mSurfaceController != null && !timeout) {
t.deferTransactionUntil(win.mSurfaceControl,
- win.getDeferTransactionBarrier(), win.getFrameNumber());
+ win.getClientViewRootSurface(), win.getFrameNumber());
t.deferTransactionUntil(win.mWinAnimator.mSurfaceController.mSurfaceControl,
- win.getDeferTransactionBarrier(), win.getFrameNumber());
+ win.getClientViewRootSurface(), win.getFrameNumber());
}
}
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index 9df4248..5f3732a 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -356,6 +356,31 @@
}
@Override
+ public void setWallpaperZoomOut(IBinder window, float zoom) {
+ if (Float.compare(0f, zoom) > 0 || Float.compare(1f, zoom) < 0 || Float.isNaN(zoom)) {
+ throw new IllegalArgumentException("Zoom must be a valid float between 0 and 1: "
+ + zoom);
+ }
+ synchronized (mService.mGlobalLock) {
+ long ident = Binder.clearCallingIdentity();
+ try {
+ actionOnWallpaper(window, (wpController, windowState) ->
+ wpController.setWallpaperZoomOut(windowState, zoom));
+ } finally {
+ Binder.restoreCallingIdentity(ident);
+ }
+ }
+ }
+
+ @Override
+ public void setShouldZoomOutWallpaper(IBinder window, boolean shouldZoom) {
+ synchronized (mService.mGlobalLock) {
+ actionOnWallpaper(window, (wpController, windowState) ->
+ wpController.setShouldZoomOutWallpaper(windowState, shouldZoom));
+ }
+ }
+
+ @Override
public void wallpaperOffsetsComplete(IBinder window) {
synchronized (mService.mGlobalLock) {
actionOnWallpaper(window, (wpController, windowState) ->
diff --git a/services/core/java/com/android/server/wm/SurfaceFreezer.java b/services/core/java/com/android/server/wm/SurfaceFreezer.java
index 36861aa..a696daf 100644
--- a/services/core/java/com/android/server/wm/SurfaceFreezer.java
+++ b/services/core/java/com/android/server/wm/SurfaceFreezer.java
@@ -103,7 +103,7 @@
*/
void unfreeze(SurfaceControl.Transaction t) {
if (mSnapshot != null) {
- mSnapshot.destroy(t);
+ mSnapshot.cancelAnimation(t, false /* restarting */);
}
if (mLeash == null) {
return;
@@ -212,7 +212,7 @@
* @param t The transaction to use for all cancelling surface operations.
* @param restarting Whether we are restarting the animation.
*/
- private void cancelAnimation(SurfaceControl.Transaction t, boolean restarting) {
+ void cancelAnimation(SurfaceControl.Transaction t, boolean restarting) {
final SurfaceControl leash = mSurfaceControl;
final AnimationAdapter animation = mAnimation;
final SurfaceAnimator.OnAnimationFinishedCallback animationFinishedCallback =
@@ -229,7 +229,6 @@
}
}
if (!restarting) {
- // TODO: do we need to destroy?
destroy(t);
}
}
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 88d4fb3..e78f2ee 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -85,6 +85,7 @@
import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
+import static com.android.server.wm.WindowContainerChildProto.TASK;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_MOVEMENT;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
@@ -198,6 +199,7 @@
private static final String ATTR_MIN_WIDTH = "min_width";
private static final String ATTR_MIN_HEIGHT = "min_height";
private static final String ATTR_PERSIST_TASK_VERSION = "persist_task_version";
+ private static final String ATTR_WINDOW_LAYOUT_AFFINITY = "window_layout_affinity";
// Current version of the task record we persist. Used to check if we need to run any upgrade
// code.
@@ -232,6 +234,8 @@
String affinity; // The affinity name for this task, or null; may change identity.
String rootAffinity; // Initial base affinity, or null; does not change from initial root.
+ String mWindowLayoutAffinity; // Launch param affinity of this task or null. Used when saving
+ // launch params of this task.
IVoiceInteractionSession voiceSession; // Voice interaction session driving task
IVoiceInteractor voiceInteractor; // Associated interactor to provide to app
Intent intent; // The original intent that started the task. Note that this value can
@@ -473,6 +477,7 @@
* taskAppeared callback, and emit a taskRemoved callback when the Task is vanished.
*/
ITaskOrganizer mTaskOrganizer;
+ private int mLastTaskOrganizerWindowingMode = -1;
/**
* Last Picture-in-Picture params applicable to the task. Updated when the app
@@ -999,6 +1004,8 @@
origActivity = new ComponentName(info.packageName, info.name);
}
}
+ mWindowLayoutAffinity =
+ info.windowLayout == null ? null : info.windowLayout.windowLayoutAffinity;
final int intentFlags = intent == null ? 0 : intent.getFlags();
if ((intentFlags & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
@@ -1928,6 +1935,7 @@
// TODO: Should also take care of Pip mode changes here.
saveLaunchingStateIfNeeded();
+ updateTaskOrganizerState(false /* forceUpdate */);
}
/**
@@ -2119,14 +2127,26 @@
intersectWithInsetsIfFits(outStableBounds, mTmpBounds, mTmpInsets);
}
+ /**
+ * Forces the app bounds related configuration can be computed by
+ * {@link #computeConfigResourceOverrides(Configuration, Configuration, DisplayInfo,
+ * ActivityRecord.CompatDisplayInsets)}.
+ */
+ private static void invalidateAppBoundsConfig(@NonNull Configuration inOutConfig) {
+ final Rect appBounds = inOutConfig.windowConfiguration.getAppBounds();
+ if (appBounds != null) {
+ appBounds.setEmpty();
+ }
+ inOutConfig.screenWidthDp = Configuration.SCREEN_WIDTH_DP_UNDEFINED;
+ inOutConfig.screenHeightDp = Configuration.SCREEN_HEIGHT_DP_UNDEFINED;
+ }
+
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
@NonNull Configuration parentConfig, @Nullable DisplayInfo overrideDisplayInfo) {
if (overrideDisplayInfo != null) {
// Make sure the screen related configs can be computed by the provided display info.
- inOutConfig.windowConfiguration.setAppBounds(null);
inOutConfig.screenLayout = Configuration.SCREENLAYOUT_UNDEFINED;
- inOutConfig.screenWidthDp = Configuration.SCREEN_WIDTH_DP_UNDEFINED;
- inOutConfig.screenHeightDp = Configuration.SCREEN_HEIGHT_DP_UNDEFINED;
+ invalidateAppBoundsConfig(inOutConfig);
}
computeConfigResourceOverrides(inOutConfig, parentConfig, overrideDisplayInfo,
null /* compatInsets */);
@@ -2141,6 +2161,10 @@
void computeConfigResourceOverrides(@NonNull Configuration inOutConfig,
@NonNull Configuration parentConfig,
@Nullable ActivityRecord.CompatDisplayInsets compatInsets) {
+ if (compatInsets != null) {
+ // Make sure the app bounds can be computed by the compat insets.
+ invalidateAppBoundsConfig(inOutConfig);
+ }
computeConfigResourceOverrides(inOutConfig, parentConfig, null /* overrideDisplayInfo */,
compatInsets);
}
@@ -3362,6 +3386,9 @@
} else {
info.pictureInPictureParams = mPictureInPictureParams;
}
+ info.topActivityInfo = mReuseActivitiesReport.top != null
+ ? mReuseActivitiesReport.top.info
+ : null;
}
/**
@@ -3407,6 +3434,9 @@
pw.println();
}
}
+ if (mWindowLayoutAffinity != null) {
+ pw.print(prefix); pw.print("windowLayoutAffinity="); pw.println(mWindowLayoutAffinity);
+ }
if (voiceSession != null || voiceInteractor != null) {
pw.print(prefix); pw.print("VOICE: session=0x");
pw.print(Integer.toHexString(System.identityHashCode(voiceSession)));
@@ -3588,6 +3618,9 @@
} else if (rootAffinity != null) {
out.attribute(null, ATTR_ROOT_AFFINITY, rootAffinity != null ? rootAffinity : "@");
}
+ if (mWindowLayoutAffinity != null) {
+ out.attribute(null, ATTR_WINDOW_LAYOUT_AFFINITY, mWindowLayoutAffinity);
+ }
out.attribute(null, ATTR_ROOTHASRESET, String.valueOf(rootWasReset));
out.attribute(null, ATTR_AUTOREMOVERECENTS, String.valueOf(autoRemoveRecents));
out.attribute(null, ATTR_ASKEDCOMPATMODE, String.valueOf(askedCompatMode));
@@ -3745,6 +3778,7 @@
String affinity = null;
String rootAffinity = null;
boolean hasRootAffinity = false;
+ String windowLayoutAffinity = null;
boolean rootHasReset = false;
boolean autoRemoveRecents = false;
boolean askedCompatMode = false;
@@ -3797,6 +3831,9 @@
rootAffinity = attrValue;
hasRootAffinity = true;
break;
+ case ATTR_WINDOW_LAYOUT_AFFINITY:
+ windowLayoutAffinity = attrValue;
+ break;
case ATTR_ROOTHASRESET:
rootHasReset = Boolean.parseBoolean(attrValue);
break;
@@ -3952,6 +3989,7 @@
realActivitySuspended, userSetupComplete, minWidth, minHeight, null /*stack*/);
task.mLastNonFullscreenBounds = lastNonFullscreenBounds;
task.setBounds(lastNonFullscreenBounds);
+ task.mWindowLayoutAffinity = windowLayoutAffinity;
for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
task.addChild(activities.get(activityNdx));
@@ -3970,12 +4008,12 @@
boolean isControlledByTaskOrganizer() {
final Task rootTask = getRootTask();
- return rootTask == this && rootTask.mTaskOrganizer != null
- // TODO(task-hierarchy): Figure out how to control nested tasks.
- // For now, if this is in a tile let WM drive.
- && !(rootTask instanceof TaskTile)
- && !(rootTask instanceof ActivityStack
- && ((ActivityStack) rootTask).getTile() != null);
+ // if the rootTask is a "child" of a tile, then don't consider it a root task.
+ // TODO: remove this along with removing tile.
+ if (((ActivityStack) rootTask).getTile() != null) {
+ return false;
+ }
+ return rootTask == this && rootTask.mTaskOrganizer != null;
}
@Override
@@ -4017,6 +4055,39 @@
// Called on Binder death.
void taskOrganizerDied() {
mTaskOrganizer = null;
+ mLastTaskOrganizerWindowingMode = -1;
+ }
+
+ /**
+ * Called when the task state changes (ie. from windowing mode change) an the task organizer
+ * state should also be updated.
+ *
+ * @param forceUpdate Updates the task organizer to the one currently specified in the task
+ * org controller for the task's windowing mode, ignoring the cached
+ * windowing mode checks.
+ */
+ void updateTaskOrganizerState(boolean forceUpdate) {
+ if (!isRootTask()) {
+ return;
+ }
+
+ final int windowingMode = getWindowingMode();
+ if (!forceUpdate && windowingMode == mLastTaskOrganizerWindowingMode) {
+ // If our windowing mode hasn't actually changed, then just stick
+ // with our old organizer. This lets us implement the semantic
+ // where SysUI can continue to manage it's old tasks
+ // while CTS temporarily takes over the registration.
+ return;
+ }
+ /*
+ * Different windowing modes may be managed by different task organizers. If
+ * getTaskOrganizer returns null, we still call setTaskOrganizer to
+ * make sure we clear it.
+ */
+ final ITaskOrganizer org =
+ mWmService.mAtmService.mTaskOrganizerController.getTaskOrganizer(windowingMode);
+ setTaskOrganizer(org);
+ mLastTaskOrganizerWindowingMode = windowingMode;
}
@Override
@@ -4121,4 +4192,17 @@
SurfaceControl.Transaction getMainWindowSizeChangeTransaction() {
return mMainWindowSizeChangeTransaction;
}
+
+ void setActivityWindowingMode(int windowingMode) {
+ PooledConsumer c = PooledLambda.obtainConsumer(ActivityRecord::setWindowingMode,
+ PooledLambda.__(ActivityRecord.class), windowingMode);
+ forAllActivities(c);
+ c.recycle();
+ }
+
+ @Override
+ long getProtoFieldId() {
+ return TASK;
+ }
+
}
diff --git a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
index 96a9127..e4f10d9 100644
--- a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
+++ b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
@@ -30,13 +30,15 @@
import android.os.RemoteCallbackList;
import android.os.RemoteException;
+import com.android.internal.os.SomeArgs;
+
import java.util.ArrayList;
class TaskChangeNotificationController {
private static final int LOG_STACK_STATE_MSG = 1;
private static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG = 2;
private static final int NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG = 3;
- private static final int NOTIFY_PINNED_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG = 4;
+ private static final int NOTIFY_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG = 4;
private static final int NOTIFY_FORCED_RESIZABLE_MSG = 6;
private static final int NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG = 7;
private static final int NOTIFY_TASK_ADDED_LISTENERS_MSG = 8;
@@ -118,8 +120,10 @@
l.onActivityUnpinned();
};
- private final TaskStackConsumer mNotifyPinnedActivityRestartAttempt = (l, m) -> {
- l.onPinnedActivityRestartAttempt(m.arg1 != 0);
+ private final TaskStackConsumer mNotifyActivityRestartAttempt = (l, m) -> {
+ SomeArgs args = (SomeArgs) m.obj;
+ l.onActivityRestartAttempt((RunningTaskInfo) args.arg1, args.argi1 != 0,
+ args.argi2 != 0);
};
private final TaskStackConsumer mNotifyActivityForcedResizable = (l, m) -> {
@@ -220,8 +224,8 @@
case NOTIFY_ACTIVITY_UNPINNED_LISTENERS_MSG:
forAllRemoteListeners(mNotifyActivityUnpinned, msg);
break;
- case NOTIFY_PINNED_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG:
- forAllRemoteListeners(mNotifyPinnedActivityRestartAttempt, msg);
+ case NOTIFY_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG:
+ forAllRemoteListeners(mNotifyActivityRestartAttempt, msg);
break;
case NOTIFY_FORCED_RESIZABLE_MSG:
forAllRemoteListeners(mNotifyActivityForcedResizable, msg);
@@ -266,6 +270,9 @@
forAllRemoteListeners(mNotifyTaskFocusChanged, msg);
break;
}
+ if (msg.obj instanceof SomeArgs) {
+ ((SomeArgs) msg.obj).recycle();
+ }
}
}
@@ -358,15 +365,18 @@
/**
* Notifies all listeners when an attempt was made to start an an activity that is already
- * running in the pinned stack and the activity was not actually started, but the task is
- * either brought to the front or a new Intent is delivered to it.
+ * running, but the task is either brought to the front or a new Intent is delivered to it.
*/
- void notifyPinnedActivityRestartAttempt(boolean clearedTask) {
- mHandler.removeMessages(NOTIFY_PINNED_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG);
- final Message msg =
- mHandler.obtainMessage(NOTIFY_PINNED_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG,
- clearedTask ? 1 : 0, 0);
- forAllLocalListeners(mNotifyPinnedActivityRestartAttempt, msg);
+ void notifyActivityRestartAttempt(RunningTaskInfo task, boolean homeTaskVisible,
+ boolean clearedTask) {
+ mHandler.removeMessages(NOTIFY_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG);
+ final SomeArgs args = SomeArgs.obtain();
+ args.arg1 = task;
+ args.argi1 = homeTaskVisible ? 1 : 0;
+ args.argi2 = clearedTask ? 1 : 0;
+ final Message msg = mHandler.obtainMessage(NOTIFY_ACTIVITY_RESTART_ATTEMPT_LISTENERS_MSG,
+ args);
+ forAllLocalListeners(mNotifyActivityRestartAttempt, msg);
msg.sendToTarget();
}
diff --git a/services/core/java/com/android/server/wm/TaskOrganizerController.java b/services/core/java/com/android/server/wm/TaskOrganizerController.java
index 8f5d048..9cbc9ee 100644
--- a/services/core/java/com/android/server/wm/TaskOrganizerController.java
+++ b/services/core/java/com/android/server/wm/TaskOrganizerController.java
@@ -105,7 +105,7 @@
TaskOrganizerState(ITaskOrganizer organizer, int windowingMode,
- TaskOrganizerState replacing) {
+ @Nullable TaskOrganizerState replacing) {
mOrganizer = organizer;
mDeathRecipient = new DeathRecipient(organizer, windowingMode);
try {
@@ -128,7 +128,7 @@
void removeTask(Task t) {
try {
- mOrganizer.taskVanished(t.getRemoteToken());
+ mOrganizer.taskVanished(t.getTaskInfo());
} catch (Exception e) {
Slog.e(TAG, "Exception sending taskVanished callback" + e);
}
@@ -203,10 +203,27 @@
final long origId = Binder.clearCallingIdentity();
try {
synchronized (mGlobalLock) {
+ if (getTaskOrganizer(windowingMode) != null) {
+ Slog.w(TAG, "Task organizer already exists for windowing mode: "
+ + windowingMode);
+ }
+ final TaskOrganizerState previousState =
+ mTaskOrganizersForWindowingMode.get(windowingMode);
final TaskOrganizerState state = new TaskOrganizerState(organizer, windowingMode,
- mTaskOrganizersForWindowingMode.get(windowingMode));
+ previousState);
mTaskOrganizersForWindowingMode.put(windowingMode, state);
mTaskOrganizerStates.put(organizer.asBinder(), state);
+
+ if (previousState == null) {
+ // Only in the case where this is the root task organizer for the given
+ // windowing mode, we add report all existing tasks in that mode to the new
+ // task organizer.
+ mService.mRootWindowContainer.forAllTasks((task) -> {
+ if (task.getWindowingMode() == windowingMode) {
+ task.updateTaskOrganizerState(true /* forceUpdate */);
+ }
+ });
+ }
}
} finally {
Binder.restoreCallingIdentity(origId);
@@ -463,8 +480,9 @@
int configMask = change.getConfigSetMask();
int windowMask = change.getWindowSetMask();
configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
- | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
- windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
+ | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE | ActivityInfo.CONFIG_SCREEN_SIZE;
+ windowMask &= (WindowConfiguration.WINDOW_CONFIG_BOUNDS
+ | WindowConfiguration.WINDOW_CONFIG_APP_BOUNDS);
int effects = 0;
if (configMask != 0) {
Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
@@ -552,18 +570,28 @@
WindowContainerTransaction.Change c) {
int effects = sanitizeAndApplyChange(wc, c);
+ final Task tr = wc.asTask();
+
final SurfaceControl.Transaction t = c.getBoundsChangeTransaction();
if (t != null) {
- Task tr = (Task) wc;
tr.setMainWindowSizeChangeTransaction(t);
}
Rect enterPipBounds = c.getEnterPipBounds();
if (enterPipBounds != null) {
- Task tr = (Task) wc;
mService.mStackSupervisor.updatePictureInPictureMode(tr,
enterPipBounds, true);
}
+
+ final int windowingMode = c.getWindowingMode();
+ if (windowingMode > -1) {
+ tr.setWindowingMode(windowingMode);
+ }
+ final int childWindowingMode = c.getActivityWindowingMode();
+ if (childWindowingMode > -1) {
+ tr.setActivityWindowingMode(childWindowingMode);
+ }
+
return effects;
}
diff --git a/services/core/java/com/android/server/wm/TaskPositioner.java b/services/core/java/com/android/server/wm/TaskPositioner.java
index b5892b9..f046e8a 100644
--- a/services/core/java/com/android/server/wm/TaskPositioner.java
+++ b/services/core/java/com/android/server/wm/TaskPositioner.java
@@ -35,7 +35,6 @@
import static com.android.server.wm.WindowState.MINIMUM_VISIBLE_WIDTH_IN_DP;
import android.annotation.NonNull;
-import android.app.IActivityTaskManager;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Binder;
@@ -48,7 +47,6 @@
import android.util.Slog;
import android.view.BatchedInputEventReceiver;
import android.view.Choreographer;
-import android.view.Display;
import android.view.InputApplicationHandle;
import android.view.InputChannel;
import android.view.InputDevice;
@@ -75,10 +73,8 @@
public static final int RESIZING_HINT_DURATION_MS = 0;
private final WindowManagerService mService;
- private final IActivityTaskManager mActivityManager;
private WindowPositionerEventReceiver mInputEventReceiver;
private DisplayContent mDisplayContent;
- private final DisplayMetrics mDisplayMetrics = new DisplayMetrics();
private Rect mTmpRect = new Rect();
private int mMinVisibleWidth;
private int mMinVisibleHeight;
@@ -151,11 +147,8 @@
if (!mTmpRect.equals(mWindowDragBounds)) {
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER,
"wm.TaskPositioner.resizeTask");
- try {
- mActivityManager.resizeTask(
- mTask.mTaskId, mWindowDragBounds, RESIZE_MODE_USER);
- } catch (RemoteException e) {
- }
+ mService.mAtmService.resizeTask(
+ mTask.mTaskId, mWindowDragBounds, RESIZE_MODE_USER);
Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
}
} break;
@@ -181,14 +174,12 @@
endDragLocked();
mTask.getDimBounds(mTmpRect);
}
- try {
- if (wasResizing && !mTmpRect.equals(mWindowDragBounds)) {
- // We were using fullscreen surface during resizing. Request
- // resizeTask() one last time to restore surface to window size.
- mActivityManager.resizeTask(
- mTask.mTaskId, mWindowDragBounds, RESIZE_MODE_USER_FORCED);
- }
- } catch(RemoteException e) {}
+ if (wasResizing && !mTmpRect.equals(mWindowDragBounds)) {
+ // We were using fullscreen surface during resizing. Request
+ // resizeTask() one last time to restore surface to window size.
+ mService.mAtmService.resizeTask(
+ mTask.mTaskId, mWindowDragBounds, RESIZE_MODE_USER_FORCED);
+ }
// Post back to WM to handle clean-ups. We still need the input
// event handler for the last finishInputEvent()!
@@ -203,15 +194,10 @@
}
}
+ /** Use {@link #create(WindowManagerService)} instead. */
@VisibleForTesting
- TaskPositioner(WindowManagerService service, IActivityTaskManager activityManager) {
- mService = service;
- mActivityManager = activityManager;
- }
-
- /** Use {@link #create(WindowManagerService)} instead **/
TaskPositioner(WindowManagerService service) {
- this(service, service.mActivityTaskManager);
+ mService = service;
}
@VisibleForTesting
@@ -224,8 +210,6 @@
* @param win The window which will be dragged.
*/
void register(DisplayContent displayContent, @NonNull WindowState win) {
- final Display display = displayContent.getDisplay();
-
if (DEBUG_TASK_POSITIONING) {
Slog.d(TAG, "Registering task positioner");
}
@@ -236,7 +220,6 @@
}
mDisplayContent = displayContent;
- display.getMetrics(mDisplayMetrics);
final InputChannel[] channels = InputChannel.openInputChannelPair(TAG);
mServerChannel = channels[0];
mClientChannel = channels[1];
@@ -251,7 +234,8 @@
mDragApplicationHandle.dispatchingTimeoutNanos =
WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
- mDragWindowHandle = new InputWindowHandle(mDragApplicationHandle, display.getDisplayId());
+ mDragWindowHandle = new InputWindowHandle(mDragApplicationHandle,
+ displayContent.getDisplayId());
mDragWindowHandle.name = TAG;
mDragWindowHandle.token = mServerChannel.getToken();
mDragWindowHandle.layoutParamsFlags = 0;
@@ -271,13 +255,13 @@
// The drag window cannot receive new touches.
mDragWindowHandle.touchableRegion.setEmpty();
- // The drag window covers the entire display
- mDragWindowHandle.frameLeft = 0;
- mDragWindowHandle.frameTop = 0;
- final Point p = new Point();
- display.getRealSize(p);
- mDragWindowHandle.frameRight = p.x;
- mDragWindowHandle.frameBottom = p.y;
+ // The drag window covers the entire display.
+ final Rect displayBounds = mTmpRect;
+ displayContent.getBounds(mTmpRect);
+ mDragWindowHandle.frameLeft = displayBounds.left;
+ mDragWindowHandle.frameTop = displayBounds.top;
+ mDragWindowHandle.frameRight = displayBounds.right;
+ mDragWindowHandle.frameBottom = displayBounds.bottom;
// Pause rotations before a drag.
ProtoLog.d(WM_DEBUG_ORIENTATION, "Pausing rotation during re-position");
@@ -287,9 +271,10 @@
mDisplayContent.getInputMonitor().updateInputWindowsImmediately();
new SurfaceControl.Transaction().syncInputWindows().apply(true);
- mMinVisibleWidth = dipToPixel(MINIMUM_VISIBLE_WIDTH_IN_DP, mDisplayMetrics);
- mMinVisibleHeight = dipToPixel(MINIMUM_VISIBLE_HEIGHT_IN_DP, mDisplayMetrics);
- display.getRealSize(mMaxVisibleSize);
+ final DisplayMetrics displayMetrics = displayContent.getDisplayMetrics();
+ mMinVisibleWidth = dipToPixel(MINIMUM_VISIBLE_WIDTH_IN_DP, displayMetrics);
+ mMinVisibleHeight = dipToPixel(MINIMUM_VISIBLE_HEIGHT_IN_DP, displayMetrics);
+ mMaxVisibleSize.set(displayBounds.width(), displayBounds.height());
mDragEnded = false;
@@ -341,8 +326,11 @@
mWindow = null;
}
- void startDrag(boolean resize, boolean preserveOrientation, float startX,
- float startY) {
+ /**
+ * Starts moving or resizing the task. This method should be only called from
+ * {@link TaskPositioningController#startPositioningLocked} or unit tests.
+ */
+ void startDrag(boolean resize, boolean preserveOrientation, float startX, float startY) {
if (DEBUG_TASK_POSITIONING) {
Slog.d(TAG, "startDrag: win=" + mWindow + ", resize=" + resize
+ ", preserveOrientation=" + preserveOrientation + ", {" + startX + ", "
@@ -351,12 +339,9 @@
// Use the bounds of the task which accounts for
// multiple app windows. Don't use any bounds from win itself as it
// may not be the same size as the task.
- mTask.getBounds(mTmpRect);
- startDrag(resize, preserveOrientation, startX, startY, mTmpRect);
- }
+ final Rect startBounds = mTmpRect;
+ mTask.getBounds(startBounds);
- protected void startDrag(boolean resize, boolean preserveOrientation,
- float startX, float startY, Rect startBounds) {
mCtrlType = CTRL_NONE;
mStartDragX = startX;
mStartDragY = startY;
@@ -389,20 +374,13 @@
// bounds yet. This will guarantee that the app starts the backdrop renderer before
// configuration changes which could cause an activity restart.
if (mResizing) {
- synchronized (mService.mGlobalLock) {
- notifyMoveLocked(startX, startY);
- }
+ notifyMoveLocked(startX, startY);
- // Perform the resize on the WMS handler thread when we don't have the WMS lock held
- // to ensure that we don't deadlock WMS and AMS. Note that WindowPositionerEventReceiver
- // callbacks are delivered on the same handler so this initial resize is always
- // guaranteed to happen before subsequent drag resizes.
+ // The WindowPositionerEventReceiver callbacks are delivered on the same handler so this
+ // initial resize is always guaranteed to happen before subsequent drag resizes.
mService.mH.post(() -> {
- try {
- mActivityManager.resizeTask(
- mTask.mTaskId, startBounds, RESIZE_MODE_USER_FORCED);
- } catch (RemoteException e) {
- }
+ mService.mAtmService.resizeTask(
+ mTask.mTaskId, startBounds, RESIZE_MODE_USER_FORCED);
});
}
@@ -417,7 +395,8 @@
}
/** Returns true if the move operation should be ended. */
- private boolean notifyMoveLocked(float x, float y) {
+ @VisibleForTesting
+ boolean notifyMoveLocked(float x, float y) {
if (DEBUG_TASK_POSITIONING) {
Slog.d(TAG, "notifyMoveLocked: {" + x + "," + y + "}");
}
@@ -429,12 +408,11 @@
}
// This is a moving or scrolling operation.
- mTask.getStack().getDimBounds(mTmpRect);
- // If a target window is covered by system bar, there is no way to move it again by touch.
- // So we exclude them from stack bounds. and then it will be shown inside stable area.
- Rect stableBounds = new Rect();
- mDisplayContent.getStableRect(stableBounds);
- mTmpRect.intersect(stableBounds);
+ // Only allow to move in stable area so the target window won't be covered by system bar.
+ // Though {@link Task#resolveOverrideConfiguration} should also avoid the case.
+ mDisplayContent.getStableRect(mTmpRect);
+ // The task may be put in a limited display area.
+ mTmpRect.intersect(mTask.getRootTask().getParent().getBounds());
int nX = (int) x;
int nY = (int) y;
diff --git a/services/core/java/com/android/server/wm/TaskTile.java b/services/core/java/com/android/server/wm/TaskTile.java
index 74d5c33..205b423 100644
--- a/services/core/java/com/android/server/wm/TaskTile.java
+++ b/services/core/java/com/android/server/wm/TaskTile.java
@@ -147,7 +147,7 @@
*/
void updateResolvedConfig(Configuration inOutResolvedConfig) {
Rect resolveBounds = inOutResolvedConfig.windowConfiguration.getBounds();
- if (resolveBounds == null || resolveBounds.isEmpty()) {
+ if (resolveBounds.isEmpty()) {
resolveBounds.set(getRequestedOverrideBounds());
}
int stackMode = inOutResolvedConfig.windowConfiguration.getWindowingMode();
@@ -162,6 +162,17 @@
inOutResolvedConfig.smallestScreenWidthDp =
getRequestedOverrideConfiguration().smallestScreenWidthDp;
}
+ if (inOutResolvedConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
+ inOutResolvedConfig.screenWidthDp = getRequestedOverrideConfiguration().screenWidthDp;
+ }
+ if (inOutResolvedConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
+ inOutResolvedConfig.screenHeightDp = getRequestedOverrideConfiguration().screenHeightDp;
+ }
+ Rect resolveAppBounds = inOutResolvedConfig.windowConfiguration.getAppBounds();
+ if (resolveAppBounds == null || resolveAppBounds.isEmpty()) {
+ inOutResolvedConfig.windowConfiguration.setAppBounds(
+ getRequestedOverrideConfiguration().windowConfiguration.getAppBounds());
+ }
}
@Override
@@ -184,7 +195,6 @@
boolean isResizable = topTask == null || topTask.isResizeable();
info.resizeMode = isResizable ? RESIZE_MODE_RESIZEABLE : RESIZE_MODE_UNRESIZEABLE;
info.topActivityType = top == null ? ACTIVITY_TYPE_UNDEFINED : top.getActivityType();
- info.configuration.setTo(getRequestedOverrideConfiguration());
}
@Override
diff --git a/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java b/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java
index bd70599..f467015 100644
--- a/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java
+++ b/services/core/java/com/android/server/wm/WallpaperAnimationAdapter.java
@@ -92,7 +92,7 @@
*/
RemoteAnimationTarget createRemoteAnimationTarget() {
mTarget = new RemoteAnimationTarget(-1, -1, getLeash(), false, null, null,
- mWallpaperToken.getPrefixOrderIndex(), new Point(), null,
+ mWallpaperToken.getPrefixOrderIndex(), new Point(), null, null,
mWallpaperToken.getWindowConfiguration(), true, null, null);
return mTarget;
}
diff --git a/services/core/java/com/android/server/wm/WallpaperController.java b/services/core/java/com/android/server/wm/WallpaperController.java
index 669eb78..57d0a33 100644
--- a/services/core/java/com/android/server/wm/WallpaperController.java
+++ b/services/core/java/com/android/server/wm/WallpaperController.java
@@ -41,6 +41,7 @@
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.ArraySet;
+import android.util.MathUtils;
import android.util.Slog;
import android.view.DisplayInfo;
import android.view.SurfaceControl;
@@ -52,6 +53,7 @@
import java.io.PrintWriter;
import java.util.ArrayList;
+import java.util.function.Consumer;
/**
* Controls wallpaper windows visibility, ordering, and so on.
@@ -75,8 +77,10 @@
private float mLastWallpaperY = -1;
private float mLastWallpaperXStep = -1;
private float mLastWallpaperYStep = -1;
+ private float mLastWallpaperZoomOut = 0;
private int mLastWallpaperDisplayOffsetX = Integer.MIN_VALUE;
private int mLastWallpaperDisplayOffsetY = Integer.MIN_VALUE;
+ private final float mMaxWallpaperScale;
// This is set when we are waiting for a wallpaper to tell us it is done
// changing its scroll position.
@@ -191,9 +195,21 @@
return false;
};
+ /**
+ * @see #computeLastWallpaperZoomOut()
+ */
+ private Consumer<WindowState> mComputeMaxZoomOutFunction = windowState -> {
+ if (!windowState.mIsWallpaper
+ && Float.compare(windowState.mWallpaperZoomOut, mLastWallpaperZoomOut) > 0) {
+ mLastWallpaperZoomOut = windowState.mWallpaperZoomOut;
+ }
+ };
+
WallpaperController(WindowManagerService service, DisplayContent displayContent) {
mService = service;
mDisplayContent = displayContent;
+ mMaxWallpaperScale = service.mContext.getResources()
+ .getFloat(com.android.internal.R.dimen.config_wallpaperMaxScale);
}
WindowState getWallpaperTarget() {
@@ -325,20 +341,30 @@
rawChanged = true;
}
- boolean changed = wallpaperWin.mWinAnimator.setWallpaperOffset(xOffset, yOffset);
+ if (Float.compare(wallpaperWin.mWallpaperZoomOut, mLastWallpaperZoomOut) != 0) {
+ wallpaperWin.mWallpaperZoomOut = mLastWallpaperZoomOut;
+ rawChanged = true;
+ }
+
+ boolean changed = wallpaperWin.mWinAnimator.setWallpaperOffset(xOffset, yOffset,
+ wallpaperWin.mShouldScaleWallpaper
+ ? zoomOutToScale(wallpaperWin.mWallpaperZoomOut) : 1);
if (rawChanged && (wallpaperWin.mAttrs.privateFlags &
WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS) != 0) {
try {
if (DEBUG_WALLPAPER) Slog.v(TAG, "Report new wp offset "
+ wallpaperWin + " x=" + wallpaperWin.mWallpaperX
- + " y=" + wallpaperWin.mWallpaperY);
+ + " y=" + wallpaperWin.mWallpaperY
+ + " zoom=" + wallpaperWin.mWallpaperZoomOut);
if (sync) {
mWaitingOnWallpaper = wallpaperWin;
}
wallpaperWin.mClient.dispatchWallpaperOffsets(
wallpaperWin.mWallpaperX, wallpaperWin.mWallpaperY,
- wallpaperWin.mWallpaperXStep, wallpaperWin.mWallpaperYStep, sync);
+ wallpaperWin.mWallpaperXStep, wallpaperWin.mWallpaperYStep,
+ wallpaperWin.mWallpaperZoomOut, sync);
+
if (sync) {
if (mWaitingOnWallpaper != null) {
long start = SystemClock.uptimeMillis();
@@ -378,6 +404,20 @@
}
}
+ void setWallpaperZoomOut(WindowState window, float zoom) {
+ if (Float.compare(window.mWallpaperZoomOut, zoom) != 0) {
+ window.mWallpaperZoomOut = zoom;
+ updateWallpaperOffsetLocked(window, false);
+ }
+ }
+
+ void setShouldZoomOutWallpaper(WindowState window, boolean shouldZoom) {
+ if (shouldZoom != window.mShouldScaleWallpaper) {
+ window.mShouldScaleWallpaper = shouldZoom;
+ updateWallpaperOffsetLocked(window, false);
+ }
+ }
+
void setWindowWallpaperDisplayOffset(WindowState window, int x, int y) {
if (window.mWallpaperDisplayOffsetX != x || window.mWallpaperDisplayOffsetY != y) {
window.mWallpaperDisplayOffsetX = x;
@@ -420,6 +460,7 @@
} else if (changingTarget.mWallpaperY >= 0) {
mLastWallpaperY = changingTarget.mWallpaperY;
}
+ computeLastWallpaperZoomOut();
if (target.mWallpaperDisplayOffsetX != Integer.MIN_VALUE) {
mLastWallpaperDisplayOffsetX = target.mWallpaperDisplayOffsetX;
} else if (changingTarget.mWallpaperDisplayOffsetX != Integer.MIN_VALUE) {
@@ -593,6 +634,9 @@
mLastWallpaperX = mWallpaperTarget.mWallpaperX;
mLastWallpaperXStep = mWallpaperTarget.mWallpaperXStep;
}
+ if (mWallpaperTarget.mWallpaperZoomOut >= 0) {
+ mLastWallpaperZoomOut = mWallpaperTarget.mWallpaperZoomOut;
+ }
if (mWallpaperTarget.mWallpaperY >= 0) {
mLastWallpaperY = mWallpaperTarget.mWallpaperY;
mLastWallpaperYStep = mWallpaperTarget.mWallpaperYStep;
@@ -762,6 +806,23 @@
return mTmpTopWallpaper;
}
+ /**
+ * Each window can request a zoom, example:
+ * - User is in overview, zoomed out.
+ * - User also pulls down the shade.
+ *
+ * This means that we always have to choose the largest zoom out that we have, otherwise
+ * we'll have conflicts and break the "depth system" mental model.
+ */
+ private void computeLastWallpaperZoomOut() {
+ mLastWallpaperZoomOut = 0;
+ mDisplayContent.forAllWindows(mComputeMaxZoomOutFunction, true);
+ }
+
+ private float zoomOutToScale(float zoom) {
+ return MathUtils.lerp(1, mMaxWallpaperScale, 1 - zoom);
+ }
+
void dump(PrintWriter pw, String prefix) {
pw.print(prefix); pw.print("displayId="); pw.println(mDisplayContent.getDisplayId());
pw.print(prefix); pw.print("mWallpaperTarget="); pw.println(mWallpaperTarget);
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index a60db94..0b11dd2 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -96,8 +96,8 @@
mAnimationFrameCallback = frameTimeNs -> {
synchronized (mService.mGlobalLock) {
mAnimationFrameCallbackScheduled = false;
+ animate(frameTimeNs);
}
- animate(frameTimeNs);
};
}
@@ -115,110 +115,94 @@
mInitialized = true;
}
- /**
- * DO NOT HOLD THE WINDOW MANAGER LOCK WHILE CALLING THIS METHOD. Reason: the method closes
- * an animation transaction, that might be blocking until the next sf-vsync, so we want to make
- * sure other threads can make progress if this happens.
- */
private void animate(long frameTimeNs) {
-
- synchronized (mService.mGlobalLock) {
- if (!mInitialized) {
- return;
- }
-
- // Schedule next frame already such that back-pressure happens continuously
- scheduleAnimation();
+ if (!mInitialized) {
+ return;
}
- synchronized (mService.mGlobalLock) {
- mCurrentTime = frameTimeNs / TimeUtils.NANOS_PER_MS;
- mBulkUpdateParams = SET_ORIENTATION_CHANGE_COMPLETE;
- if (DEBUG_WINDOW_TRACE) {
- Slog.i(TAG, "!!! animate: entry time=" + mCurrentTime);
+ // Schedule next frame already such that back-pressure happens continuously.
+ scheduleAnimation();
+
+ mCurrentTime = frameTimeNs / TimeUtils.NANOS_PER_MS;
+ mBulkUpdateParams = SET_ORIENTATION_CHANGE_COMPLETE;
+ if (DEBUG_WINDOW_TRACE) {
+ Slog.i(TAG, "!!! animate: entry time=" + mCurrentTime);
+ }
+
+ ProtoLog.i(WM_SHOW_TRANSACTIONS, ">>> OPEN TRANSACTION animate");
+ mService.openSurfaceTransaction();
+ try {
+ final AccessibilityController accessibilityController =
+ mService.mAccessibilityController;
+ final int numDisplays = mDisplayContentsAnimators.size();
+ for (int i = 0; i < numDisplays; i++) {
+ final int displayId = mDisplayContentsAnimators.keyAt(i);
+ final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
+ // Update animations of all applications, including those associated with
+ // exiting/removed apps.
+ dc.updateWindowsForAnimator();
+ dc.prepareSurfaces();
}
- ProtoLog.i(WM_SHOW_TRANSACTIONS, ">>> OPEN TRANSACTION animate");
- mService.openSurfaceTransaction();
- try {
- final AccessibilityController accessibilityController =
- mService.mAccessibilityController;
- final int numDisplays = mDisplayContentsAnimators.size();
- for (int i = 0; i < numDisplays; i++) {
- final int displayId = mDisplayContentsAnimators.keyAt(i);
- final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
- // Update animations of all applications, including those
- // associated with exiting/removed apps
- dc.updateWindowsForAnimator();
- dc.prepareSurfaces();
+ for (int i = 0; i < numDisplays; i++) {
+ final int displayId = mDisplayContentsAnimators.keyAt(i);
+ final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
+
+ dc.checkAppWindowsReadyToShow();
+ if (accessibilityController != null) {
+ accessibilityController.drawMagnifiedRegionBorderIfNeededLocked(displayId,
+ mTransaction);
}
-
- for (int i = 0; i < numDisplays; i++) {
- final int displayId = mDisplayContentsAnimators.keyAt(i);
- final DisplayContent dc = mService.mRoot.getDisplayContent(displayId);
-
- dc.checkAppWindowsReadyToShow();
- if (accessibilityController != null) {
- accessibilityController.drawMagnifiedRegionBorderIfNeededLocked(displayId,
- mTransaction);
- }
- }
-
- cancelAnimation();
-
- if (mService.mWatermark != null) {
- mService.mWatermark.drawIfNeeded();
- }
-
- SurfaceControl.mergeToGlobalTransaction(mTransaction);
- } catch (RuntimeException e) {
- Slog.wtf(TAG, "Unhandled exception in Window Manager", e);
- } finally {
- mService.closeSurfaceTransaction("WindowAnimator");
- ProtoLog.i(WM_SHOW_TRANSACTIONS, "<<< CLOSE TRANSACTION animate");
}
- boolean hasPendingLayoutChanges = mService.mRoot.hasPendingLayoutChanges(this);
- boolean doRequest = false;
- if (mBulkUpdateParams != 0) {
- doRequest = mService.mRoot.copyAnimToLayoutParams();
+ cancelAnimation();
+
+ if (mService.mWatermark != null) {
+ mService.mWatermark.drawIfNeeded();
}
- if (hasPendingLayoutChanges || doRequest) {
- mService.mWindowPlacerLocked.requestTraversal();
- }
+ SurfaceControl.mergeToGlobalTransaction(mTransaction);
+ } catch (RuntimeException e) {
+ Slog.wtf(TAG, "Unhandled exception in Window Manager", e);
+ } finally {
+ mService.closeSurfaceTransaction("WindowAnimator");
+ ProtoLog.i(WM_SHOW_TRANSACTIONS, "<<< CLOSE TRANSACTION animate");
+ }
- final boolean rootAnimating = mService.mRoot.isAnimating(TRANSITION | CHILDREN);
- if (rootAnimating && !mLastRootAnimating) {
+ final boolean hasPendingLayoutChanges = mService.mRoot.hasPendingLayoutChanges(this);
+ final boolean doRequest = mBulkUpdateParams != 0 && mService.mRoot.copyAnimToLayoutParams();
+ if (hasPendingLayoutChanges || doRequest) {
+ mService.mWindowPlacerLocked.requestTraversal();
+ }
- // Usually app transitions but quite a load onto the system already (with all the
- // things happening in app), so pause task snapshot persisting to not increase the
- // load.
- mService.mTaskSnapshotController.setPersisterPaused(true);
- Trace.asyncTraceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "animating", 0);
- }
- if (!rootAnimating && mLastRootAnimating) {
- mService.mWindowPlacerLocked.requestTraversal();
- mService.mTaskSnapshotController.setPersisterPaused(false);
- Trace.asyncTraceEnd(Trace.TRACE_TAG_WINDOW_MANAGER, "animating", 0);
- }
+ final boolean rootAnimating = mService.mRoot.isAnimating(TRANSITION | CHILDREN);
+ if (rootAnimating && !mLastRootAnimating) {
+ // Usually app transitions but quite a load onto the system already (with all the things
+ // happening in app), so pause task snapshot persisting to not increase the load.
+ mService.mTaskSnapshotController.setPersisterPaused(true);
+ Trace.asyncTraceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "animating", 0);
+ }
+ if (!rootAnimating && mLastRootAnimating) {
+ mService.mWindowPlacerLocked.requestTraversal();
+ mService.mTaskSnapshotController.setPersisterPaused(false);
+ Trace.asyncTraceEnd(Trace.TRACE_TAG_WINDOW_MANAGER, "animating", 0);
+ }
- mLastRootAnimating = rootAnimating;
+ mLastRootAnimating = rootAnimating;
- if (mRemoveReplacedWindows) {
- mService.mRoot.removeReplacedWindows();
- mRemoveReplacedWindows = false;
- }
+ if (mRemoveReplacedWindows) {
+ mService.mRoot.removeReplacedWindows();
+ mRemoveReplacedWindows = false;
+ }
- mService.destroyPreservedSurfaceLocked();
+ mService.destroyPreservedSurfaceLocked();
- executeAfterPrepareSurfacesRunnables();
+ executeAfterPrepareSurfacesRunnables();
- if (DEBUG_WINDOW_TRACE) {
- Slog.i(TAG, "!!! animate: exit"
- + " mBulkUpdateParams=" + Integer.toHexString(mBulkUpdateParams)
- + " hasPendingLayoutChanges=" + hasPendingLayoutChanges);
- }
+ if (DEBUG_WINDOW_TRACE) {
+ Slog.i(TAG, "!!! animate: exit"
+ + " mBulkUpdateParams=" + Integer.toHexString(mBulkUpdateParams)
+ + " hasPendingLayoutChanges=" + hasPendingLayoutChanges);
}
}
diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java
index 10d34b5..9a92832 100644
--- a/services/core/java/com/android/server/wm/WindowContainer.java
+++ b/services/core/java/com/android/server/wm/WindowContainer.java
@@ -40,6 +40,7 @@
import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
+import static com.android.server.wm.WindowContainerChildProto.WINDOW_CONTAINER;
import static com.android.server.wm.WindowContainerProto.CONFIGURATION_CONTAINER;
import static com.android.server.wm.WindowContainerProto.ORIENTATION;
import static com.android.server.wm.WindowContainerProto.SURFACE_ANIMATOR;
@@ -274,7 +275,7 @@
RemoteToken mRemoteToken = null;
BLASTSyncEngine mBLASTSyncEngine = new BLASTSyncEngine();
- SurfaceControl.Transaction mBLASTSyncTransaction = new SurfaceControl.Transaction();
+ SurfaceControl.Transaction mBLASTSyncTransaction;
boolean mUsingBLASTSyncTransaction = false;
BLASTSyncEngine.TransactionReadyListener mWaitingListener;
int mWaitingSyncId;
@@ -282,6 +283,7 @@
WindowContainer(WindowManagerService wms) {
mWmService = wms;
mPendingTransaction = wms.mTransactionFactory.get();
+ mBLASTSyncTransaction = wms.mTransactionFactory.get();
mSurfaceAnimator = new SurfaceAnimator(this, this::onAnimationFinished, wms);
mSurfaceFreezer = new SurfaceFreezer(this, wms);
}
@@ -1819,9 +1821,25 @@
if (mSurfaceAnimator.isAnimating()) {
mSurfaceAnimator.dumpDebug(proto, SURFACE_ANIMATOR);
}
+
+ // add children to proto
+ for (int i = 0; i < getChildCount(); i++) {
+ final long childToken = proto.start(WindowContainerProto.CHILDREN);
+ final E child = getChildAt(i);
+ child.dumpDebug(proto, child.getProtoFieldId(), logLevel);
+ proto.end(childToken);
+ }
proto.end(token);
}
+ /**
+ * @return a proto field id to identify where to add the derived class to the generic window
+ * container proto.
+ */
+ long getProtoFieldId() {
+ return WINDOW_CONTAINER;
+ }
+
private ForAllWindowsConsumerWrapper obtainConsumerWrapper(Consumer<WindowState> consumer) {
ForAllWindowsConsumerWrapper wrapper = mConsumerWrapperPool.acquire();
if (wrapper == null) {
@@ -2086,9 +2104,11 @@
// Delaying animation start isn't compatible with remote animations at all.
if (controller != null && !mSurfaceAnimator.isAnimationStartDelayed()) {
+ final Rect localBounds = new Rect(mTmpRect);
+ localBounds.offsetTo(mTmpPoint.x, mTmpPoint.y);
final RemoteAnimationController.RemoteAnimationRecord adapters =
- controller.createRemoteAnimationRecord(this, mTmpPoint, mTmpRect,
- (isChanging ? mSurfaceFreezer.mFreezeBounds : null));
+ controller.createRemoteAnimationRecord(this, mTmpPoint, localBounds,
+ mTmpRect, (isChanging ? mSurfaceFreezer.mFreezeBounds : null));
resultAdapters = new Pair<>(adapters.mAdapter, adapters.mThumbnailAdapter);
} else if (isChanging) {
final float durationScale = mWmService.getTransitionAnimationScaleLocked();
@@ -2441,6 +2461,19 @@
mWaitingSyncId = -1;
}
+ /**
+ * Returns true if any of the children elected to participate in the Sync
+ */
+ boolean addChildrenToSyncSet(int localId) {
+ boolean willSync = false;
+
+ for (int i = 0; i < mChildren.size(); i++) {
+ final WindowContainer child = mChildren.get(i);
+ willSync |= mBLASTSyncEngine.addToSyncSet(localId, child);
+ }
+ return willSync;
+ }
+
boolean prepareForSync(BLASTSyncEngine.TransactionReadyListener waitingListener,
int waitingId) {
boolean willSync = false;
@@ -2449,16 +2482,12 @@
}
mUsingBLASTSyncTransaction = true;
- int localId = mBLASTSyncEngine.startSyncSet(this);
- for (int i = 0; i < mChildren.size(); i++) {
- final WindowContainer child = mChildren.get(i);
- willSync = mBLASTSyncEngine.addToSyncSet(localId, child) | willSync;
- }
-
// Make sure to set these before we call setReady in case the sync was a no-op
mWaitingSyncId = waitingId;
mWaitingListener = waitingListener;
+ int localId = mBLASTSyncEngine.startSyncSet(this);
+ willSync |= addChildrenToSyncSet(localId);
mBLASTSyncEngine.setReady(localId);
return willSync;
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 3f4f629..1a77807 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -1007,9 +1007,7 @@
void openSurfaceTransaction() {
try {
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "openSurfaceTransaction");
- synchronized (mGlobalLock) {
- SurfaceControl.openTransaction();
- }
+ SurfaceControl.openTransaction();
} finally {
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
}
@@ -1022,10 +1020,8 @@
void closeSurfaceTransaction(String where) {
try {
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "closeSurfaceTransaction");
- synchronized (mGlobalLock) {
- SurfaceControl.closeTransaction();
- mWindowTracing.logState(where);
- }
+ SurfaceControl.closeTransaction();
+ mWindowTracing.logState(where);
} finally {
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
}
@@ -1287,7 +1283,7 @@
mConstants.start(new HandlerExecutor(mH));
LocalServices.addService(WindowManagerInternal.class, new LocalService());
- mEmbeddedWindowController = new EmbeddedWindowController(mGlobalLock);
+ mEmbeddedWindowController = new EmbeddedWindowController(mAtmService);
mDisplayAreaPolicyProvider = DisplayAreaPolicy.Provider.fromResources(
mContext.getResources());
@@ -1900,7 +1896,7 @@
if (dc.mCurrentFocus == null) {
dc.mWinRemovedSinceNullFocus.add(win);
}
- mEmbeddedWindowController.removeWindowsWithHost(win);
+ mEmbeddedWindowController.onWindowRemoved(win);
mPendingRemove.remove(win);
mResizingWindows.remove(win);
updateNonSystemOverlayWindowsVisibilityIfNeeded(win, false /* surfaceShown */);
@@ -2447,10 +2443,6 @@
// of a transaction to avoid artifacts.
win.mAnimatingExit = true;
} else {
- final DisplayContent displayContent = win.getDisplayContent();
- if (displayContent.mInputMethodWindow == win) {
- displayContent.setInputMethodWindowLocked(null);
- }
boolean stopped = win.mActivityRecord != null ? win.mActivityRecord.mAppStopped : true;
// We set mDestroying=true so ActivityRecord#notifyAppStopped in-to destroy surfaces
// will later actually destroy the surface if we do not do so here. Normally we leave
@@ -2610,7 +2602,8 @@
if (type == TYPE_WALLPAPER) {
new WallpaperWindowToken(this, binder, true, dc, callerCanManageAppTokens);
} else {
- new WindowToken(this, binder, type, true, dc, callerCanManageAppTokens);
+ new WindowToken(this, binder, type, true, dc, callerCanManageAppTokens,
+ false /* roundedCornerOverlay */, fromClientToken);
}
}
} finally {
@@ -4661,6 +4654,7 @@
public static final int RECOMPUTE_FOCUS = 61;
public static final int ON_POINTER_DOWN_OUTSIDE_FOCUS = 62;
public static final int LAYOUT_AND_ASSIGN_WINDOW_LAYERS_IF_NEEDED = 63;
+ public static final int WINDOW_STATE_BLAST_SYNC_TIMEOUT = 64;
/**
* Used to denote that an integer field in a message will not be used.
@@ -5041,6 +5035,13 @@
}
break;
}
+ case WINDOW_STATE_BLAST_SYNC_TIMEOUT: {
+ synchronized (mGlobalLock) {
+ final WindowState ws = (WindowState) msg.obj;
+ ws.finishDrawing(null);
+ }
+ break;
+ }
}
if (DEBUG_WINDOW_TRACE) {
Slog.v(TAG_WM, "handleMessage: exit");
@@ -6126,7 +6127,7 @@
}
mRoot.forAllWindows((w) -> {
- if ((!visibleOnly || w.mWinAnimator.getShown())
+ if ((!visibleOnly || w.isVisible())
&& (!appsOnly || w.mActivityRecord != null)) {
windows.add(w);
}
@@ -8010,9 +8011,9 @@
}
@Override
- public void getWindowInsets(WindowManager.LayoutParams attrs,
+ public boolean getWindowInsets(WindowManager.LayoutParams attrs,
int displayId, Rect outContentInsets, Rect outStableInsets,
- DisplayCutout.ParcelableWrapper displayCutout) {
+ DisplayCutout.ParcelableWrapper outDisplayCutout, InsetsState outInsetsState) {
final long origId = Binder.clearCallingIdentity();
try {
synchronized (mGlobalLock) {
@@ -8022,8 +8023,13 @@
+ "could not be found!");
}
final WindowToken windowToken = dc.getWindowToken(attrs.token);
- dc.getDisplayPolicy().getLayoutHint(attrs, windowToken, mTmpRect /* outFrame */,
- outContentInsets, outStableInsets, displayCutout);
+ final InsetsStateController insetsStateController =
+ dc.getInsetsStateController();
+ outInsetsState.set(insetsStateController.getInsetsForWindowMetrics(attrs));
+
+ return dc.getDisplayPolicy().getLayoutHint(attrs, windowToken,
+ mTmpRect /* outFrame */, outContentInsets, outStableInsets,
+ outDisplayCutout);
}
} finally {
Binder.restoreCallingIdentity(origId);
diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
index 03dc4c9..f356329 100644
--- a/services/core/java/com/android/server/wm/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -41,6 +41,7 @@
import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.app.ActivityThread;
import android.app.IApplicationThread;
import android.app.ProfilerInfo;
@@ -52,6 +53,7 @@
import android.content.res.Configuration;
import android.os.Build;
import android.os.Message;
+import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.ArraySet;
@@ -185,6 +187,13 @@
// Registered display id as a listener to override config change
private int mDisplayId;
private ActivityRecord mConfigActivityRecord;
+ /**
+ * Activities that hosts some UI drawn by the current process. The activities live
+ * in another process. This is used to check if the process is currently showing anything
+ * visible to the user.
+ */
+ @Nullable
+ private final ArrayList<ActivityRecord> mHostActivities = new ArrayList<>();
/** Whether our process is currently running a {@link RecentsAnimation} */
private boolean mRunningRecentsAnimation;
@@ -192,6 +201,9 @@
/** Whether our process is currently running a {@link IRemoteAnimationRunner} */
private boolean mRunningRemoteAnimation;
+ /** Whether this process is owned by the System UI package. */
+ final boolean mIsSysUiPackage;
+
public WindowProcessController(@NonNull ActivityTaskManagerService atm, ApplicationInfo info,
String name, int uid, int userId, Object owner, WindowProcessListener listener) {
mInfo = info;
@@ -202,6 +214,10 @@
mListener = listener;
mAtm = atm;
mDisplayId = INVALID_DISPLAY;
+
+ mIsSysUiPackage = info.packageName.equals(
+ mAtm.getSysUiServiceComponentLocked().getPackageName());
+
onConfigurationChanged(atm.getGlobalConfiguration());
}
@@ -672,6 +688,23 @@
return true;
}
}
+ if (isEmbedded()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @return {@code true} if this process is rendering content on to a window shown by
+ * another process.
+ */
+ private boolean isEmbedded() {
+ for (int i = mHostActivities.size() - 1; i >= 0; --i) {
+ final ActivityRecord r = mHostActivities.get(i);
+ if (r.isInterestingToUserLocked()) {
+ return true;
+ }
}
return false;
}
@@ -814,6 +847,19 @@
}
}
+ /** Adds an activity that hosts UI drawn by the current process. */
+ void addHostActivity(ActivityRecord r) {
+ if (mHostActivities.contains(r)) {
+ return;
+ }
+ mHostActivities.add(r);
+ }
+
+ /** Removes an activity that hosts UI drawn by the current process. */
+ void removeHostActivity(ActivityRecord r) {
+ mHostActivities.remove(r);
+ }
+
public interface ComputeOomAdjCallback {
void onVisibleActivity();
void onPausedActivity();
@@ -1012,7 +1058,7 @@
}
private void registerActivityConfigurationListener(ActivityRecord activityRecord) {
- if (activityRecord == null) {
+ if (activityRecord == null || activityRecord.containsListener(this)) {
return;
}
// A process can only register to one activityRecord to listen to the override configuration
@@ -1039,9 +1085,15 @@
* always track the configuration of the non-finishing activity last added to the process.
*/
private void updateActivityConfigurationListener() {
+ if (mIsSysUiPackage || mUid == Process.SYSTEM_UID) {
+ // This is a system owned process and should not use an activity config.
+ // TODO(b/151161907): Remove after support for display-independent (raw) SysUi configs.
+ return;
+ }
+
for (int i = mActivities.size() - 1; i >= 0; i--) {
final ActivityRecord activityRecord = mActivities.get(i);
- if (!activityRecord.finishing && !activityRecord.containsListener(this)) {
+ if (!activityRecord.finishing) {
// Eligible activity is found, update listener.
registerActivityConfigurationListener(activityRecord);
return;
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 27f1ca0..3617570 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -118,6 +118,7 @@
import static com.android.server.wm.SurfaceAnimator.ANIMATION_TYPE_WINDOW_ANIMATION;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
+import static com.android.server.wm.WindowContainerChildProto.WINDOW;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_CONFIGURATION;
@@ -137,6 +138,7 @@
import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_REMOVING_FOCUS;
import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_PLACE_SURFACES;
import static com.android.server.wm.WindowManagerService.WINDOWS_FREEZING_SCREENS_TIMEOUT;
+import static com.android.server.wm.WindowManagerService.H.WINDOW_STATE_BLAST_SYNC_TIMEOUT;
import static com.android.server.wm.WindowStateAnimator.COMMIT_DRAW_PENDING;
import static com.android.server.wm.WindowStateAnimator.DRAW_PENDING;
import static com.android.server.wm.WindowStateAnimator.HAS_DRAWN;
@@ -145,7 +147,6 @@
import static com.android.server.wm.WindowStateProto.ANIMATING_EXIT;
import static com.android.server.wm.WindowStateProto.ANIMATOR;
import static com.android.server.wm.WindowStateProto.ATTRIBUTES;
-import static com.android.server.wm.WindowStateProto.CHILD_WINDOWS;
import static com.android.server.wm.WindowStateProto.DESTROYING;
import static com.android.server.wm.WindowStateProto.DISPLAY_ID;
import static com.android.server.wm.WindowStateProto.FINISHED_SEAMLESS_ROTATION_FRAME;
@@ -414,6 +415,7 @@
float mHScale=1, mVScale=1;
float mLastHScale=1, mLastVScale=1;
final Matrix mTmpMatrix = new Matrix();
+ final float[] mTmpMatrixArray = new float[9];
private final WindowFrames mWindowFrames = new WindowFrames();
@@ -445,6 +447,14 @@
float mWallpaperX = -1;
float mWallpaperY = -1;
+ // If a window showing a wallpaper: the requested zoom out for the
+ // wallpaper; if a wallpaper window: the currently applied zoom.
+ float mWallpaperZoomOut = -1;
+
+ // If a wallpaper window: whether the wallpaper should be scaled when zoomed, if set
+ // to false, mWallpaperZoom will be ignored here and just passed to the WallpaperService.
+ boolean mShouldScaleWallpaper;
+
// If a window showing a wallpaper: what fraction of the offset
// range corresponds to a full virtual screen.
float mWallpaperXStep = -1;
@@ -670,6 +680,17 @@
int mFrameRateSelectionPriority = RefreshRatePolicy.LAYER_PRIORITY_UNSET;
/**
+ * BLASTSyncEngine ID corresponding to a sync-set for all
+ * our children. We add our children to this set in Sync,
+ * but we save it and don't mark it as ready until finishDrawing
+ * this way we have a two way latch between all our children finishing
+ * and drawing ourselves.
+ */
+ private int mLocalSyncId = -1;
+
+ static final int BLAST_TIMEOUT_DURATION = 5000; /* milliseconds */
+
+ /**
* @return The insets state as requested by the client, i.e. the dispatched insets state
* for which the visibilities are overridden with what the client requested.
*/
@@ -2917,8 +2938,9 @@
// and add the window only if the permission was granted. Therefore, if
// the mode is MODE_DEFAULT we want the op to succeed as the window is
// shown.
- final int mode = mWmService.mAppOps.startOpNoThrow(mAppOp,
- getOwningUid(), getOwningPackage(), true);
+ final int mode = mWmService.mAppOps.startOpNoThrow(mAppOp, getOwningUid(),
+ getOwningPackage(), true /* startIfModeDefault */, null /* featureId */,
+ "init-default-visibility");
if (mode != MODE_ALLOWED && mode != MODE_DEFAULT) {
setAppOpVisibilityLw(false);
}
@@ -2926,7 +2948,8 @@
void resetAppOpsState() {
if (mAppOp != OP_NONE && mAppOpVisibility) {
- mWmService.mAppOps.finishOp(mAppOp, getOwningUid(), getOwningPackage());
+ mWmService.mAppOps.finishOp(mAppOp, getOwningUid(), getOwningPackage(),
+ null /* featureId */);
}
}
@@ -2941,11 +2964,12 @@
// as this would mean we will get another change callback and will reconcile.
int mode = mWmService.mAppOps.checkOpNoThrow(mAppOp, uid, packageName);
if (mode != MODE_ALLOWED && mode != MODE_DEFAULT) {
- mWmService.mAppOps.finishOp(mAppOp, uid, packageName);
+ mWmService.mAppOps.finishOp(mAppOp, uid, packageName, null /* featureId */);
setAppOpVisibilityLw(false);
}
} else {
- final int mode = mWmService.mAppOps.startOpNoThrow(mAppOp, uid, packageName, true);
+ final int mode = mWmService.mAppOps.startOpNoThrow(mAppOp, uid, packageName,
+ true /* startIfModeDefault */, null /* featureId */, "attempt-to-be-visible");
if (mode == MODE_ALLOWED || mode == MODE_DEFAULT) {
setAppOpVisibilityLw(true);
}
@@ -3758,9 +3782,6 @@
mSurfacePosition.dumpDebug(proto, SURFACE_POSITION);
mWinAnimator.dumpDebug(proto, ANIMATOR);
proto.write(ANIMATING_EXIT, mAnimatingExit);
- for (int i = 0; i < mChildren.size(); i++) {
- mChildren.get(i).dumpDebug(proto, CHILD_WINDOWS, logLevel);
- }
proto.write(REQUESTED_WIDTH, mRequestedWidth);
proto.write(REQUESTED_HEIGHT, mRequestedHeight);
proto.write(VIEW_VISIBILITY, mViewVisibility);
@@ -3779,6 +3800,11 @@
}
@Override
+ long getProtoFieldId() {
+ return WINDOW;
+ }
+
+ @Override
public void writeIdentifierToProto(ProtoOutputStream proto, long fieldId) {
final long token = proto.start(fieldId);
proto.write(HASH_CODE, System.identityHashCode(this));
@@ -3918,6 +3944,9 @@
pw.println(prefix + "mWallpaperXStep=" + mWallpaperXStep
+ " mWallpaperYStep=" + mWallpaperYStep);
}
+ if (mWallpaperZoomOut != -1) {
+ pw.println(prefix + "mWallpaperZoomOut=" + mWallpaperZoomOut);
+ }
if (mWallpaperDisplayOffsetX != Integer.MIN_VALUE
|| mWallpaperDisplayOffsetY != Integer.MIN_VALUE) {
pw.println(prefix + "mWallpaperDisplayOffsetX=" + mWallpaperDisplayOffsetX
@@ -5660,17 +5689,27 @@
return mSession.mPid == pid && isNonToastOrStarting() && isVisibleNow();
}
- SurfaceControl getDeferTransactionBarrier() {
- return mWinAnimator.getDeferTransactionBarrier();
+ SurfaceControl getClientViewRootSurface() {
+ return mWinAnimator.getClientViewRootSurface();
}
@Override
boolean prepareForSync(BLASTSyncEngine.TransactionReadyListener waitingListener,
int waitingId) {
- // TODO(b/148871522): Support child window
+ if (!isVisible()) {
+ return false;
+ }
mWaitingListener = waitingListener;
mWaitingSyncId = waitingId;
mUsingBLASTSyncTransaction = true;
+
+ mLocalSyncId = mBLASTSyncEngine.startSyncSet(this);
+ addChildrenToSyncSet(mLocalSyncId);
+
+ mWmService.mH.removeMessages(WINDOW_STATE_BLAST_SYNC_TIMEOUT, this);
+ mWmService.mH.sendNewMessageDelayed(WINDOW_STATE_BLAST_SYNC_TIMEOUT, this,
+ BLAST_TIMEOUT_DURATION);
+
return true;
}
@@ -5678,11 +5717,23 @@
if (!mUsingBLASTSyncTransaction) {
return mWinAnimator.finishDrawingLocked(postDrawTransaction);
}
- if (postDrawTransaction == null) {
- postDrawTransaction = new SurfaceControl.Transaction();
+
+ mWmService.mH.removeMessages(WINDOW_STATE_BLAST_SYNC_TIMEOUT, this);
+ if (postDrawTransaction != null) {
+ mBLASTSyncTransaction.merge(postDrawTransaction);
}
- postDrawTransaction.merge(mBLASTSyncTransaction);
- mWaitingListener.transactionReady(mWaitingSyncId, postDrawTransaction);
+
+ // If localSyncId is >0 then we are syncing with children and will
+ // invoke transaction ready from our own #transactionReady callback
+ // we just need to signal our side of the sync (setReady). But if we
+ // have no sync operation at this level transactionReady will never
+ // be invoked and we need to invoke it ourself.
+ if (mLocalSyncId >= 0) {
+ mBLASTSyncEngine.setReady(mLocalSyncId);
+ } else {
+ mWaitingListener.transactionReady(mWaitingSyncId, mBLASTSyncTransaction);
+ }
+
mUsingBLASTSyncTransaction = false;
mWaitingSyncId = 0;
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 81d0e3e..563710b 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -16,6 +16,12 @@
package com.android.server.wm;
+import static android.graphics.Matrix.MSCALE_X;
+import static android.graphics.Matrix.MSCALE_Y;
+import static android.graphics.Matrix.MSKEW_X;
+import static android.graphics.Matrix.MSKEW_Y;
+import static android.graphics.Matrix.MTRANS_X;
+import static android.graphics.Matrix.MTRANS_Y;
import static android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
import static android.view.WindowManager.LayoutParams.FLAG_SCALED;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY;
@@ -217,6 +223,10 @@
int mXOffset = 0;
int mYOffset = 0;
+ // A scale factor for the surface contents, that will be applied from the center of the visible
+ // region.
+ float mWallpaperScale = 1f;
+
/**
* A flag to determine if the WSA needs to offset its position to compensate for the stack's
* position update before the WSA surface has resized.
@@ -383,8 +393,9 @@
// Make sure to reparent any children of the new surface back to the preserved
// surface before destroying it.
if (mSurfaceController != null && mPendingDestroySurface != null) {
- mPostDrawTransaction.reparentChildren(mSurfaceController.mSurfaceControl,
- mPendingDestroySurface.mSurfaceControl).apply();
+ mPostDrawTransaction.reparentChildren(
+ mSurfaceController.getClientViewRootSurface(),
+ mPendingDestroySurface.mSurfaceControl).apply();
}
destroySurfaceLocked();
mSurfaceDestroyDeferred = true;
@@ -413,9 +424,9 @@
// child layers need to be reparented to the new surface to make this
// transparent to the app.
if (mWin.mActivityRecord == null || mWin.mActivityRecord.isRelaunching() == false) {
- mPostDrawTransaction.reparentChildren(mPendingDestroySurface.mSurfaceControl,
- mSurfaceController.mSurfaceControl)
- .apply();
+ mPostDrawTransaction.reparentChildren(
+ mPendingDestroySurface.getClientViewRootSurface(),
+ mSurfaceController.mSurfaceControl).apply();
}
}
}
@@ -875,7 +886,7 @@
if (mSurfaceResized && (mAttrType == TYPE_BASE_APPLICATION) &&
(task != null) && (task.getMainWindowSizeChangeTransaction() != null)) {
- mSurfaceController.deferTransactionUntil(mWin.getDeferTransactionBarrier(),
+ mSurfaceController.deferTransactionUntil(mWin.getClientViewRootSurface(),
mWin.getFrameNumber());
SurfaceControl.mergeToGlobalTransaction(task.getMainWindowSizeChangeTransaction());
task.setMainWindowSizeChangeTransaction(null);
@@ -1012,7 +1023,7 @@
// the WS position is reset (so the stack position is shown) at the same
// time that the buffer size changes.
setOffsetPositionForStackResize(false);
- mSurfaceController.deferTransactionUntil(mWin.getDeferTransactionBarrier(),
+ mSurfaceController.deferTransactionUntil(mWin.getClientViewRootSurface(),
mWin.getFrameNumber());
} else {
final ActivityStack stack = mWin.getRootTask();
@@ -1033,7 +1044,12 @@
}
}
}
- mSurfaceController.setPositionInTransaction(xOffset, yOffset, recoveringMemory);
+ if (!mIsWallpaper) {
+ mSurfaceController.setPositionInTransaction(xOffset, yOffset, recoveringMemory);
+ } else {
+ setWallpaperPositionAndScale(
+ xOffset, yOffset, mWallpaperScale, recoveringMemory);
+ }
}
}
@@ -1043,18 +1059,22 @@
// comes in at the new size (normally position and crop are unfrozen).
// deferTransactionUntil accomplishes this for us.
if (wasForceScaled && !mForceScaleUntilResize) {
- mSurfaceController.deferTransactionUntil(mWin.getDeferTransactionBarrier(),
+ mSurfaceController.deferTransactionUntil(mWin.getClientViewRootSurface(),
mWin.getFrameNumber());
mSurfaceController.forceScaleableInTransaction(false);
}
if (!w.mSeamlesslyRotated) {
- applyCrop(clipRect, recoveringMemory);
- mSurfaceController.setMatrixInTransaction(mDsDx * w.mHScale * mExtraHScale,
- mDtDx * w.mVScale * mExtraVScale,
- mDtDy * w.mHScale * mExtraHScale,
- mDsDy * w.mVScale * mExtraVScale, recoveringMemory);
+ if (!mIsWallpaper) {
+ applyCrop(clipRect, recoveringMemory);
+ mSurfaceController.setMatrixInTransaction(mDsDx * w.mHScale * mExtraHScale,
+ mDtDx * w.mVScale * mExtraVScale,
+ mDtDy * w.mHScale * mExtraHScale,
+ mDsDy * w.mVScale * mExtraVScale, recoveringMemory);
+ } else {
+ setWallpaperPositionAndScale(mXOffset, mYOffset, mWallpaperScale, recoveringMemory);
+ }
}
if (mSurfaceResized) {
@@ -1201,18 +1221,18 @@
mSurfaceController.setTransparentRegionHint(region);
}
- boolean setWallpaperOffset(int dx, int dy) {
- if (mXOffset == dx && mYOffset == dy) {
+ boolean setWallpaperOffset(int dx, int dy, float scale) {
+ if (mXOffset == dx && mYOffset == dy && Float.compare(mWallpaperScale, scale) == 0) {
return false;
}
mXOffset = dx;
mYOffset = dy;
+ mWallpaperScale = scale;
try {
if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION setWallpaperOffset");
mService.openSurfaceTransaction();
- mSurfaceController.setPositionInTransaction(dx, dy, false);
- applyCrop(null, false);
+ setWallpaperPositionAndScale(dx, dy, scale, false);
} catch (RuntimeException e) {
Slog.w(TAG, "Error positioning surface of " + mWin
+ " pos=(" + dx + "," + dy + ")", e);
@@ -1224,6 +1244,27 @@
}
}
+ private void setWallpaperPositionAndScale(int dx, int dy, float scale,
+ boolean recoveringMemory) {
+ DisplayInfo displayInfo = mWin.getDisplayInfo();
+ Matrix matrix = mWin.mTmpMatrix;
+ matrix.setTranslate(dx, dy);
+ matrix.postScale(scale, scale, displayInfo.logicalWidth / 2f,
+ displayInfo.logicalHeight / 2f);
+ matrix.getValues(mWin.mTmpMatrixArray);
+ matrix.reset();
+
+ mSurfaceController.setPositionInTransaction(mWin.mTmpMatrixArray[MTRANS_X],
+ mWin.mTmpMatrixArray[MTRANS_Y], recoveringMemory);
+ mSurfaceController.setMatrixInTransaction(
+ mDsDx * mWin.mTmpMatrixArray[MSCALE_X] * mWin.mHScale * mExtraHScale,
+ mDtDx * mWin.mTmpMatrixArray[MSKEW_Y] * mWin.mVScale * mExtraVScale,
+ mDtDy * mWin.mTmpMatrixArray[MSKEW_X] * mWin.mHScale * mExtraHScale,
+ mDsDy * mWin.mTmpMatrixArray[MSCALE_Y] * mWin.mVScale * mExtraVScale,
+ recoveringMemory);
+ applyCrop(null, recoveringMemory);
+ }
+
/**
* Try to change the pixel format without recreating the surface. This
* will be common in the case of changing from PixelFormat.OPAQUE to
@@ -1288,8 +1329,9 @@
if (mPendingDestroySurface != null && mDestroyPreservedSurfaceUponRedraw) {
final SurfaceControl pendingSurfaceControl = mPendingDestroySurface.mSurfaceControl;
mPostDrawTransaction.reparent(pendingSurfaceControl, null);
- mPostDrawTransaction.reparentChildren(pendingSurfaceControl,
- mSurfaceController.mSurfaceControl);
+ mPostDrawTransaction.reparentChildren(
+ mPendingDestroySurface.getClientViewRootSurface(),
+ mSurfaceController.mSurfaceControl);
}
SurfaceControl.mergeToGlobalTransaction(mPostDrawTransaction);
@@ -1521,10 +1563,10 @@
mOffsetPositionForStackResize = offsetPositionForStackResize;
}
- SurfaceControl getDeferTransactionBarrier() {
+ SurfaceControl getClientViewRootSurface() {
if (!hasSurface()) {
return null;
}
- return mSurfaceController.getDeferTransactionBarrier();
+ return mSurfaceController.getClientViewRootSurface();
}
}
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index 383c0d9..d7c97b9 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -533,7 +533,15 @@
return mSurfaceH;
}
- SurfaceControl getDeferTransactionBarrier() {
+ /**
+ * Returns the Surface which the client-framework ViewRootImpl will be using.
+ * This is either the WSA SurfaceControl or it's BLAST child surface.
+ * This has too main uses:
+ * 1. This is the Surface the client will add children to, we use this to make
+ * sure we don't reparent the BLAST surface itself when calling reparentChildren
+ * 2. We use this as the barrier Surface for some deferTransaction operations.
+ */
+ SurfaceControl getClientViewRootSurface() {
if (mBLASTSurfaceControl != null) {
return mBLASTSurfaceControl;
}
diff --git a/services/core/java/com/android/server/wm/WindowToken.java b/services/core/java/com/android/server/wm/WindowToken.java
index 98d9c8fc..b7c6af2 100644
--- a/services/core/java/com/android/server/wm/WindowToken.java
+++ b/services/core/java/com/android/server/wm/WindowToken.java
@@ -28,13 +28,13 @@
import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
import static com.android.server.wm.WindowContainer.AnimationFlags.PARENTS;
import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
+import static com.android.server.wm.WindowContainerChildProto.WINDOW_TOKEN;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
import static com.android.server.wm.WindowTokenProto.HASH_CODE;
import static com.android.server.wm.WindowTokenProto.PAUSED;
import static com.android.server.wm.WindowTokenProto.WAITING_TO_SHOW;
-import static com.android.server.wm.WindowTokenProto.WINDOWS;
import static com.android.server.wm.WindowTokenProto.WINDOW_CONTAINER;
import android.annotation.CallSuper;
@@ -50,6 +50,7 @@
import android.view.SurfaceControl;
import android.view.WindowManager;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.server.policy.WindowManagerPolicy;
import com.android.server.protolog.common.ProtoLog;
@@ -99,7 +100,8 @@
private Configuration mLastReportedConfig;
private int mLastReportedDisplay = INVALID_DISPLAY;
- private final boolean mFromClientToken;
+ @VisibleForTesting
+ final boolean mFromClientToken;
/**
* Used to fix the transform of the token to be rotated to a rotation different than it's
@@ -180,13 +182,13 @@
WindowToken(WindowManagerService service, IBinder _token, int type, boolean persistOnEmpty,
DisplayContent dc, boolean ownerCanManageAppTokens) {
this(service, _token, type, persistOnEmpty, dc, ownerCanManageAppTokens,
- false /* roundedCornersOverlay */);
+ false /* roundedCornerOverlay */);
}
WindowToken(WindowManagerService service, IBinder _token, int type, boolean persistOnEmpty,
- DisplayContent dc, boolean ownerCanManageAppTokens, boolean fromClientToken) {
+ DisplayContent dc, boolean ownerCanManageAppTokens, boolean roundedCornerOverlay) {
this(service, _token, type, persistOnEmpty, dc, ownerCanManageAppTokens,
- false /* roundedCornersOverlay */, fromClientToken);
+ roundedCornerOverlay, false /* fromClientToken */);
}
WindowToken(WindowManagerService service, IBinder _token, int type, boolean persistOnEmpty,
@@ -539,15 +541,16 @@
final long token = proto.start(fieldId);
super.dumpDebug(proto, WINDOW_CONTAINER, logLevel);
proto.write(HASH_CODE, System.identityHashCode(this));
- for (int i = 0; i < mChildren.size(); i++) {
- final WindowState w = mChildren.get(i);
- w.dumpDebug(proto, WINDOWS, logLevel);
- }
proto.write(WAITING_TO_SHOW, waitingToShow);
proto.write(PAUSED, paused);
proto.end(token);
}
+ @Override
+ long getProtoFieldId() {
+ return WINDOW_TOKEN;
+ }
+
void dump(PrintWriter pw, String prefix, boolean dumpAll) {
super.dump(pw, prefix, dumpAll);
pw.print(prefix); pw.print("windows="); pw.println(mChildren);
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index c781a5a..74982c6 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -146,6 +146,7 @@
"android.hardware.light@2.0",
"android.hardware.power@1.0",
"android.hardware.power@1.1",
+ "android.hardware.power-cpp",
"android.hardware.power.stats@1.0",
"android.hardware.thermal@1.0",
"android.hardware.tv.cec@1.0",
diff --git a/services/core/jni/com_android_server_am_BatteryStatsService.cpp b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
index 9cbb58d..b08868e 100644
--- a/services/core/jni/com_android_server_am_BatteryStatsService.cpp
+++ b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
@@ -67,9 +67,9 @@
static bool wakeup_init = false;
static sem_t wakeup_sem;
-extern sp<IPowerV1_0> getPowerHalV1_0();
-extern sp<IPowerV1_1> getPowerHalV1_1();
-extern bool processPowerHalReturn(const Return<void> &ret, const char* functionName);
+extern sp<IPowerV1_0> getPowerHalHidlV1_0();
+extern sp<IPowerV1_1> getPowerHalHidlV1_1();
+extern bool processPowerHalReturn(bool isOk, const char* functionName);
extern sp<ISuspendControlService> getSuspendControl();
// Java methods used in getLowPowerStats
@@ -596,7 +596,7 @@
// The caller must be holding powerHalMutex.
static void getPowerHalLowPowerData(JNIEnv* env, jobject jrpmStats) {
- sp<IPowerV1_0> powerHalV1_0 = getPowerHalV1_0();
+ sp<IPowerV1_0> powerHalV1_0 = getPowerHalHidlV1_0();
if (powerHalV1_0 == nullptr) {
ALOGE("Power Hal not loaded");
return;
@@ -629,12 +629,12 @@
}
}
});
- if (!processPowerHalReturn(ret, "getPlatformLowPowerStats")) {
+ if (!processPowerHalReturn(ret.isOk(), "getPlatformLowPowerStats")) {
return;
}
// Trying to get IPower 1.1, this will succeed only for devices supporting 1.1
- sp<IPowerV1_1> powerHal_1_1 = getPowerHalV1_1();
+ sp<IPowerV1_1> powerHal_1_1 = getPowerHalHidlV1_1();
if (powerHal_1_1 == nullptr) {
// This device does not support IPower@1.1, exiting gracefully
return;
@@ -665,7 +665,7 @@
}
}
});
- processPowerHalReturn(ret, "getSubsystemLowPowerStats");
+ processPowerHalReturn(ret.isOk(), "getSubsystemLowPowerStats");
}
static jint getPowerHalPlatformData(JNIEnv* env, jobject outBuf) {
@@ -675,7 +675,7 @@
int total_added = -1;
{
- sp<IPowerV1_0> powerHalV1_0 = getPowerHalV1_0();
+ sp<IPowerV1_0> powerHalV1_0 = getPowerHalHidlV1_0();
if (powerHalV1_0 == nullptr) {
ALOGE("Power Hal not loaded");
return -1;
@@ -733,7 +733,7 @@
}
);
- if (!processPowerHalReturn(ret, "getPlatformLowPowerStats")) {
+ if (!processPowerHalReturn(ret.isOk(), "getPlatformLowPowerStats")) {
return -1;
}
}
@@ -753,7 +753,7 @@
{
// Trying to get 1.1, this will succeed only for devices supporting 1.1
- powerHal_1_1 = getPowerHalV1_1();
+ powerHal_1_1 = getPowerHalHidlV1_1();
if (powerHal_1_1 == nullptr) {
//This device does not support IPower@1.1, exiting gracefully
return 0;
@@ -820,7 +820,7 @@
}
);
- if (!processPowerHalReturn(ret, "getSubsystemLowPowerStats")) {
+ if (!processPowerHalReturn(ret.isOk(), "getSubsystemLowPowerStats")) {
return -1;
}
}
diff --git a/services/core/jni/com_android_server_pm_PackageManagerShellCommandDataLoader.cpp b/services/core/jni/com_android_server_pm_PackageManagerShellCommandDataLoader.cpp
index 6f9d012..29b2cd6 100644
--- a/services/core/jni/com_android_server_pm_PackageManagerShellCommandDataLoader.cpp
+++ b/services/core/jni/com_android_server_pm_PackageManagerShellCommandDataLoader.cpp
@@ -172,26 +172,25 @@
BlockHeader readHeader(std::span<uint8_t>& data);
-static inline int32_t readBEInt32(borrowed_fd fd) {
+static inline int32_t readLEInt32(borrowed_fd fd) {
int32_t result;
ReadFully(fd, &result, sizeof(result));
- result = int32_t(be32toh(result));
+ result = int32_t(le32toh(result));
return result;
}
static inline std::vector<char> readBytes(borrowed_fd fd) {
- int32_t size = readBEInt32(fd);
+ int32_t size = readLEInt32(fd);
std::vector<char> result(size);
ReadFully(fd, result.data(), size);
return result;
}
static inline int32_t skipIdSigHeaders(borrowed_fd fd) {
- readBEInt32(fd); // version
- readBytes(fd); // verityRootHash
- readBytes(fd); // v3Digest
- readBytes(fd); // pkcs7SignatureBlock
- return readBEInt32(fd); // size of the verity tree
+ readLEInt32(fd); // version
+ readBytes(fd); // hashingInfo
+ readBytes(fd); // signingInfo
+ return readLEInt32(fd); // size of the verity tree
}
static inline IncFsSize verityTreeSizeForFile(IncFsSize fileSize) {
@@ -365,13 +364,8 @@
}
}
void onDestroy() final {
- ALOGE("Sending EXIT to server.");
- sendRequest(mOutFd, EXIT);
// Make sure the receiver thread stopped.
CHECK(!mReceiverThread.joinable());
-
- mInFd.reset();
- mOutFd.reset();
}
// Installation.
@@ -569,13 +563,6 @@
// Streaming.
bool initStreaming(unique_fd inout) {
- mInFd.reset(dup(inout));
- mOutFd.reset(dup(inout));
- if (mInFd < 0 || mOutFd < 0) {
- ALOGE("Failed to dup FDs.");
- return false;
- }
-
mEventFd.reset(eventfd(0, EFD_CLOEXEC));
if (mEventFd < 0) {
ALOGE("Failed to create eventfd.");
@@ -584,7 +571,7 @@
// Awaiting adb handshake.
char okay_buf[OKAY.size()];
- if (!android::base::ReadFully(mInFd, okay_buf, OKAY.size())) {
+ if (!android::base::ReadFully(inout, okay_buf, OKAY.size())) {
ALOGE("Failed to receive OKAY. Abort.");
return false;
}
@@ -594,13 +581,23 @@
return false;
}
- mReceiverThread = std::thread([this]() { receiver(); });
+ {
+ std::lock_guard lock{mOutFdLock};
+ mOutFd.reset(::dup(inout));
+ if (mOutFd < 0) {
+ ALOGE("Failed to create streaming fd.");
+ }
+ }
+
+ mReceiverThread =
+ std::thread([this, io = std::move(inout)]() mutable { receiver(std::move(io)); });
ALOGI("Started streaming...");
return true;
}
// IFS callbacks.
void onPendingReads(dataloader::PendingReads pendingReads) final {
+ std::lock_guard lock{mOutFdLock};
CHECK(mIfs);
for (auto&& pendingRead : pendingReads) {
const android::dataloader::FileId& fileId = pendingRead.id;
@@ -626,12 +623,12 @@
}
}
- void receiver() {
+ void receiver(unique_fd inout) {
std::vector<uint8_t> data;
std::vector<IncFsDataBlock> instructions;
std::unordered_map<FileIdx, unique_fd> writeFds;
while (!mStopReceiving) {
- const int res = waitForDataOrSignal(mInFd, mEventFd);
+ const int res = waitForDataOrSignal(inout, mEventFd);
if (res == 0) {
continue;
}
@@ -641,10 +638,11 @@
break;
}
if (res == mEventFd) {
- ALOGE("Received stop signal. Exit.");
+ ALOGE("Received stop signal. Sending EXIT to server.");
+ sendRequest(inout, EXIT);
break;
}
- if (!readChunk(mInFd, data)) {
+ if (!readChunk(inout, data)) {
ALOGE("Failed to read a message. Abort.");
mStatusListener->reportStatus(DATA_LOADER_NO_CONNECTION);
break;
@@ -657,7 +655,7 @@
ALOGI("Stop signal received. Sending exit command (remaining bytes: %d).",
int(remainingData.size()));
- sendRequest(mOutFd, EXIT);
+ sendRequest(inout, EXIT);
mStopReceiving = true;
break;
}
@@ -700,6 +698,11 @@
writeInstructions(instructions);
}
writeInstructions(instructions);
+
+ {
+ std::lock_guard lock{mOutFdLock};
+ mOutFd.reset();
+ }
}
void writeInstructions(std::vector<IncFsDataBlock>& instructions) {
@@ -743,7 +746,7 @@
std::string mArgs;
android::dataloader::FilesystemConnectorPtr mIfs = nullptr;
android::dataloader::StatusListenerPtr mStatusListener = nullptr;
- android::base::unique_fd mInFd;
+ std::mutex mOutFdLock;
android::base::unique_fd mOutFd;
android::base::unique_fd mEventFd;
std::thread mReceiverThread;
diff --git a/services/core/jni/com_android_server_power_PowerManagerService.cpp b/services/core/jni/com_android_server_power_PowerManagerService.cpp
index 4e04348..fe05d4e 100644
--- a/services/core/jni/com_android_server_power_PowerManagerService.cpp
+++ b/services/core/jni/com_android_server_power_PowerManagerService.cpp
@@ -19,6 +19,9 @@
//#define LOG_NDEBUG 0
#include <android/hardware/power/1.1/IPower.h>
+#include <android/hardware/power/Boost.h>
+#include <android/hardware/power/IPower.h>
+#include <android/hardware/power/Mode.h>
#include <android/system/suspend/1.0/ISystemSuspend.h>
#include <android/system/suspend/ISuspendControlService.h>
#include <nativehelper/JNIHelp.h>
@@ -45,6 +48,8 @@
using android::hardware::Return;
using android::hardware::Void;
+using android::hardware::power::Boost;
+using android::hardware::power::Mode;
using android::hardware::power::V1_0::PowerHint;
using android::hardware::power::V1_0::Feature;
using android::String8;
@@ -54,6 +59,7 @@
using android::system::suspend::ISuspendControlService;
using IPowerV1_1 = android::hardware::power::V1_1::IPower;
using IPowerV1_0 = android::hardware::power::V1_0::IPower;
+using IPowerAidl = android::hardware::power::IPower;
namespace android {
@@ -66,11 +72,18 @@
// ----------------------------------------------------------------------------
static jobject gPowerManagerServiceObj;
-// Use getPowerHal* to retrieve a copy
-static sp<IPowerV1_0> gPowerHalV1_0_ = nullptr;
-static sp<IPowerV1_1> gPowerHalV1_1_ = nullptr;
-static bool gPowerHalExists = true;
+static sp<IPowerV1_0> gPowerHalHidlV1_0_ = nullptr;
+static sp<IPowerV1_1> gPowerHalHidlV1_1_ = nullptr;
+static sp<IPowerAidl> gPowerHalAidl_ = nullptr;
static std::mutex gPowerHalMutex;
+
+enum class HalVersion {
+ NONE,
+ HIDL_1_0,
+ HIDL_1_1,
+ AIDL,
+};
+
static nsecs_t gLastEventTime[USER_ACTIVITY_EVENT_LAST + 1];
// Throttling interval for user activity calls.
@@ -88,67 +101,225 @@
return false;
}
-// Check validity of current handle to the power HAL service, and call getService() if necessary.
+// Check validity of current handle to the power HAL service, and connect to it if necessary.
// The caller must be holding gPowerHalMutex.
-static void connectPowerHalLocked() {
- if (gPowerHalExists && gPowerHalV1_0_ == nullptr) {
- gPowerHalV1_0_ = IPowerV1_0::getService();
- if (gPowerHalV1_0_ != nullptr) {
- ALOGI("Loaded power HAL 1.0 service");
- // Try cast to powerHAL V1_1
- gPowerHalV1_1_ = IPowerV1_1::castFrom(gPowerHalV1_0_);
- if (gPowerHalV1_1_ == nullptr) {
- } else {
- ALOGI("Loaded power HAL 1.1 service");
- }
+static HalVersion connectPowerHalLocked() {
+ static bool gPowerHalHidlExists = true;
+ static bool gPowerHalAidlExists = true;
+ if (!gPowerHalHidlExists && !gPowerHalAidlExists) {
+ return HalVersion::NONE;
+ }
+ if (gPowerHalAidlExists) {
+ if (!gPowerHalAidl_) {
+ gPowerHalAidl_ = waitForVintfService<IPowerAidl>();
+ }
+ if (gPowerHalAidl_) {
+ ALOGI("Successfully connected to Power HAL AIDL service.");
+ return HalVersion::AIDL;
} else {
- ALOGI("Couldn't load power HAL service");
- gPowerHalExists = false;
+ gPowerHalAidlExists = false;
}
}
+ if (gPowerHalHidlExists && gPowerHalHidlV1_0_ == nullptr) {
+ gPowerHalHidlV1_0_ = IPowerV1_0::getService();
+ if (gPowerHalHidlV1_0_) {
+ ALOGI("Successfully connected to Power HAL HIDL 1.0 service.");
+ // Try cast to powerHAL HIDL V1_1
+ gPowerHalHidlV1_1_ = IPowerV1_1::castFrom(gPowerHalHidlV1_0_);
+ if (gPowerHalHidlV1_1_) {
+ ALOGI("Successfully connected to Power HAL HIDL 1.1 service.");
+ }
+ } else {
+ ALOGI("Couldn't load power HAL HIDL service");
+ gPowerHalHidlExists = false;
+ return HalVersion::NONE;
+ }
+ }
+ if (gPowerHalHidlV1_1_) {
+ return HalVersion::HIDL_1_1;
+ } else if (gPowerHalHidlV1_0_) {
+ return HalVersion::HIDL_1_0;
+ }
+ return HalVersion::NONE;
}
-// Retrieve a copy of PowerHAL V1_0
-sp<IPowerV1_0> getPowerHalV1_0() {
+// Retrieve a copy of PowerHAL HIDL V1_0
+sp<IPowerV1_0> getPowerHalHidlV1_0() {
std::lock_guard<std::mutex> lock(gPowerHalMutex);
- connectPowerHalLocked();
- return gPowerHalV1_0_;
+ HalVersion halVersion = connectPowerHalLocked();
+ if (halVersion == HalVersion::HIDL_1_0 || halVersion == HalVersion::HIDL_1_1) {
+ return gPowerHalHidlV1_0_;
+ }
+
+ return nullptr;
}
-// Retrieve a copy of PowerHAL V1_1
-sp<IPowerV1_1> getPowerHalV1_1() {
+// Retrieve a copy of PowerHAL HIDL V1_1
+sp<IPowerV1_1> getPowerHalHidlV1_1() {
std::lock_guard<std::mutex> lock(gPowerHalMutex);
- connectPowerHalLocked();
- return gPowerHalV1_1_;
+ if (connectPowerHalLocked() == HalVersion::HIDL_1_1) {
+ return gPowerHalHidlV1_1_;
+ }
+
+ return nullptr;
}
// Check if a call to a power HAL function failed; if so, log the failure and invalidate the
// current handle to the power HAL service.
-bool processPowerHalReturn(const Return<void> &ret, const char* functionName) {
- if (!ret.isOk()) {
+bool processPowerHalReturn(bool isOk, const char* functionName) {
+ if (!isOk) {
ALOGE("%s() failed: power HAL service not available.", functionName);
gPowerHalMutex.lock();
- gPowerHalV1_0_ = nullptr;
- gPowerHalV1_1_ = nullptr;
+ gPowerHalHidlV1_0_ = nullptr;
+ gPowerHalHidlV1_1_ = nullptr;
+ gPowerHalAidl_ = nullptr;
gPowerHalMutex.unlock();
}
- return ret.isOk();
+ return isOk;
}
-static void sendPowerHint(PowerHint hintId, uint32_t data) {
- sp<IPowerV1_1> powerHalV1_1 = getPowerHalV1_1();
- Return<void> ret;
- if (powerHalV1_1 != nullptr) {
- ret = powerHalV1_1->powerHintAsync(hintId, data);
- processPowerHalReturn(ret, "powerHintAsync");
- } else {
- sp<IPowerV1_0> powerHalV1_0 = getPowerHalV1_0();
- if (powerHalV1_0 != nullptr) {
- ret = powerHalV1_0->powerHint(hintId, data);
- processPowerHalReturn(ret, "powerHint");
+enum class HalSupport {
+ UNKNOWN = 0,
+ ON,
+ OFF,
+};
+
+static void setPowerBoostWithHandle(sp<IPowerAidl> handle, Boost boost, int32_t durationMs) {
+ // Android framework only sends boost upto DISPLAY_UPDATE_IMMINENT.
+ // Need to increase the array size if more boost supported.
+ static std::array<std::atomic<HalSupport>,
+ static_cast<int32_t>(Boost::DISPLAY_UPDATE_IMMINENT) + 1>
+ boostSupportedArray = {HalSupport::UNKNOWN};
+
+ // Quick return if boost is not supported by HAL
+ if (boost > Boost::DISPLAY_UPDATE_IMMINENT ||
+ boostSupportedArray[static_cast<int32_t>(boost)] == HalSupport::OFF) {
+ ALOGV("Skipped setPowerBoost %s because HAL doesn't support it", toString(boost).c_str());
+ return;
+ }
+
+ if (boostSupportedArray[static_cast<int32_t>(boost)] == HalSupport::UNKNOWN) {
+ bool isSupported = false;
+ handle->isBoostSupported(boost, &isSupported);
+ boostSupportedArray[static_cast<int32_t>(boost)] =
+ isSupported ? HalSupport::ON : HalSupport::OFF;
+ if (!isSupported) {
+ ALOGV("Skipped setPowerBoost %s because HAL doesn't support it",
+ toString(boost).c_str());
+ return;
}
}
+ auto ret = handle->setBoost(boost, durationMs);
+ processPowerHalReturn(ret.isOk(), "setPowerBoost");
+}
+
+static void setPowerBoost(Boost boost, int32_t durationMs) {
+ std::unique_lock<std::mutex> lock(gPowerHalMutex);
+ if (connectPowerHalLocked() != HalVersion::AIDL) {
+ ALOGV("Power HAL AIDL not available");
+ return;
+ }
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerBoostWithHandle(handle, boost, durationMs);
+}
+
+static void setPowerModeWithHandle(sp<IPowerAidl> handle, Mode mode, bool enabled) {
+ // Android framework only sends mode upto DISPLAY_INACTIVE.
+ // Need to increase the array if more mode supported.
+ static std::array<std::atomic<HalSupport>, static_cast<int32_t>(Mode::DISPLAY_INACTIVE) + 1>
+ modeSupportedArray = {HalSupport::UNKNOWN};
+
+ // Quick return if mode is not supported by HAL
+ if (mode > Mode::DISPLAY_INACTIVE ||
+ modeSupportedArray[static_cast<int32_t>(mode)] == HalSupport::OFF) {
+ ALOGV("Skipped setPowerMode %s because HAL doesn't support it", toString(mode).c_str());
+ return;
+ }
+
+ if (modeSupportedArray[static_cast<int32_t>(mode)] == HalSupport::UNKNOWN) {
+ bool isSupported = false;
+ handle->isModeSupported(mode, &isSupported);
+ modeSupportedArray[static_cast<int32_t>(mode)] =
+ isSupported ? HalSupport::ON : HalSupport::OFF;
+ if (!isSupported) {
+ ALOGV("Skipped setPowerMode %s because HAL doesn't support it", toString(mode).c_str());
+ return;
+ }
+ }
+
+ auto ret = handle->setMode(mode, enabled);
+ processPowerHalReturn(ret.isOk(), "setPowerMode");
+}
+
+static void setPowerMode(Mode mode, bool enabled) {
+ std::unique_lock<std::mutex> lock(gPowerHalMutex);
+ if (connectPowerHalLocked() != HalVersion::AIDL) {
+ ALOGV("Power HAL AIDL not available");
+ return;
+ }
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, mode, enabled);
+}
+
+static void sendPowerHint(PowerHint hintId, uint32_t data) {
+ std::unique_lock<std::mutex> lock(gPowerHalMutex);
+ switch (connectPowerHalLocked()) {
+ case HalVersion::NONE:
+ return;
+ case HalVersion::HIDL_1_0: {
+ sp<IPowerV1_0> handle = gPowerHalHidlV1_0_;
+ lock.unlock();
+ auto ret = handle->powerHint(hintId, data);
+ processPowerHalReturn(ret.isOk(), "powerHint");
+ break;
+ }
+ case HalVersion::HIDL_1_1: {
+ sp<IPowerV1_1> handle = gPowerHalHidlV1_1_;
+ lock.unlock();
+ auto ret = handle->powerHintAsync(hintId, data);
+ processPowerHalReturn(ret.isOk(), "powerHintAsync");
+ break;
+ }
+ case HalVersion::AIDL: {
+ if (hintId == PowerHint::INTERACTION) {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerBoostWithHandle(handle, Boost::INTERACTION, data);
+ break;
+ } else if (hintId == PowerHint::LAUNCH) {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, Mode::LAUNCH, static_cast<bool>(data));
+ break;
+ } else if (hintId == PowerHint::LOW_POWER) {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, Mode::LOW_POWER, static_cast<bool>(data));
+ break;
+ } else if (hintId == PowerHint::SUSTAINED_PERFORMANCE) {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, Mode::SUSTAINED_PERFORMANCE,
+ static_cast<bool>(data));
+ break;
+ } else if (hintId == PowerHint::VR_MODE) {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, Mode::VR, static_cast<bool>(data));
+ break;
+ } else {
+ ALOGE("Unsupported power hint: %s.", toString(hintId).c_str());
+ return;
+ }
+ }
+ default: {
+ ALOGE("Unknown power HAL state");
+ return;
+ }
+ }
SurfaceComposerClient::notifyPowerHint(static_cast<int32_t>(hintId));
}
@@ -253,14 +424,33 @@
}
static void nativeSetInteractive(JNIEnv* /* env */, jclass /* clazz */, jboolean enable) {
- sp<IPowerV1_0> powerHalV1_0 = getPowerHalV1_0();
- if (powerHalV1_0 != nullptr) {
- android::base::Timer t;
- Return<void> ret = powerHalV1_0->setInteractive(enable);
- processPowerHalReturn(ret, "setInteractive");
- if (t.duration() > 20ms) {
- ALOGD("Excessive delay in setInteractive(%s) while turning screen %s",
- enable ? "true" : "false", enable ? "on" : "off");
+ std::unique_lock<std::mutex> lock(gPowerHalMutex);
+ switch (connectPowerHalLocked()) {
+ case HalVersion::NONE:
+ return;
+ case HalVersion::HIDL_1_0:
+ FALLTHROUGH_INTENDED;
+ case HalVersion::HIDL_1_1: {
+ android::base::Timer t;
+ sp<IPowerV1_0> handle = gPowerHalHidlV1_0_;
+ lock.unlock();
+ auto ret = handle->setInteractive(enable);
+ processPowerHalReturn(ret.isOk(), "setInteractive");
+ if (t.duration() > 20ms) {
+ ALOGD("Excessive delay in setInteractive(%s) while turning screen %s",
+ enable ? "true" : "false", enable ? "on" : "off");
+ }
+ return;
+ }
+ case HalVersion::AIDL: {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, Mode::INTERACTIVE, enable);
+ return;
+ }
+ default: {
+ ALOGE("Unknown power HAL state");
+ return;
}
}
}
@@ -285,11 +475,39 @@
sendPowerHint(static_cast<PowerHint>(hintId), data);
}
+static void nativeSetPowerBoost(JNIEnv* /* env */, jclass /* clazz */, jint boost,
+ jint durationMs) {
+ setPowerBoost(static_cast<Boost>(boost), durationMs);
+}
+
+static void nativeSetPowerMode(JNIEnv* /* env */, jclass /* clazz */, jint mode, jboolean enabled) {
+ setPowerMode(static_cast<Mode>(mode), enabled);
+}
+
static void nativeSetFeature(JNIEnv* /* env */, jclass /* clazz */, jint featureId, jint data) {
- sp<IPowerV1_0> powerHalV1_0 = getPowerHalV1_0();
- if (powerHalV1_0 != nullptr) {
- Return<void> ret = powerHalV1_0->setFeature((Feature)featureId, static_cast<bool>(data));
- processPowerHalReturn(ret, "setFeature");
+ std::unique_lock<std::mutex> lock(gPowerHalMutex);
+ switch (connectPowerHalLocked()) {
+ case HalVersion::NONE:
+ return;
+ case HalVersion::HIDL_1_0:
+ FALLTHROUGH_INTENDED;
+ case HalVersion::HIDL_1_1: {
+ sp<IPowerV1_0> handle = gPowerHalHidlV1_0_;
+ lock.unlock();
+ auto ret = handle->setFeature(static_cast<Feature>(featureId), static_cast<bool>(data));
+ processPowerHalReturn(ret.isOk(), "setFeature");
+ return;
+ }
+ case HalVersion::AIDL: {
+ sp<IPowerAidl> handle = gPowerHalAidl_;
+ lock.unlock();
+ setPowerModeWithHandle(handle, Mode::DOUBLE_TAP_TO_WAKE, static_cast<bool>(data));
+ return;
+ }
+ default: {
+ ALOGE("Unknown power HAL state");
+ return;
+ }
}
}
@@ -317,6 +535,10 @@
(void*) nativeSetAutoSuspend },
{ "nativeSendPowerHint", "(II)V",
(void*) nativeSendPowerHint },
+ { "nativeSetPowerBoost", "(II)V",
+ (void*) nativeSetPowerBoost },
+ { "nativeSetPowerMode", "(IZ)V",
+ (void*) nativeSetPowerMode },
{ "nativeSetFeature", "(II)V",
(void*) nativeSetFeature },
};
diff --git a/services/core/jni/com_android_server_security_VerityUtils.cpp b/services/core/jni/com_android_server_security_VerityUtils.cpp
index be11b86..0277f16 100644
--- a/services/core/jni/com_android_server_security_VerityUtils.cpp
+++ b/services/core/jni/com_android_server_security_VerityUtils.cpp
@@ -25,17 +25,14 @@
#include <errno.h>
#include <fcntl.h>
#include <linux/fsverity.h>
+#include <linux/stat.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
-#include <type_traits>
-
#include <android-base/unique_fd.h>
-const int kSha256Bytes = 32;
-
namespace android {
namespace {
@@ -69,30 +66,28 @@
return 0;
}
-int measureFsverity(JNIEnv* env, jobject /* clazz */, jstring filePath) {
- using Storage = std::aligned_storage_t<sizeof(fsverity_digest) + kSha256Bytes>;
-
- Storage bytes;
- fsverity_digest *data = reinterpret_cast<fsverity_digest *>(&bytes);
- data->digest_size = kSha256Bytes; // the only input/output parameter
-
+// Returns whether the file has fs-verity enabled.
+// 0 if it is not present, 1 if is present, and -errno if there was an error.
+int statxForFsverity(JNIEnv *env, jobject /* clazz */, jstring filePath) {
ScopedUtfChars path(env, filePath);
- if (path.c_str() == nullptr) {
- return EINVAL;
+
+ struct statx out = {};
+ if (statx(AT_FDCWD, path.c_str(), 0 /* flags */, STATX_ALL, &out) != 0) {
+ return -errno;
}
- ::android::base::unique_fd rfd(open(path.c_str(), O_RDONLY | O_CLOEXEC));
- if (rfd.get() < 0) {
- return errno;
+
+ // Sanity check.
+ if ((out.stx_attributes_mask & STATX_ATTR_VERITY) == 0) {
+ ALOGE("Unexpected, STATX_ATTR_VERITY not supported by kernel");
+ return -ENOSYS;
}
- if (ioctl(rfd.get(), FS_IOC_MEASURE_VERITY, data) < 0) {
- return errno;
- }
- return 0;
+
+ return (out.stx_attributes & STATX_ATTR_VERITY) != 0;
}
const JNINativeMethod sMethods[] = {
- { "enableFsverityNative", "(Ljava/lang/String;[B)I", (void *)enableFsverity },
- { "measureFsverityNative", "(Ljava/lang/String;)I", (void *)measureFsverity },
+ {"enableFsverityNative", "(Ljava/lang/String;[B)I", (void *)enableFsverity},
+ {"statxForFsverityNative", "(Ljava/lang/String;)I", (void *)statxForFsverity},
};
} // namespace
diff --git a/services/core/jni/com_android_server_tv_GamepadKeys.h b/services/core/jni/com_android_server_tv_GamepadKeys.h
new file mode 100644
index 0000000..11fc903
--- /dev/null
+++ b/services/core/jni/com_android_server_tv_GamepadKeys.h
@@ -0,0 +1,79 @@
+#ifndef ANDROIDTVREMOTE_SERVICE_JNI_GAMEPAD_KEYS_H_
+#define ANDROIDTVREMOTE_SERVICE_JNI_GAMEPAD_KEYS_H_
+
+#include <linux/input.h>
+
+namespace android {
+
+// Follows the W3 spec for gamepad buttons and their corresponding mapping into
+// Linux keycodes. Note that gamepads are generally not very well standardized
+// and various controllers will result in different buttons. This mapping tries
+// to be reasonable.
+//
+// W3 Button spec: https://www.w3.org/TR/gamepad/#remapping
+//
+// Standard gamepad keycodes are added plus 2 additional buttons (e.g. Stadia
+// has "Assistant" and "Share", PS4 has the touchpad button).
+//
+// To generate this list, PS4, XBox, Stadia and Nintendo Switch Pro were tested.
+static const int GAMEPAD_KEY_CODES[19] = {
+ // Right-side buttons. A/B/X/Y or circle/triangle/square/X or similar
+ BTN_A, // "South", A, GAMEPAD and SOUTH have the same constant
+ BTN_B, // "East", BTN_B, BTN_EAST have the same constant
+ BTN_X, // "West", Note that this maps to X and NORTH in constants
+ BTN_Y, // "North", Note that this maps to Y and WEST in constants
+
+ BTN_TL, // "Left Bumper" / "L1" - Nintendo sends BTN_WEST instead
+ BTN_TR, // "Right Bumper" / "R1" - Nintendo sends BTN_Z instead
+
+ // For triggers, gamepads vary:
+ // - Stadia sends analog values over ABS_GAS/ABS_BRAKE and sends
+ // TriggerHappy3/4 as digital presses
+ // - PS4 and Xbox send analog values as ABS_Z/ABS_RZ
+ // - Nintendo Pro sends BTN_TL/BTN_TR (since bumpers behave differently)
+ // As placeholders we chose the stadia trigger-happy values since TL/TR are
+ // sent for bumper button presses
+ BTN_TRIGGER_HAPPY4, // "Left Trigger" / "L2"
+ BTN_TRIGGER_HAPPY3, // "Right Trigger" / "R2"
+
+ BTN_SELECT, // "Select/Back". Often "options" or similar
+ BTN_START, // "Start/forward". Often "hamburger" icon
+
+ BTN_THUMBL, // "Left Joystick Pressed"
+ BTN_THUMBR, // "Right Joystick Pressed"
+
+ // For DPads, gamepads generally only send axis changes
+ // on ABS_HAT0X and ABS_HAT0Y.
+ KEY_UP, // "Digital Pad up"
+ KEY_DOWN, // "Digital Pad down"
+ KEY_LEFT, // "Digital Pad left"
+ KEY_RIGHT, // "Digital Pad right"
+
+ BTN_MODE, // "Main button" (Stadia/PS/XBOX/Home)
+
+ BTN_TRIGGER_HAPPY1, // Extra button: "Assistant" for Stadia
+ BTN_TRIGGER_HAPPY2, // Extra button: "Share" for Stadia
+};
+
+// Defines information for an axis.
+struct Axis {
+ int number;
+ int rangeMin;
+ int rangeMax;
+};
+
+// List of all axes supported by a gamepad
+static const Axis GAMEPAD_AXES[] = {
+ {ABS_X, 0, 254}, // Left joystick X
+ {ABS_Y, 0, 254}, // Left joystick Y
+ {ABS_RX, 0, 254}, // Right joystick X
+ {ABS_RY, 0, 254}, // Right joystick Y
+ {ABS_Z, 0, 254}, // Left trigger
+ {ABS_RZ, 0, 254}, // Right trigger
+ {ABS_HAT0X, -1, 1}, // DPad X
+ {ABS_HAT0Y, -1, 1}, // DPad Y
+};
+
+} // namespace android
+
+#endif // ANDROIDTVREMOTE_SERVICE_JNI_GAMEPAD_KEYS_H_
diff --git a/services/core/jni/com_android_server_tv_TvKeys.h b/services/core/jni/com_android_server_tv_TvKeys.h
index 4895f34..7eacdf6 100644
--- a/services/core/jni/com_android_server_tv_TvKeys.h
+++ b/services/core/jni/com_android_server_tv_TvKeys.h
@@ -110,4 +110,4 @@
} // namespace android
-#endif // SERVICE_JNI_KEYS_H_
+#endif // ANDROIDTVREMOTE_SERVICE_JNI_KEYS_H_
diff --git a/services/core/jni/com_android_server_tv_TvUinputBridge.cpp b/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
index c832c18..0e96bd7 100644
--- a/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
+++ b/services/core/jni/com_android_server_tv_TvUinputBridge.cpp
@@ -16,6 +16,7 @@
#define LOG_TAG "TvRemote-native-uiBridge"
+#include "com_android_server_tv_GamepadKeys.h"
#include "com_android_server_tv_TvKeys.h"
#include "jni.h"
@@ -92,27 +93,156 @@
}
}
+static const int kInvalidFileDescriptor = -1;
+
+// Convenience class to manage an opened /dev/uinput device
+class UInputDescriptor {
+public:
+ UInputDescriptor() : mFd(kInvalidFileDescriptor) {
+ memset(&mUinputDescriptor, 0, sizeof(mUinputDescriptor));
+ }
+
+ // Auto-closes any open /dev/uinput descriptor unless detached.
+ ~UInputDescriptor();
+
+ // Open /dev/uinput and prepare to register
+ // the device with the given name and unique Id
+ bool Open(const char* name, const char* uniqueId);
+
+ // Checks if the current file descriptor is valid
+ bool IsValid() const { return mFd != kInvalidFileDescriptor; }
+
+ void EnableKey(int keyCode);
+
+ void EnableAxesEvents();
+ void EnableAxis(int axis, int rangeMin, int rangeMax);
+
+ bool Create();
+
+ // Detaches from the current file descriptor
+ // Returns the file descriptor for /dev/uniput
+ int Detach();
+
+private:
+ int mFd;
+ struct uinput_user_dev mUinputDescriptor;
+};
+
+UInputDescriptor::~UInputDescriptor() {
+ if (mFd != kInvalidFileDescriptor) {
+ close(mFd);
+ mFd = kInvalidFileDescriptor;
+ }
+}
+
+int UInputDescriptor::Detach() {
+ int fd = mFd;
+ mFd = kInvalidFileDescriptor;
+ return fd;
+}
+
+bool UInputDescriptor::Open(const char* name, const char* uniqueId) {
+ if (IsValid()) {
+ ALOGE("UInput device already open");
+ return false;
+ }
+
+ mFd = ::open("/dev/uinput", O_WRONLY | O_NDELAY);
+ if (mFd < 0) {
+ ALOGE("Cannot open /dev/uinput: %s.", strerror(errno));
+ mFd = kInvalidFileDescriptor;
+ return false;
+ }
+
+ // write device unique id to the phys property
+ ioctl(mFd, UI_SET_PHYS, uniqueId);
+
+ memset(&mUinputDescriptor, 0, sizeof(mUinputDescriptor));
+ strlcpy(mUinputDescriptor.name, name, UINPUT_MAX_NAME_SIZE);
+ mUinputDescriptor.id.version = 1;
+ mUinputDescriptor.id.bustype = BUS_VIRTUAL;
+
+ // All UInput devices we use process keys
+ ioctl(mFd, UI_SET_EVBIT, EV_KEY);
+
+ return true;
+}
+
+void UInputDescriptor::EnableKey(int keyCode) {
+ ioctl(mFd, UI_SET_KEYBIT, keyCode);
+}
+
+void UInputDescriptor::EnableAxesEvents() {
+ ioctl(mFd, UI_SET_EVBIT, EV_ABS);
+}
+
+void UInputDescriptor::EnableAxis(int axis, int rangeMin, int rangeMax) {
+ if ((axis < 0) || (axis >= NELEM(mUinputDescriptor.absmin))) {
+ ALOGE("Invalid axis number: %d", axis);
+ return;
+ }
+
+ if (ioctl(mFd, UI_SET_ABSBIT, axis) != 0) {
+ ALOGE("Failed to set absbit for %d", axis);
+ }
+
+ mUinputDescriptor.absmin[axis] = rangeMin;
+ mUinputDescriptor.absmax[axis] = rangeMax;
+ mUinputDescriptor.absfuzz[axis] = 0;
+ mUinputDescriptor.absflat[axis] = 0;
+}
+
+bool UInputDescriptor::Create() {
+ // register the input device
+ if (write(mFd, &mUinputDescriptor, sizeof(mUinputDescriptor)) != sizeof(mUinputDescriptor)) {
+ ALOGE("Cannot write uinput_user_dev to fd %d: %s.", mFd, strerror(errno));
+ return false;
+ }
+
+ if (ioctl(mFd, UI_DEV_CREATE) != 0) {
+ ALOGE("Unable to create uinput device: %s.", strerror(errno));
+ return false;
+ }
+
+ ALOGV("Created uinput device, fd=%d.", mFd);
+
+ return true;
+}
+
class NativeConnection {
public:
+ enum class ConnectionType {
+ kRemoteDevice,
+ kGamepadDevice,
+ };
+
~NativeConnection();
static NativeConnection* open(const char* name, const char* uniqueId,
int32_t width, int32_t height, int32_t maxPointerId);
+ static NativeConnection* openGamepad(const char* name, const char* uniqueId);
+
void sendEvent(int32_t type, int32_t code, int32_t value);
int32_t getMaxPointers() const { return mMaxPointers; }
+ ConnectionType getType() const { return mType; }
+
+ bool IsGamepad() const { return getType() == ConnectionType::kGamepadDevice; }
+
+ bool IsRemote() const { return getType() == ConnectionType::kRemoteDevice; }
+
private:
- NativeConnection(int fd, int32_t maxPointers);
+ NativeConnection(int fd, int32_t maxPointers, ConnectionType type);
const int mFd;
const int32_t mMaxPointers;
+ const ConnectionType mType;
};
-NativeConnection::NativeConnection(int fd, int32_t maxPointers) :
- mFd(fd), mMaxPointers(maxPointers) {
-}
+NativeConnection::NativeConnection(int fd, int32_t maxPointers, ConnectionType type)
+ : mFd(fd), mMaxPointers(maxPointers), mType(type) {}
NativeConnection::~NativeConnection() {
ALOGI("Un-Registering uinput device %d.", mFd);
@@ -125,44 +255,50 @@
ALOGI("Registering uinput device %s: touch pad size %dx%d, "
"max pointers %d.", name, width, height, maxPointers);
- int fd = ::open("/dev/uinput", O_WRONLY | O_NDELAY);
- if (fd < 0) {
- ALOGE("Cannot open /dev/uinput: %s.", strerror(errno));
- return nullptr;
- }
-
- struct uinput_user_dev uinp;
- memset(&uinp, 0, sizeof(struct uinput_user_dev));
- strlcpy(uinp.name, name, UINPUT_MAX_NAME_SIZE);
- uinp.id.version = 1;
- uinp.id.bustype = BUS_VIRTUAL;
-
- // initialize keymap
initKeysMap();
- // write device unique id to the phys property
- ioctl(fd, UI_SET_PHYS, uniqueId);
-
- // set the keys mapped
- ioctl(fd, UI_SET_EVBIT, EV_KEY);
- for (size_t i = 0; i < NELEM(KEYS); i++) {
- ioctl(fd, UI_SET_KEYBIT, KEYS[i].linuxKeyCode);
- }
-
- // register the input device
- if (write(fd, &uinp, sizeof(uinp)) != sizeof(uinp)) {
- ALOGE("Cannot write uinput_user_dev to fd %d: %s.", fd, strerror(errno));
- close(fd);
- return NULL;
- }
- if (ioctl(fd, UI_DEV_CREATE) != 0) {
- ALOGE("Unable to create uinput device: %s.", strerror(errno));
- close(fd);
+ UInputDescriptor descriptor;
+ if (!descriptor.Open(name, uniqueId)) {
return nullptr;
}
- ALOGV("Created uinput device, fd=%d.", fd);
- return new NativeConnection(fd, maxPointers);
+ // set the keys mapped
+ for (size_t i = 0; i < NELEM(KEYS); i++) {
+ descriptor.EnableKey(KEYS[i].linuxKeyCode);
+ }
+
+ if (!descriptor.Create()) {
+ return nullptr;
+ }
+
+ return new NativeConnection(descriptor.Detach(), maxPointers, ConnectionType::kRemoteDevice);
+}
+
+NativeConnection* NativeConnection::openGamepad(const char* name, const char* uniqueId) {
+ ALOGI("Registering uinput device %s: gamepad", name);
+
+ UInputDescriptor descriptor;
+ if (!descriptor.Open(name, uniqueId)) {
+ return nullptr;
+ }
+
+ // set the keys mapped for gamepads
+ for (size_t i = 0; i < NELEM(GAMEPAD_KEY_CODES); i++) {
+ descriptor.EnableKey(GAMEPAD_KEY_CODES[i]);
+ }
+
+ // define the axes that are required
+ descriptor.EnableAxesEvents();
+ for (size_t i = 0; i < NELEM(GAMEPAD_AXES); i++) {
+ const Axis& axis = GAMEPAD_AXES[i];
+ descriptor.EnableAxis(axis.number, axis.rangeMin, axis.rangeMax);
+ }
+
+ if (!descriptor.Create()) {
+ return nullptr;
+ }
+
+ return new NativeConnection(descriptor.Detach(), 0, ConnectionType::kGamepadDevice);
}
void NativeConnection::sendEvent(int32_t type, int32_t code, int32_t value) {
@@ -174,7 +310,6 @@
write(mFd, &iev, sizeof(iev));
}
-
static jlong nativeOpen(JNIEnv* env, jclass clazz,
jstring nameStr, jstring uniqueIdStr,
jint width, jint height, jint maxPointers) {
@@ -186,6 +321,14 @@
return reinterpret_cast<jlong>(connection);
}
+static jlong nativeGamepadOpen(JNIEnv* env, jclass clazz, jstring nameStr, jstring uniqueIdStr) {
+ ScopedUtfChars name(env, nameStr);
+ ScopedUtfChars uniqueId(env, uniqueIdStr);
+
+ NativeConnection* connection = NativeConnection::openGamepad(name.c_str(), uniqueId.c_str());
+ return reinterpret_cast<jlong>(connection);
+}
+
static void nativeClose(JNIEnv* env, jclass clazz, jlong ptr) {
NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
delete connection;
@@ -194,6 +337,12 @@
static void nativeSendKey(JNIEnv* env, jclass clazz, jlong ptr, jint keyCode, jboolean down) {
int32_t code = getLinuxKeyCode(keyCode);
NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+
+ if (connection->IsGamepad()) {
+ ALOGE("Invalid key even for a gamepad - need to send gamepad events");
+ return;
+ }
+
if (code != KEY_UNKNOWN) {
connection->sendEvent(EV_KEY, code, down ? 1 : 0);
} else {
@@ -201,10 +350,44 @@
}
}
+static void nativeSendGamepadKey(JNIEnv* env, jclass clazz, jlong ptr, jint keyIndex,
+ jboolean down) {
+ NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+
+ if (!connection->IsGamepad()) {
+ ALOGE("Invalid gamepad key for non-gamepad device");
+ return;
+ }
+
+ if ((keyIndex < 0) || (keyIndex >= NELEM(GAMEPAD_KEY_CODES))) {
+ ALOGE("Invalid gamepad key index: %d", keyIndex);
+ return;
+ }
+
+ connection->sendEvent(EV_KEY, GAMEPAD_KEY_CODES[keyIndex], down ? 1 : 0);
+}
+
+static void nativeSendGamepadAxisValue(JNIEnv* env, jclass clazz, jlong ptr, jint axis,
+ jint value) {
+ NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+
+ if (!connection->IsGamepad()) {
+ ALOGE("Invalid axis send for non-gamepad device");
+ return;
+ }
+
+ connection->sendEvent(EV_ABS, axis, value);
+}
+
static void nativeSendPointerDown(JNIEnv* env, jclass clazz, jlong ptr,
jint pointerId, jint x, jint y) {
NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+ if (connection->IsGamepad()) {
+ ALOGE("Invalid pointer down event for a gamepad.");
+ return;
+ }
+
int32_t slot = findSlot(pointerId);
if (slot == SLOT_UNKNOWN) {
slot = assignSlot(pointerId);
@@ -221,6 +404,11 @@
jint pointerId) {
NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
+ if (connection->IsGamepad()) {
+ ALOGE("Invalid pointer up event for a gamepad.");
+ return;
+ }
+
int32_t slot = findSlot(pointerId);
if (slot != SLOT_UNKNOWN) {
connection->sendEvent(EV_ABS, ABS_MT_SLOT, slot);
@@ -238,17 +426,34 @@
NativeConnection* connection = reinterpret_cast<NativeConnection*>(ptr);
// Clear keys.
- for (size_t i = 0; i < NELEM(KEYS); i++) {
- connection->sendEvent(EV_KEY, KEYS[i].linuxKeyCode, 0);
- }
+ if (connection->IsRemote()) {
+ for (size_t i = 0; i < NELEM(KEYS); i++) {
+ connection->sendEvent(EV_KEY, KEYS[i].linuxKeyCode, 0);
+ }
- // Clear pointers.
- int32_t slot = SLOT_UNKNOWN;
- for (int32_t i = 0; i < connection->getMaxPointers(); i++) {
- slot = findSlot(i);
- if (slot != SLOT_UNKNOWN) {
- connection->sendEvent(EV_ABS, ABS_MT_SLOT, slot);
- connection->sendEvent(EV_ABS, ABS_MT_TRACKING_ID, -1);
+ // Clear pointers.
+ int32_t slot = SLOT_UNKNOWN;
+ for (int32_t i = 0; i < connection->getMaxPointers(); i++) {
+ slot = findSlot(i);
+ if (slot != SLOT_UNKNOWN) {
+ connection->sendEvent(EV_ABS, ABS_MT_SLOT, slot);
+ connection->sendEvent(EV_ABS, ABS_MT_TRACKING_ID, -1);
+ }
+ }
+ } else {
+ for (size_t i = 0; i < NELEM(GAMEPAD_KEY_CODES); i++) {
+ connection->sendEvent(EV_KEY, GAMEPAD_KEY_CODES[i], 0);
+ }
+
+ for (size_t i = 0; i < NELEM(GAMEPAD_AXES); i++) {
+ const Axis& axis = GAMEPAD_AXES[i];
+ if ((axis.number == ABS_Z) || (axis.number == ABS_RZ)) {
+ // Mark triggers unpressed
+ connection->sendEvent(EV_ABS, axis.number, 0);
+ } else {
+ // Joysticks and dpad rests on center
+ connection->sendEvent(EV_ABS, axis.number, (axis.rangeMin + axis.rangeMax) / 2);
+ }
}
}
@@ -261,20 +466,16 @@
*/
static JNINativeMethod gUinputBridgeMethods[] = {
- { "nativeOpen", "(Ljava/lang/String;Ljava/lang/String;III)J",
- (void*)nativeOpen },
- { "nativeClose", "(J)V",
- (void*)nativeClose },
- { "nativeSendKey", "(JIZ)V",
- (void*)nativeSendKey },
- { "nativeSendPointerDown", "(JIII)V",
- (void*)nativeSendPointerDown },
- { "nativeSendPointerUp", "(JI)V",
- (void*)nativeSendPointerUp },
- { "nativeClear", "(J)V",
- (void*)nativeClear },
- { "nativeSendPointerSync", "(J)V",
- (void*)nativeSendPointerSync },
+ {"nativeOpen", "(Ljava/lang/String;Ljava/lang/String;III)J", (void*)nativeOpen},
+ {"nativeGamepadOpen", "(Ljava/lang/String;Ljava/lang/String;)J", (void*)nativeGamepadOpen},
+ {"nativeClose", "(J)V", (void*)nativeClose},
+ {"nativeSendKey", "(JIZ)V", (void*)nativeSendKey},
+ {"nativeSendPointerDown", "(JIII)V", (void*)nativeSendPointerDown},
+ {"nativeSendPointerUp", "(JI)V", (void*)nativeSendPointerUp},
+ {"nativeClear", "(J)V", (void*)nativeClear},
+ {"nativeSendPointerSync", "(J)V", (void*)nativeSendPointerSync},
+ {"nativeSendGamepadKey", "(JIZ)V", (void*)nativeSendGamepadKey},
+ {"nativeSendGamepadAxisValue", "(JII)V", (void*)nativeSendGamepadAxisValue},
};
int register_android_server_tv_TvUinputBridge(JNIEnv* env) {
diff --git a/services/core/xsd/platform-compat-config.xsd b/services/core/xsd/platform-compat-config.xsd
index a70568f..5a4c682 100644
--- a/services/core/xsd/platform-compat-config.xsd
+++ b/services/core/xsd/platform-compat-config.xsd
@@ -27,6 +27,7 @@
<xs:attribute type="xs:long" name="id" use="required"/>
<xs:attribute type="xs:string" name="name" use="required"/>
<xs:attribute type="xs:boolean" name="disabled"/>
+ <xs:attribute type="xs:boolean" name="loggingOnly"/>
<xs:attribute type="xs:int" name="enableAfterTargetSdk"/>
<xs:attribute type="xs:string" name="description"/>
</xs:extension>
diff --git a/services/core/xsd/platform-compat-schema/current.txt b/services/core/xsd/platform-compat-schema/current.txt
index 3a33f63..7def58d 100644
--- a/services/core/xsd/platform-compat-schema/current.txt
+++ b/services/core/xsd/platform-compat-schema/current.txt
@@ -7,12 +7,14 @@
method public boolean getDisabled();
method public int getEnableAfterTargetSdk();
method public long getId();
+ method public boolean getLoggingOnly();
method public String getName();
method public String getValue();
method public void setDescription(String);
method public void setDisabled(boolean);
method public void setEnableAfterTargetSdk(int);
method public void setId(long);
+ method public void setLoggingOnly(boolean);
method public void setName(String);
method public void setValue(String);
}
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index c58eae1..fc9044a 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -86,6 +86,7 @@
import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
+import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
import static android.provider.Settings.Global.PRIVATE_DNS_MODE;
import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER;
import static android.provider.Telephony.Carriers.DPC_URI;
@@ -148,10 +149,6 @@
import android.app.admin.SystemUpdateInfo;
import android.app.admin.SystemUpdatePolicy;
import android.app.backup.IBackupManager;
-import android.app.timedetector.ManualTimeSuggestion;
-import android.app.timedetector.TimeDetector;
-import android.app.timezonedetector.ManualTimeZoneSuggestion;
-import android.app.timezonedetector.TimeZoneDetector;
import android.app.trust.TrustManager;
import android.app.usage.UsageStatsManagerInternal;
import android.compat.annotation.ChangeId;
@@ -396,6 +393,7 @@
private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
+ private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY;
private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION =
"com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
@@ -789,7 +787,7 @@
List<String> mLockTaskPackages = new ArrayList<>();
// List of packages protected by device owner
- List<String> mProtectedPackages = new ArrayList<>();
+ List<String> mUserControlDisabledPackages = new ArrayList<>();
// Bitfield of feature flags to be enabled during LockTask mode.
// We default on the power button menu, in order to be consistent with pre-P behaviour.
@@ -1202,7 +1200,7 @@
// Whether the admin explicitly requires personal apps to be suspended
boolean mSuspendPersonalApps = false;
// Maximum time the profile owned by this admin can be off.
- long mProfileMaximumTimeOff = 0;
+ long mProfileMaximumTimeOffMillis = 0;
// Time by which the profile should be turned on according to System.currentTimeMillis().
long mProfileOffDeadline = 0;
@@ -1443,10 +1441,11 @@
if (mSuspendPersonalApps) {
writeAttributeValueToXml(out, TAG_SUSPEND_PERSONAL_APPS, mSuspendPersonalApps);
}
- if (mProfileMaximumTimeOff != 0) {
- writeAttributeValueToXml(out, TAG_PROFILE_MAXIMUM_TIME_OFF, mProfileMaximumTimeOff);
+ if (mProfileMaximumTimeOffMillis != 0) {
+ writeAttributeValueToXml(out, TAG_PROFILE_MAXIMUM_TIME_OFF,
+ mProfileMaximumTimeOffMillis);
}
- if (mProfileMaximumTimeOff != 0) {
+ if (mProfileMaximumTimeOffMillis != 0) {
writeAttributeValueToXml(out, TAG_PROFILE_OFF_DEADLINE, mProfileOffDeadline);
}
if (!TextUtils.isEmpty(mAlwaysOnVpnPackage)) {
@@ -1695,7 +1694,7 @@
mSuspendPersonalApps = Boolean.parseBoolean(
parser.getAttributeValue(null, ATTR_VALUE));
} else if (TAG_PROFILE_MAXIMUM_TIME_OFF.equals(tag)) {
- mProfileMaximumTimeOff =
+ mProfileMaximumTimeOffMillis =
Long.parseLong(parser.getAttributeValue(null, ATTR_VALUE));
} else if (TAG_PROFILE_OFF_DEADLINE.equals(tag)) {
mProfileOffDeadline =
@@ -1933,8 +1932,8 @@
pw.println(mCrossProfilePackages);
pw.print("mSuspendPersonalApps=");
pw.println(mSuspendPersonalApps);
- pw.print("mProfileMaximumTimeOff=");
- pw.println(mProfileMaximumTimeOff);
+ pw.print("mProfileMaximumTimeOffMillis=");
+ pw.println(mProfileMaximumTimeOffMillis);
pw.print("mProfileOffDeadline=");
pw.println(mProfileOffDeadline);
pw.print("mAlwaysOnVpnPackage=");
@@ -2118,14 +2117,6 @@
return mContext.getSystemService(AlarmManager.class);
}
- TimeDetector getTimeDetector() {
- return mContext.getSystemService(TimeDetector.class);
- }
-
- TimeZoneDetector getTimeZoneDetector() {
- return mContext.getSystemService(TimeZoneDetector.class);
- }
-
ConnectivityManager getConnectivityManager() {
return mContext.getSystemService(ConnectivityManager.class);
}
@@ -3551,8 +3542,8 @@
out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
}
- for (int i = 0, size = policy.mProtectedPackages.size(); i < size; i++) {
- String packageName = policy.mProtectedPackages.get(i);
+ for (int i = 0, size = policy.mUserControlDisabledPackages.size(); i < size; i++) {
+ String packageName = policy.mUserControlDisabledPackages.get(i);
out.startTag(null, TAG_PROTECTED_PACKAGES);
out.attribute(null, ATTR_NAME, packageName);
out.endTag(null, TAG_PROTECTED_PACKAGES);
@@ -3677,7 +3668,7 @@
policy.mAdminMap.clear();
policy.mAffiliationIds.clear();
policy.mOwnerInstalledCaCerts.clear();
- policy.mProtectedPackages.clear();
+ policy.mUserControlDisabledPackages.clear();
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
@@ -3779,7 +3770,8 @@
} else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
} else if (TAG_PROTECTED_PACKAGES.equals(tag)) {
- policy.mProtectedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
+ policy.mUserControlDisabledPackages.add(
+ parser.getAttributeValue(null, ATTR_NAME));
} else if (TAG_APPS_SUSPENDED.equals(tag)) {
policy.mAppsSuspended =
Boolean.parseBoolean(parser.getAttributeValue(null, ATTR_VALUE));
@@ -3814,7 +3806,7 @@
updateMaximumTimeToLockLocked(userHandle);
updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
- updateProtectedPackagesLocked(policy.mProtectedPackages);
+ updateUserControlDisabledPackagesLocked(policy.mUserControlDisabledPackages);
if (policy.mStatusBarDisabled) {
setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
}
@@ -3840,7 +3832,7 @@
}
}
- private void updateProtectedPackagesLocked(List<String> packages) {
+ private void updateUserControlDisabledPackagesLocked(List<String> packages) {
mInjector.getPackageManagerInternal().setDeviceOwnerProtectedPackages(packages);
}
@@ -5886,6 +5878,14 @@
}
}
+ private void enforceNetworkStackOrProfileOrDeviceOwner(ComponentName who) {
+ if (mContext.checkCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)
+ == PackageManager.PERMISSION_GRANTED) {
+ return;
+ }
+ enforceProfileOrDeviceOwner(who);
+ }
+
private void enforceDeviceOwnerOrProfileOwnerOnOrganizationOwnedDevice(ComponentName who) {
synchronized (getLockObject()) {
getActiveAdminForCallerLocked(
@@ -6882,7 +6882,7 @@
@Override
public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
- enforceProfileOrDeviceOwner(admin);
+ enforceNetworkStackOrProfileOrDeviceOwner(admin);
final int userId = mInjector.userHandleGetCallingUserId();
return mInjector.binderWithCleanCallingIdentity(
@@ -7798,7 +7798,7 @@
* Set whether auto time is enabled on the device.
*/
@Override
- public void setAutoTime(ComponentName who, boolean enabled) {
+ public void setAutoTimeEnabled(ComponentName who, boolean enabled) {
if (!mHasFeature) {
return;
}
@@ -7819,7 +7819,7 @@
* Returns whether auto time is used on the device or not.
*/
@Override
- public boolean getAutoTime(ComponentName who) {
+ public boolean getAutoTimeEnabled(ComponentName who) {
if (!mHasFeature) {
return false;
}
@@ -7833,7 +7833,7 @@
* Set whether auto time zone is enabled on the device.
*/
@Override
- public void setAutoTimeZone(ComponentName who, boolean enabled) {
+ public void setAutoTimeZoneEnabled(ComponentName who, boolean enabled) {
if (!mHasFeature) {
return;
}
@@ -7854,7 +7854,7 @@
* Returns whether auto time zone is used on the device or not.
*/
@Override
- public boolean getAutoTimeZone(ComponentName who) {
+ public boolean getAutoTimeZoneEnabled(ComponentName who) {
if (!mHasFeature) {
return false;
}
@@ -8832,8 +8832,8 @@
policy.mLockTaskPackages.clear();
updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId);
policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
- policy.mProtectedPackages.clear();
- updateProtectedPackagesLocked(policy.mProtectedPackages);
+ policy.mUserControlDisabledPackages.clear();
+ updateUserControlDisabledPackagesLocked(policy.mUserControlDisabledPackages);
saveSettingsLocked(userId);
try {
@@ -9586,7 +9586,8 @@
pw.println();
pw.increaseIndent();
pw.print("mPasswordOwner="); pw.println(policy.mPasswordOwner);
- pw.print("mProtectedPackages="); pw.println(policy.mProtectedPackages);
+ pw.print("mUserControlDisabledPackages=");
+ pw.println(policy.mUserControlDisabledPackages);
pw.print("mAppsSuspended="); pw.println(policy.mAppsSuspended);
pw.decreaseIndent();
}
@@ -11730,15 +11731,11 @@
if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
return false;
}
- ManualTimeSuggestion manualTimeSuggestion = TimeDetector.createManualTimeSuggestion(
- millis, "DevicePolicyManagerService: setTime");
- mInjector.binderWithCleanCallingIdentity(
- () -> mInjector.getTimeDetector().suggestManualTime(manualTimeSuggestion));
-
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_TIME)
.setAdmin(who)
.write();
+ mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
return true;
}
@@ -11750,11 +11747,8 @@
if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
return false;
}
- ManualTimeZoneSuggestion manualTimeZoneSuggestion =
- TimeZoneDetector.createManualTimeZoneSuggestion(
- timeZone, "DevicePolicyManagerService: setTimeZone");
mInjector.binderWithCleanCallingIdentity(() ->
- mInjector.getTimeZoneDetector().suggestManualTimeZone(manualTimeZoneSuggestion));
+ mInjector.getAlarmManager().setTimeZone(timeZone));
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_TIME_ZONE)
@@ -15568,39 +15562,39 @@
}
@Override
- public void setProtectedPackages(ComponentName who, List<String> packages) {
+ public void setUserControlDisabledPackages(ComponentName who, List<String> packages) {
Preconditions.checkNotNull(who, "ComponentName is null");
Preconditions.checkNotNull(packages, "packages is null");
enforceDeviceOwner(who);
synchronized (getLockObject()) {
final int userHandle = mInjector.userHandleGetCallingUserId();
- setProtectedPackagesLocked(userHandle, packages);
+ setUserControlDisabledPackagesLocked(userHandle, packages);
DevicePolicyEventLogger
- .createEvent(DevicePolicyEnums.SET_PACKAGES_PROTECTED)
+ .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
.setAdmin(who)
.setStrings(packages.toArray(new String[packages.size()]))
.write();
}
}
- private void setProtectedPackagesLocked(int userHandle, List<String> packages) {
+ private void setUserControlDisabledPackagesLocked(int userHandle, List<String> packages) {
final DevicePolicyData policy = getUserData(userHandle);
- policy.mProtectedPackages = packages;
+ policy.mUserControlDisabledPackages = packages;
// Store the settings persistently.
saveSettingsLocked(userHandle);
- updateProtectedPackagesLocked(packages);
+ updateUserControlDisabledPackagesLocked(packages);
}
@Override
- public List<String> getProtectedPackages(ComponentName who) {
+ public List<String> getUserControlDisabledPackages(ComponentName who) {
Preconditions.checkNotNull(who, "ComponentName is null");
enforceDeviceOwner(who);
final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
synchronized (getLockObject()) {
- final List<String> packages = getUserData(userHandle).mProtectedPackages;
+ final List<String> packages = getUserData(userHandle).mUserControlDisabledPackages;
return packages == null ? Collections.EMPTY_LIST : packages;
}
}
@@ -15735,18 +15729,18 @@
}
boolean shouldSaveSettings = false;
if (profileOwner.mProfileOffDeadline != 0
- && (profileOwner.mProfileMaximumTimeOff == 0 || unlocked)) {
+ && (profileOwner.mProfileMaximumTimeOffMillis == 0 || unlocked)) {
// There is a deadline but either there is no policy or the profile is unlocked -> clear
// the deadline.
Slog.i(LOG_TAG, "Profile off deadline is reset to zero");
profileOwner.mProfileOffDeadline = 0;
shouldSaveSettings = true;
} else if (profileOwner.mProfileOffDeadline == 0
- && (profileOwner.mProfileMaximumTimeOff != 0 && !unlocked)) {
+ && (profileOwner.mProfileMaximumTimeOffMillis != 0 && !unlocked)) {
// There profile is locked and there is a policy, but the deadline is not set -> set the
// deadline.
Slog.i(LOG_TAG, "Profile off deadline is set.");
- profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOff;
+ profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis;
shouldSaveSettings = true;
}
@@ -15847,7 +15841,7 @@
}
@Override
- public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMs) {
+ public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) {
final int userId = mInjector.userHandleGetCallingUserId();
synchronized (getLockObject()) {
final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
@@ -15856,10 +15850,16 @@
// DO shouldn't be able to use this method.
enforceProfileOwnerOfOrganizationOwnedDevice(admin);
enforceHandlesCheckPolicyComplianceIntent(userId, admin.info.getPackageName());
- if (admin.mProfileMaximumTimeOff == timeoutMs) {
+ Preconditions.checkArgument(timeoutMillis >= 0, "Timeout must be non-negative.");
+ // Ensure the timeout is long enough to avoid having bad user experience.
+ if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD
+ && !isAdminTestOnlyLocked(who, userId)) {
+ timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD;
+ }
+ if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) {
return;
}
- admin.mProfileMaximumTimeOff = timeoutMs;
+ admin.mProfileMaximumTimeOffMillis = timeoutMillis;
saveSettingsLocked(userId);
}
@@ -15869,7 +15869,7 @@
DevicePolicyEventLogger
.createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF)
.setAdmin(who)
- .setTimePeriod(timeoutMs)
+ .setTimePeriod(timeoutMillis)
.write();
}
@@ -15893,7 +15893,7 @@
false /* parent */);
// DO shouldn't be able to use this method.
enforceProfileOwnerOfOrganizationOwnedDevice(admin);
- return admin.mProfileMaximumTimeOff;
+ return admin.mProfileMaximumTimeOffMillis;
}
}
diff --git a/services/incremental/BinderIncrementalService.cpp b/services/incremental/BinderIncrementalService.cpp
index 3fcb57a..2dbbc5a 100644
--- a/services/incremental/BinderIncrementalService.cpp
+++ b/services/incremental/BinderIncrementalService.cpp
@@ -178,15 +178,9 @@
nfp.size = params.size;
nfp.metadata = {(const char*)params.metadata.data(), (IncFsSize)params.metadata.size()};
if (!params.signature) {
- nfp.verification = {};
+ nfp.signature = {};
} else {
- nfp.verification.hashAlgorithm = IncFsHashAlgortithm(params.signature->hashAlgorithm);
- nfp.verification.rootHash = {(const char*)params.signature->rootHash.data(),
- (IncFsSize)params.signature->rootHash.size()};
- nfp.verification.additionalData = {(const char*)params.signature->additionalData.data(),
- (IncFsSize)params.signature->additionalData.size()};
- nfp.verification.signature = {(const char*)params.signature->signature.data(),
- (IncFsSize)params.signature->signature.size()};
+ nfp.signature = {(const char*)params.signature->data(), (IncFsSize)params.signature->size()};
}
return {0, id, nfp};
}
diff --git a/services/incremental/BinderIncrementalService.h b/services/incremental/BinderIncrementalService.h
index 4075da6..28613e1 100644
--- a/services/incremental/BinderIncrementalService.h
+++ b/services/incremental/BinderIncrementalService.h
@@ -31,7 +31,7 @@
BinderIncrementalService(const sp<IServiceManager>& sm);
static BinderIncrementalService* start();
- static const char16_t* getServiceName() { return u"incremental_service"; }
+ static const char16_t* getServiceName() { return u"incremental"; }
status_t dump(int fd, const Vector<String16>& args) final;
void onSystemReady();
diff --git a/services/incremental/IncrementalService.cpp b/services/incremental/IncrementalService.cpp
index 2426e8f..7275936 100644
--- a/services/incremental/IncrementalService.cpp
+++ b/services/incremental/IncrementalService.cpp
@@ -28,6 +28,7 @@
#include <androidfw/ZipFileRO.h>
#include <androidfw/ZipUtils.h>
#include <binder/BinderService.h>
+#include <binder/Nullable.h>
#include <binder/ParcelFileDescriptor.h>
#include <binder/Status.h>
#include <sys/stat.h>
@@ -917,19 +918,23 @@
}
bool IncrementalService::startLoading(StorageId storage) const {
- const auto ifs = getIfs(storage);
- if (!ifs) {
- return false;
- }
- std::unique_lock l(ifs->lock);
- if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
- if (ifs->dataLoaderReady.wait_for(l, Seconds(5)) == std::cv_status::timeout) {
- LOG(ERROR) << "Timeout waiting for data loader to be ready";
+ {
+ std::unique_lock l(mLock);
+ const auto& ifs = getIfsLocked(storage);
+ if (!ifs) {
return false;
}
+ if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
+ ifs->dataLoaderStartRequested = true;
+ return true;
+ }
}
+ return startDataLoader(storage);
+}
+
+bool IncrementalService::startDataLoader(MountId mountId) const {
sp<IDataLoader> dataloader;
- auto status = mDataLoaderManager->getDataLoader(ifs->mountId, &dataloader);
+ auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
if (!status.isOk()) {
return false;
}
@@ -1065,15 +1070,9 @@
}
return true; // eventually...
}
- if (base::GetBoolProperty("incremental.skip_loader", false)) {
- LOG(INFO) << "Skipped data loader because of incremental.skip_loader property";
- std::unique_lock l(ifs.lock);
- ifs.savedDataLoaderParams.reset();
- return true;
- }
std::unique_lock l(ifs.lock);
- if (ifs.dataLoaderStatus == IDataLoaderStatusListener::DATA_LOADER_CREATED) {
+ if (ifs.dataLoaderStatus != -1) {
LOG(INFO) << "Skipped data loader preparation because it already exists";
return true;
}
@@ -1085,7 +1084,7 @@
return false;
}
FileSystemControlParcel fsControlParcel;
- fsControlParcel.incremental = std::make_unique<IncrementalFileSystemControlParcel>();
+ fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd)));
fsControlParcel.incremental->pendingReads.reset(
base::unique_fd(::dup(ifs.control.pendingReads)));
@@ -1156,7 +1155,7 @@
// Create new lib file without signature info
incfs::NewFileParams libFileParams{};
libFileParams.size = uncompressedLen;
- libFileParams.verification.hashAlgorithm = INCFS_HASH_NONE;
+ libFileParams.signature = {};
// Metadata of the new lib file is its relative path
IncFsSpan libFileMetadata;
libFileMetadata.data = targetLibPath.c_str();
@@ -1226,30 +1225,42 @@
externalListener->onStatusChanged(mountId, newStatus);
}
- std::unique_lock l(incrementalService.mLock);
- const auto& ifs = incrementalService.getIfsLocked(mountId);
- if (!ifs) {
- LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
- << mountId;
- return binder::Status::ok();
+ bool startRequested = false;
+ {
+ std::unique_lock l(incrementalService.mLock);
+ const auto& ifs = incrementalService.getIfsLocked(mountId);
+ if (!ifs) {
+ LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
+ << mountId;
+ return binder::Status::ok();
+ }
+ ifs->dataLoaderStatus = newStatus;
+
+ if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
+ ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
+ incrementalService.deleteStorageLocked(*ifs, std::move(l));
+ return binder::Status::ok();
+ }
+
+ startRequested = ifs->dataLoaderStartRequested;
}
- ifs->dataLoaderStatus = newStatus;
+
switch (newStatus) {
case IDataLoaderStatusListener::DATA_LOADER_NO_CONNECTION: {
// TODO(b/150411019): handle data loader connection loss
break;
}
case IDataLoaderStatusListener::DATA_LOADER_CONNECTION_OK: {
- ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STARTED;
+ // TODO(b/150411019): handle data loader connection loss
break;
}
case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
- ifs->dataLoaderReady.notify_one();
+ if (startRequested) {
+ incrementalService.startDataLoader(mountId);
+ }
break;
}
case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
- ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
- incrementalService.deleteStorageLocked(*ifs, std::move(l));
break;
}
case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
diff --git a/services/incremental/IncrementalService.h b/services/incremental/IncrementalService.h
index 8ff441b..406b32e 100644
--- a/services/incremental/IncrementalService.h
+++ b/services/incremental/IncrementalService.h
@@ -170,7 +170,7 @@
std::optional<DataLoaderParamsParcel> savedDataLoaderParams;
std::atomic<int> nextStorageDirNo{0};
std::atomic<int> dataLoaderStatus = -1;
- std::condition_variable dataLoaderReady;
+ bool dataLoaderStartRequested = false;
TimePoint connectionLostTime = TimePoint();
const IncrementalService& incrementalService;
@@ -208,6 +208,8 @@
bool prepareDataLoader(IncFsMount& ifs, DataLoaderParamsParcel* params = nullptr,
const DataLoaderStatusListener* externalListener = nullptr);
+ bool startDataLoader(MountId mountId) const;
+
BindPathMap::const_iterator findStorageLocked(std::string_view path) const;
StorageId findStorageId(std::string_view path) const;
diff --git a/services/net/Android.bp b/services/net/Android.bp
index dbc2df8..c54102f 100644
--- a/services/net/Android.bp
+++ b/services/net/Android.bp
@@ -20,6 +20,44 @@
],
}
+// Version of services.net for usage by the wifi mainline module.
+// Note: This is compiled against module_current.
+// TODO(b/145825329): This should be moved to networkstack-client,
+// with dependencies moved to frameworks/libs/net right.
+java_library {
+ name: "services.net-module-wifi",
+ srcs: [
+ ":framework-services-net-module-wifi-shared-srcs",
+ ":net-module-utils-srcs",
+ "java/android/net/ip/IpClientCallbacks.java",
+ "java/android/net/ip/IpClientManager.java",
+ "java/android/net/ip/IpClientUtil.java",
+ "java/android/net/util/KeepalivePacketDataUtil.java",
+ "java/android/net/util/NetworkConstants.java",
+ "java/android/net/IpMemoryStore.java",
+ "java/android/net/NetworkMonitorManager.java",
+ "java/android/net/TcpKeepalivePacketData.java",
+ ],
+ sdk_version: "module_current",
+ libs: [
+ "unsupportedappusage",
+ ],
+ static_libs: [
+ "dnsresolver_aidl_interface-V2-java",
+ "netd_aidl_interface-unstable-java",
+ "netlink-client",
+ "networkstack-client",
+ "net-utils-services-common",
+ ],
+ apex_available: [
+ "com.android.wifi",
+ ],
+ visibility: [
+ "//frameworks/opt/net/wifi/service",
+ "//frameworks/opt/net/wifi/tests/wifitests",
+ ],
+}
+
filegroup {
name: "services-tethering-shared-srcs",
srcs: [
diff --git a/services/net/java/android/net/IpMemoryStore.java b/services/net/java/android/net/IpMemoryStore.java
index dcefb53..8df2e0d 100644
--- a/services/net/java/android/net/IpMemoryStore.java
+++ b/services/net/java/android/net/IpMemoryStore.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.content.Context;
+import android.net.networkstack.ModuleNetworkStackClient;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -41,7 +42,7 @@
super(context);
mService = new CompletableFuture<>();
mTailNode = new AtomicReference<CompletableFuture<IIpMemoryStore>>(mService);
- getNetworkStackClient().fetchIpMemoryStore(
+ getModuleNetworkStackClient(context).fetchIpMemoryStore(
new IIpMemoryStoreCallbacks.Stub() {
@Override
public void onIpMemoryStoreFetched(@NonNull final IIpMemoryStore memoryStore) {
@@ -85,8 +86,8 @@
}
@VisibleForTesting
- protected NetworkStackClient getNetworkStackClient() {
- return NetworkStackClient.getInstance();
+ protected ModuleNetworkStackClient getModuleNetworkStackClient(Context context) {
+ return ModuleNetworkStackClient.getInstance(context);
}
/** Gets an instance of the memory store */
diff --git a/services/net/java/android/net/TcpKeepalivePacketData.java b/services/net/java/android/net/TcpKeepalivePacketData.java
index aad75ae..fcf3a56 100644
--- a/services/net/java/android/net/TcpKeepalivePacketData.java
+++ b/services/net/java/android/net/TcpKeepalivePacketData.java
@@ -74,6 +74,19 @@
ipTtl = tcpDetails.ttl;
}
+ private TcpKeepalivePacketData(final InetAddress srcAddress, int srcPort,
+ final InetAddress dstAddress, int dstPort, final byte[] data, int tcpSeq,
+ int tcpAck, int tcpWnd, int tcpWndScale, int ipTos, int ipTtl)
+ throws InvalidPacketException {
+ super(srcAddress, srcPort, dstAddress, dstPort, data);
+ this.tcpSeq = tcpSeq;
+ this.tcpAck = tcpAck;
+ this.tcpWnd = tcpWnd;
+ this.tcpWndScale = tcpWndScale;
+ this.ipTos = ipTos;
+ this.ipTtl = ipTtl;
+ }
+
/**
* Factory method to create tcp keepalive packet structure.
*/
@@ -169,7 +182,11 @@
/** Write to parcel. */
public void writeToParcel(Parcel out, int flags) {
- super.writeToParcel(out, flags);
+ out.writeString(srcAddress.getHostAddress());
+ out.writeString(dstAddress.getHostAddress());
+ out.writeInt(srcPort);
+ out.writeInt(dstPort);
+ out.writeByteArray(getPacket());
out.writeInt(tcpSeq);
out.writeInt(tcpAck);
out.writeInt(tcpWnd);
@@ -178,21 +195,32 @@
out.writeInt(ipTtl);
}
- private TcpKeepalivePacketData(Parcel in) {
- super(in);
- tcpSeq = in.readInt();
- tcpAck = in.readInt();
- tcpWnd = in.readInt();
- tcpWndScale = in.readInt();
- ipTos = in.readInt();
- ipTtl = in.readInt();
+ private static TcpKeepalivePacketData readFromParcel(Parcel in) throws InvalidPacketException {
+ InetAddress srcAddress = InetAddresses.parseNumericAddress(in.readString());
+ InetAddress dstAddress = InetAddresses.parseNumericAddress(in.readString());
+ int srcPort = in.readInt();
+ int dstPort = in.readInt();
+ byte[] packet = in.createByteArray();
+ int tcpSeq = in.readInt();
+ int tcpAck = in.readInt();
+ int tcpWnd = in.readInt();
+ int tcpWndScale = in.readInt();
+ int ipTos = in.readInt();
+ int ipTtl = in.readInt();
+ return new TcpKeepalivePacketData(srcAddress, srcPort, dstAddress, dstPort, packet, tcpSeq,
+ tcpAck, tcpWnd, tcpWndScale, ipTos, ipTtl);
}
/** Parcelable Creator. */
public static final @NonNull Parcelable.Creator<TcpKeepalivePacketData> CREATOR =
new Parcelable.Creator<TcpKeepalivePacketData>() {
public TcpKeepalivePacketData createFromParcel(Parcel in) {
- return new TcpKeepalivePacketData(in);
+ try {
+ return readFromParcel(in);
+ } catch (InvalidPacketException e) {
+ throw new IllegalArgumentException(
+ "Invalid NAT-T keepalive data: " + e.error);
+ }
}
public TcpKeepalivePacketData[] newArray(int size) {
diff --git a/services/net/java/android/net/ip/IpClientUtil.java b/services/net/java/android/net/ip/IpClientUtil.java
index a3618b4..b329aee 100644
--- a/services/net/java/android/net/ip/IpClientUtil.java
+++ b/services/net/java/android/net/ip/IpClientUtil.java
@@ -22,7 +22,7 @@
import android.net.DhcpResultsParcelable;
import android.net.Layer2PacketParcelable;
import android.net.LinkProperties;
-import android.net.NetworkStackClient;
+import android.net.networkstack.ModuleNetworkStackClient;
import android.os.ConditionVariable;
import java.io.FileDescriptor;
@@ -75,11 +75,11 @@
*
* <p>This is a convenience method to allow clients to use {@link IpClientCallbacks} instead of
* {@link IIpClientCallbacks}.
- * @see {@link NetworkStackClient#makeIpClient(String, IIpClientCallbacks)}
+ * @see {@link ModuleNetworkStackClient#makeIpClient(String, IIpClientCallbacks)}
*/
public static void makeIpClient(Context context, String ifName, IpClientCallbacks callback) {
- // TODO: migrate clients and remove context argument
- NetworkStackClient.getInstance().makeIpClient(ifName, new IpClientCallbacksProxy(callback));
+ ModuleNetworkStackClient.getInstance(context)
+ .makeIpClient(ifName, new IpClientCallbacksProxy(callback));
}
/**
diff --git a/services/people/java/com/android/server/people/PeopleService.java b/services/people/java/com/android/server/people/PeopleService.java
index 983a639..37bf664 100644
--- a/services/people/java/com/android/server/people/PeopleService.java
+++ b/services/people/java/com/android/server/people/PeopleService.java
@@ -72,13 +72,13 @@
}
@Override
- public void onUserUnlocking(@NonNull TargetUser targetUser) {
- mDataManager.onUserUnlocked(targetUser.getUserIdentifier());
+ public void onUserUnlocked(@NonNull TargetUser user) {
+ mDataManager.onUserUnlocked(user.getUserIdentifier());
}
@Override
- public void onUserStopping(@NonNull TargetUser targetUser) {
- mDataManager.onUserStopped(targetUser.getUserIdentifier());
+ public void onUserStopping(@NonNull TargetUser user) {
+ mDataManager.onUserStopping(user.getUserIdentifier());
}
@VisibleForTesting
diff --git a/services/people/java/com/android/server/people/data/ConversationStore.java b/services/people/java/com/android/server/people/data/ConversationStore.java
index 8481e5b..28e3d4b 100644
--- a/services/people/java/com/android/server/people/data/ConversationStore.java
+++ b/services/people/java/com/android/server/people/data/ConversationStore.java
@@ -89,25 +89,21 @@
* Loads conversations from disk to memory in a background thread. This should be called
* after the device powers on and the user has been unlocked.
*/
- @MainThread
- void loadConversationsFromDisk() {
- mScheduledExecutorService.execute(() -> {
- synchronized (this) {
- ConversationInfosProtoDiskReadWriter conversationInfosProtoDiskReadWriter =
- getConversationInfosProtoDiskReadWriter();
- if (conversationInfosProtoDiskReadWriter == null) {
- return;
- }
- List<ConversationInfo> conversationsOnDisk =
- conversationInfosProtoDiskReadWriter.read(CONVERSATIONS_FILE_NAME);
- if (conversationsOnDisk == null) {
- return;
- }
- for (ConversationInfo conversationInfo : conversationsOnDisk) {
- updateConversationsInMemory(conversationInfo);
- }
- }
- });
+ @WorkerThread
+ synchronized void loadConversationsFromDisk() {
+ ConversationInfosProtoDiskReadWriter conversationInfosProtoDiskReadWriter =
+ getConversationInfosProtoDiskReadWriter();
+ if (conversationInfosProtoDiskReadWriter == null) {
+ return;
+ }
+ List<ConversationInfo> conversationsOnDisk =
+ conversationInfosProtoDiskReadWriter.read(CONVERSATIONS_FILE_NAME);
+ if (conversationsOnDisk == null) {
+ return;
+ }
+ for (ConversationInfo conversationInfo : conversationsOnDisk) {
+ updateConversationsInMemory(conversationInfo);
+ }
}
/**
diff --git a/services/people/java/com/android/server/people/data/DataManager.java b/services/people/java/com/android/server/people/data/DataManager.java
index e4ce6ba..7085f96 100644
--- a/services/people/java/com/android/server/people/data/DataManager.java
+++ b/services/people/java/com/android/server/people/data/DataManager.java
@@ -28,6 +28,7 @@
import android.app.prediction.AppTargetEvent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
+import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
@@ -87,13 +88,13 @@
private static final String TAG = "DataManager";
- private static final long QUERY_EVENTS_MAX_AGE_MS = DateUtils.DAY_IN_MILLIS;
+ private static final long QUERY_EVENTS_MAX_AGE_MS = 5L * DateUtils.MINUTE_IN_MILLIS;
private static final long USAGE_STATS_QUERY_INTERVAL_SEC = 120L;
private final Context mContext;
private final Injector mInjector;
- private final ScheduledExecutorService mUsageStatsQueryExecutor;
- private final ScheduledExecutorService mDiskReadWriterExecutor;
+ private final ScheduledExecutorService mScheduledExecutor;
+ private final Object mLock = new Object();
private final SparseArray<UserData> mUserDataArray = new SparseArray<>();
private final SparseArray<BroadcastReceiver> mBroadcastReceivers = new SparseArray<>();
@@ -118,8 +119,7 @@
DataManager(Context context, Injector injector) {
mContext = context;
mInjector = injector;
- mUsageStatsQueryExecutor = mInjector.createScheduledExecutor();
- mDiskReadWriterExecutor = mInjector.createScheduledExecutor();
+ mScheduledExecutor = mInjector.createScheduledExecutor();
}
/** Initialization. Called when the system services are up running. */
@@ -138,103 +138,56 @@
/** This method is called when a user is unlocked. */
public void onUserUnlocked(int userId) {
- UserData userData = mUserDataArray.get(userId);
- if (userData == null) {
- userData = new UserData(userId, mDiskReadWriterExecutor);
- mUserDataArray.put(userId, userData);
+ synchronized (mLock) {
+ UserData userData = mUserDataArray.get(userId);
+ if (userData == null) {
+ userData = new UserData(userId, mScheduledExecutor);
+ mUserDataArray.put(userId, userData);
+ }
+ userData.setUserUnlocked();
}
- userData.setUserUnlocked();
- updateDefaultDialer(userData);
- updateDefaultSmsApp(userData);
-
- ScheduledFuture<?> scheduledFuture = mUsageStatsQueryExecutor.scheduleAtFixedRate(
- new UsageStatsQueryRunnable(userId), 1L, USAGE_STATS_QUERY_INTERVAL_SEC,
- TimeUnit.SECONDS);
- mUsageStatsQueryFutures.put(userId, scheduledFuture);
-
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(TelecomManager.ACTION_DEFAULT_DIALER_CHANGED);
- intentFilter.addAction(SmsApplication.ACTION_DEFAULT_SMS_PACKAGE_CHANGED_INTERNAL);
- BroadcastReceiver broadcastReceiver = new PerUserBroadcastReceiver(userId);
- mBroadcastReceivers.put(userId, broadcastReceiver);
- mContext.registerReceiverAsUser(
- broadcastReceiver, UserHandle.of(userId), intentFilter, null, null);
-
- ContentObserver contactsContentObserver = new ContactsContentObserver(
- BackgroundThread.getHandler());
- mContactsContentObservers.put(userId, contactsContentObserver);
- mContext.getContentResolver().registerContentObserver(
- Contacts.CONTENT_URI, /* notifyForDescendants= */ true,
- contactsContentObserver, userId);
-
- NotificationListener notificationListener = new NotificationListener();
- mNotificationListeners.put(userId, notificationListener);
- try {
- notificationListener.registerAsSystemService(mContext,
- new ComponentName(mContext, getClass()), userId);
- } catch (RemoteException e) {
- // Should never occur for local calls.
- }
-
- PackageMonitor packageMonitor = new PerUserPackageMonitor();
- packageMonitor.register(mContext, null, UserHandle.of(userId), true);
- mPackageMonitors.put(userId, packageMonitor);
-
- if (userId == UserHandle.USER_SYSTEM) {
- // The call log and MMS/SMS messages are shared across user profiles. So only need to
- // register the content observers once for the primary user.
- // TODO: Register observers after the conversations and events being loaded from disk.
- mCallLogContentObserver = new CallLogContentObserver(BackgroundThread.getHandler());
- mContext.getContentResolver().registerContentObserver(
- CallLog.CONTENT_URI, /* notifyForDescendants= */ true,
- mCallLogContentObserver, UserHandle.USER_SYSTEM);
-
- mMmsSmsContentObserver = new MmsSmsContentObserver(BackgroundThread.getHandler());
- mContext.getContentResolver().registerContentObserver(
- MmsSms.CONTENT_URI, /* notifyForDescendants= */ false,
- mMmsSmsContentObserver, UserHandle.USER_SYSTEM);
- }
-
- DataMaintenanceService.scheduleJob(mContext, userId);
+ mScheduledExecutor.execute(() -> setupUser(userId));
}
- /** This method is called when a user is stopped. */
- public void onUserStopped(int userId) {
- if (mUserDataArray.indexOfKey(userId) >= 0) {
- mUserDataArray.get(userId).setUserStopped();
- }
- if (mUsageStatsQueryFutures.indexOfKey(userId) >= 0) {
- mUsageStatsQueryFutures.valueAt(userId).cancel(true);
- }
- if (mBroadcastReceivers.indexOfKey(userId) >= 0) {
- mContext.unregisterReceiver(mBroadcastReceivers.get(userId));
- }
- if (mContactsContentObservers.indexOfKey(userId) >= 0) {
- mContext.getContentResolver().unregisterContentObserver(
- mContactsContentObservers.get(userId));
- }
- if (mNotificationListeners.indexOfKey(userId) >= 0) {
- try {
- mNotificationListeners.get(userId).unregisterAsSystemService();
- } catch (RemoteException e) {
- // Should never occur for local calls.
+ /** This method is called when a user is stopping. */
+ public void onUserStopping(int userId) {
+ synchronized (mLock) {
+ ContentResolver contentResolver = mContext.getContentResolver();
+ if (mUserDataArray.indexOfKey(userId) >= 0) {
+ mUserDataArray.get(userId).setUserStopped();
}
- }
- if (mPackageMonitors.indexOfKey(userId) >= 0) {
- mPackageMonitors.get(userId).unregister();
- }
- if (userId == UserHandle.USER_SYSTEM) {
- if (mCallLogContentObserver != null) {
- mContext.getContentResolver().unregisterContentObserver(mCallLogContentObserver);
- mCallLogContentObserver = null;
+ if (mUsageStatsQueryFutures.indexOfKey(userId) >= 0) {
+ mUsageStatsQueryFutures.get(userId).cancel(true);
}
- if (mMmsSmsContentObserver != null) {
- mContext.getContentResolver().unregisterContentObserver(mMmsSmsContentObserver);
- mCallLogContentObserver = null;
+ if (mBroadcastReceivers.indexOfKey(userId) >= 0) {
+ mContext.unregisterReceiver(mBroadcastReceivers.get(userId));
}
- }
+ if (mContactsContentObservers.indexOfKey(userId) >= 0) {
+ contentResolver.unregisterContentObserver(mContactsContentObservers.get(userId));
+ }
+ if (mNotificationListeners.indexOfKey(userId) >= 0) {
+ try {
+ mNotificationListeners.get(userId).unregisterAsSystemService();
+ } catch (RemoteException e) {
+ // Should never occur for local calls.
+ }
+ }
+ if (mPackageMonitors.indexOfKey(userId) >= 0) {
+ mPackageMonitors.get(userId).unregister();
+ }
+ if (userId == UserHandle.USER_SYSTEM) {
+ if (mCallLogContentObserver != null) {
+ contentResolver.unregisterContentObserver(mCallLogContentObserver);
+ mCallLogContentObserver = null;
+ }
+ if (mMmsSmsContentObserver != null) {
+ contentResolver.unregisterContentObserver(mMmsSmsContentObserver);
+ mCallLogContentObserver = null;
+ }
+ }
- DataMaintenanceService.cancelJob(mContext, userId);
+ DataMaintenanceService.cancelJob(mContext, userId);
+ }
}
/**
@@ -288,6 +241,9 @@
return;
}
UserData userData = getUnlockedUserData(appTarget.getUser().getIdentifier());
+ if (userData == null) {
+ return;
+ }
PackageData packageData = userData.getOrCreatePackageData(appTarget.getPackageName());
String mimeType = intentFilter != null ? intentFilter.getDataType(0) : null;
@Event.EventType int eventType = mimeTypeToShareEventType(mimeType);
@@ -353,6 +309,68 @@
userData.restore(payload);
}
+ private void setupUser(@UserIdInt int userId) {
+ synchronized (mLock) {
+ UserData userData = getUnlockedUserData(userId);
+ if (userData == null) {
+ return;
+ }
+ userData.loadUserData();
+
+ updateDefaultDialer(userData);
+ updateDefaultSmsApp(userData);
+
+ ScheduledFuture<?> scheduledFuture = mScheduledExecutor.scheduleAtFixedRate(
+ new UsageStatsQueryRunnable(userId), 1L, USAGE_STATS_QUERY_INTERVAL_SEC,
+ TimeUnit.SECONDS);
+ mUsageStatsQueryFutures.put(userId, scheduledFuture);
+
+ IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(TelecomManager.ACTION_DEFAULT_DIALER_CHANGED);
+ intentFilter.addAction(SmsApplication.ACTION_DEFAULT_SMS_PACKAGE_CHANGED_INTERNAL);
+ BroadcastReceiver broadcastReceiver = new PerUserBroadcastReceiver(userId);
+ mBroadcastReceivers.put(userId, broadcastReceiver);
+ mContext.registerReceiverAsUser(
+ broadcastReceiver, UserHandle.of(userId), intentFilter, null, null);
+
+ ContentObserver contactsContentObserver = new ContactsContentObserver(
+ BackgroundThread.getHandler());
+ mContactsContentObservers.put(userId, contactsContentObserver);
+ mContext.getContentResolver().registerContentObserver(
+ Contacts.CONTENT_URI, /* notifyForDescendants= */ true,
+ contactsContentObserver, userId);
+
+ NotificationListener notificationListener = new NotificationListener();
+ mNotificationListeners.put(userId, notificationListener);
+ try {
+ notificationListener.registerAsSystemService(mContext,
+ new ComponentName(mContext, getClass()), userId);
+ } catch (RemoteException e) {
+ // Should never occur for local calls.
+ }
+
+ PackageMonitor packageMonitor = new PerUserPackageMonitor();
+ packageMonitor.register(mContext, null, UserHandle.of(userId), true);
+ mPackageMonitors.put(userId, packageMonitor);
+
+ if (userId == UserHandle.USER_SYSTEM) {
+ // The call log and MMS/SMS messages are shared across user profiles. So only need
+ // to register the content observers once for the primary user.
+ mCallLogContentObserver = new CallLogContentObserver(BackgroundThread.getHandler());
+ mContext.getContentResolver().registerContentObserver(
+ CallLog.CONTENT_URI, /* notifyForDescendants= */ true,
+ mCallLogContentObserver, UserHandle.USER_SYSTEM);
+
+ mMmsSmsContentObserver = new MmsSmsContentObserver(BackgroundThread.getHandler());
+ mContext.getContentResolver().registerContentObserver(
+ MmsSms.CONTENT_URI, /* notifyForDescendants= */ false,
+ mMmsSmsContentObserver, UserHandle.USER_SYSTEM);
+ }
+
+ DataMaintenanceService.scheduleJob(mContext, userId);
+ }
+ }
+
private int mimeTypeToShareEventType(String mimeType) {
if (mimeType.startsWith("text/")) {
return Event.TYPE_SHARE_TEXT;
diff --git a/services/people/java/com/android/server/people/data/EventStore.java b/services/people/java/com/android/server/people/data/EventStore.java
index 00d4241..9cf84c9 100644
--- a/services/people/java/com/android/server/people/data/EventStore.java
+++ b/services/people/java/com/android/server/people/data/EventStore.java
@@ -17,9 +17,9 @@
package com.android.server.people.data;
import android.annotation.IntDef;
-import android.annotation.MainThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.WorkerThread;
import android.net.Uri;
import android.util.ArrayMap;
@@ -90,20 +90,16 @@
* Loads existing {@link EventHistoryImpl}s from disk. This should be called when device powers
* on and user is unlocked.
*/
- @MainThread
- void loadFromDisk() {
- mScheduledExecutorService.execute(() -> {
- synchronized (this) {
- for (@EventCategory int category = 0; category < mEventsCategoryDirs.size();
- category++) {
- File categoryDir = mEventsCategoryDirs.get(category);
- Map<String, EventHistoryImpl> existingEventHistoriesImpl =
- EventHistoryImpl.eventHistoriesImplFromDisk(categoryDir,
- mScheduledExecutorService);
- mEventHistoryMaps.get(category).putAll(existingEventHistoriesImpl);
- }
- }
- });
+ @WorkerThread
+ synchronized void loadFromDisk() {
+ for (@EventCategory int category = 0; category < mEventsCategoryDirs.size();
+ category++) {
+ File categoryDir = mEventsCategoryDirs.get(category);
+ Map<String, EventHistoryImpl> existingEventHistoriesImpl =
+ EventHistoryImpl.eventHistoriesImplFromDisk(categoryDir,
+ mScheduledExecutorService);
+ mEventHistoryMaps.get(category).putAll(existingEventHistoriesImpl);
+ }
}
/**
diff --git a/services/people/java/com/android/server/people/data/MmsQueryHelper.java b/services/people/java/com/android/server/people/data/MmsQueryHelper.java
index 1e485c0..39dba9c 100644
--- a/services/people/java/com/android/server/people/data/MmsQueryHelper.java
+++ b/services/people/java/com/android/server/people/data/MmsQueryHelper.java
@@ -21,6 +21,7 @@
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
+import android.os.Binder;
import android.provider.Telephony.BaseMmsColumns;
import android.provider.Telephony.Mms;
import android.telephony.PhoneNumberUtils;
@@ -71,31 +72,36 @@
// NOTE: The field Mms.DATE is stored in seconds, not milliseconds.
String[] selectionArgs = new String[] { Long.toString(sinceTime / MILLIS_PER_SECONDS) };
boolean hasResults = false;
- try (Cursor cursor = mContext.getContentResolver().query(
- Mms.CONTENT_URI, projection, selection, selectionArgs, null)) {
- if (cursor == null) {
- Slog.w(TAG, "Cursor is null when querying MMS table.");
- return false;
- }
- while (cursor.moveToNext()) {
- // ID
- int msgIdIndex = cursor.getColumnIndex(Mms._ID);
- String msgId = cursor.getString(msgIdIndex);
+ Binder.allowBlockingForCurrentThread();
+ try {
+ try (Cursor cursor = mContext.getContentResolver().query(
+ Mms.CONTENT_URI, projection, selection, selectionArgs, null)) {
+ if (cursor == null) {
+ Slog.w(TAG, "Cursor is null when querying MMS table.");
+ return false;
+ }
+ while (cursor.moveToNext()) {
+ // ID
+ int msgIdIndex = cursor.getColumnIndex(Mms._ID);
+ String msgId = cursor.getString(msgIdIndex);
- // Date
- int dateIndex = cursor.getColumnIndex(Mms.DATE);
- long date = cursor.getLong(dateIndex) * MILLIS_PER_SECONDS;
+ // Date
+ int dateIndex = cursor.getColumnIndex(Mms.DATE);
+ long date = cursor.getLong(dateIndex) * MILLIS_PER_SECONDS;
- // Message box
- int msgBoxIndex = cursor.getColumnIndex(Mms.MESSAGE_BOX);
- int msgBox = cursor.getInt(msgBoxIndex);
+ // Message box
+ int msgBoxIndex = cursor.getColumnIndex(Mms.MESSAGE_BOX);
+ int msgBox = cursor.getInt(msgBoxIndex);
- mLastMessageTimestamp = Math.max(mLastMessageTimestamp, date);
- String address = getMmsAddress(msgId, msgBox);
- if (address != null && addEvent(address, date, msgBox)) {
- hasResults = true;
+ mLastMessageTimestamp = Math.max(mLastMessageTimestamp, date);
+ String address = getMmsAddress(msgId, msgBox);
+ if (address != null && addEvent(address, date, msgBox)) {
+ hasResults = true;
+ }
}
}
+ } finally {
+ Binder.defaultBlockingForCurrentThread();
}
return hasResults;
}
diff --git a/services/people/java/com/android/server/people/data/PackageData.java b/services/people/java/com/android/server/people/data/PackageData.java
index 3e4c992..28837d5 100644
--- a/services/people/java/com/android/server/people/data/PackageData.java
+++ b/services/people/java/com/android/server/people/data/PackageData.java
@@ -25,6 +25,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
+import android.annotation.WorkerThread;
import android.content.LocusId;
import android.os.FileUtils;
import android.text.TextUtils;
@@ -77,6 +78,7 @@
* Returns a map of package directory names as keys and their associated {@link PackageData}.
* This should be called when device is powered on and unlocked.
*/
+ @WorkerThread
@NonNull
static Map<String, PackageData> packagesDataFromDisk(@UserIdInt int userId,
@NonNull Predicate<String> isDefaultDialerPredicate,
diff --git a/services/people/java/com/android/server/people/data/SmsQueryHelper.java b/services/people/java/com/android/server/people/data/SmsQueryHelper.java
index c38c846..a5eb3a5 100644
--- a/services/people/java/com/android/server/people/data/SmsQueryHelper.java
+++ b/services/people/java/com/android/server/people/data/SmsQueryHelper.java
@@ -19,6 +19,7 @@
import android.annotation.WorkerThread;
import android.content.Context;
import android.database.Cursor;
+import android.os.Binder;
import android.provider.Telephony.Sms;
import android.provider.Telephony.TextBasedSmsColumns;
import android.telephony.PhoneNumberUtils;
@@ -65,35 +66,40 @@
String selection = Sms.DATE + " > ?";
String[] selectionArgs = new String[] { Long.toString(sinceTime) };
boolean hasResults = false;
- try (Cursor cursor = mContext.getContentResolver().query(
- Sms.CONTENT_URI, projection, selection, selectionArgs, null)) {
- if (cursor == null) {
- Slog.w(TAG, "Cursor is null when querying SMS table.");
- return false;
- }
- while (cursor.moveToNext()) {
- // ID
- int msgIdIndex = cursor.getColumnIndex(Sms._ID);
- String msgId = cursor.getString(msgIdIndex);
+ Binder.allowBlockingForCurrentThread();
+ try {
+ try (Cursor cursor = mContext.getContentResolver().query(
+ Sms.CONTENT_URI, projection, selection, selectionArgs, null)) {
+ if (cursor == null) {
+ Slog.w(TAG, "Cursor is null when querying SMS table.");
+ return false;
+ }
+ while (cursor.moveToNext()) {
+ // ID
+ int msgIdIndex = cursor.getColumnIndex(Sms._ID);
+ String msgId = cursor.getString(msgIdIndex);
- // Date
- int dateIndex = cursor.getColumnIndex(Sms.DATE);
- long date = cursor.getLong(dateIndex);
+ // Date
+ int dateIndex = cursor.getColumnIndex(Sms.DATE);
+ long date = cursor.getLong(dateIndex);
- // Type
- int typeIndex = cursor.getColumnIndex(Sms.TYPE);
- int type = cursor.getInt(typeIndex);
+ // Type
+ int typeIndex = cursor.getColumnIndex(Sms.TYPE);
+ int type = cursor.getInt(typeIndex);
- // Address
- int addressIndex = cursor.getColumnIndex(Sms.ADDRESS);
- String address = PhoneNumberUtils.formatNumberToE164(
- cursor.getString(addressIndex), mCurrentCountryIso);
+ // Address
+ int addressIndex = cursor.getColumnIndex(Sms.ADDRESS);
+ String address = PhoneNumberUtils.formatNumberToE164(
+ cursor.getString(addressIndex), mCurrentCountryIso);
- mLastMessageTimestamp = Math.max(mLastMessageTimestamp, date);
- if (address != null && addEvent(address, date, type)) {
- hasResults = true;
+ mLastMessageTimestamp = Math.max(mLastMessageTimestamp, date);
+ if (address != null && addEvent(address, date, type)) {
+ hasResults = true;
+ }
}
}
+ } finally {
+ Binder.defaultBlockingForCurrentThread();
}
return hasResults;
}
diff --git a/services/people/java/com/android/server/people/data/UserData.java b/services/people/java/com/android/server/people/data/UserData.java
index ed8c595..429d5b7 100644
--- a/services/people/java/com/android/server/people/data/UserData.java
+++ b/services/people/java/com/android/server/people/data/UserData.java
@@ -19,6 +19,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
+import android.annotation.WorkerThread;
import android.os.Environment;
import android.text.TextUtils;
import android.util.ArrayMap;
@@ -75,12 +76,6 @@
void setUserUnlocked() {
mIsUnlocked = true;
-
- // Ensures per user root directory for people data is present, and attempt to load
- // data from disk.
- mPerUserPeopleDataDir.mkdirs();
- mPackageDataMap.putAll(PackageData.packagesDataFromDisk(mUserId, this::isDefaultDialer,
- this::isDefaultSmsApp, mScheduledExecutorService, mPerUserPeopleDataDir));
}
void setUserStopped() {
@@ -91,6 +86,15 @@
return mIsUnlocked;
}
+ @WorkerThread
+ void loadUserData() {
+ mPerUserPeopleDataDir.mkdir();
+ Map<String, PackageData> packageDataMap = PackageData.packagesDataFromDisk(
+ mUserId, this::isDefaultDialer, this::isDefaultSmsApp, mScheduledExecutorService,
+ mPerUserPeopleDataDir);
+ mPackageDataMap.putAll(packageDataMap);
+ }
+
/**
* Gets the {@link PackageData} for the specified {@code packageName} if exists; otherwise
* creates a new instance and returns it.
diff --git a/services/robotests/Android.bp b/services/robotests/Android.bp
index 602e4e1..25ab5d3 100644
--- a/services/robotests/Android.bp
+++ b/services/robotests/Android.bp
@@ -27,7 +27,7 @@
"services.net",
],
- libs: ["ike-stubs"],
+ libs: ["android.net.ipsec.ike.stubs.system"],
}
//##################################################################
diff --git a/services/robotests/backup/Android.bp b/services/robotests/backup/Android.bp
index 5160eae..32587ac 100644
--- a/services/robotests/backup/Android.bp
+++ b/services/robotests/backup/Android.bp
@@ -29,7 +29,7 @@
"services.net",
],
- libs: ["ike-stubs"],
+ libs: ["android.net.ipsec.ike.stubs.system"],
}
//##################################################################
diff --git a/services/tests/mockingservicestests/src/com/android/server/RescuePartyTest.java b/services/tests/mockingservicestests/src/com/android/server/RescuePartyTest.java
index c94bb87..5c82200 100644
--- a/services/tests/mockingservicestests/src/com/android/server/RescuePartyTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/RescuePartyTest.java
@@ -79,6 +79,7 @@
private static final String CALLING_PACKAGE2 = "com.package.name2";
private static final String NAMESPACE1 = "namespace1";
private static final String NAMESPACE2 = "namespace2";
+ private static final String DISABLE_RESCUE_PARTY_FLAG = "disable_rescue_party";
private MockitoSession mSession;
private HashMap<String, String> mSystemSettingsMap;
@@ -316,6 +317,13 @@
@Test
public void testExplicitlyEnablingAndDisablingRescue() {
+ // mock the DeviceConfig get call to avoid hitting
+ // android.permission.READ_DEVICE_CONFIG when calling real DeviceConfig.
+ doReturn(true)
+ .when(() -> DeviceConfig.getBoolean(
+ eq(DeviceConfig.NAMESPACE_CONFIGURATION),
+ eq(DISABLE_RESCUE_PARTY_FLAG),
+ eq(false)));
SystemProperties.set(RescueParty.PROP_ENABLE_RESCUE, Boolean.toString(false));
SystemProperties.set(PROP_DISABLE_RESCUE, Boolean.toString(true));
assertEquals(RescuePartyObserver.getInstance(mMockContext).execute(sFailingPackage,
@@ -327,6 +335,22 @@
}
@Test
+ public void testDisablingRescueByDeviceConfigFlag() {
+ doReturn(true)
+ .when(() -> DeviceConfig.getBoolean(
+ eq(DeviceConfig.NAMESPACE_CONFIGURATION),
+ eq(DISABLE_RESCUE_PARTY_FLAG),
+ eq(false)));
+ SystemProperties.set(RescueParty.PROP_ENABLE_RESCUE, Boolean.toString(false));
+
+ assertEquals(RescuePartyObserver.getInstance(mMockContext).execute(sFailingPackage,
+ PackageWatchdog.FAILURE_REASON_APP_NOT_RESPONDING), false);
+
+ // Restore the property value initalized in SetUp()
+ SystemProperties.set(RescueParty.PROP_ENABLE_RESCUE, Boolean.toString(true));
+ }
+
+ @Test
public void testHealthCheckLevels() {
RescuePartyObserver observer = RescuePartyObserver.getInstance(mMockContext);
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/ApplicationExitInfoTest.java b/services/tests/mockingservicestests/src/com/android/server/am/ApplicationExitInfoTest.java
index 6083ce34..efe8119 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/ApplicationExitInfoTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/ApplicationExitInfoTest.java
@@ -55,6 +55,7 @@
import android.text.TextUtils;
import android.util.Pair;
+import com.android.server.LocalServices;
import com.android.server.ServiceThread;
import com.android.server.appop.AppOpsService;
import com.android.server.wm.ActivityTaskManagerService;
@@ -125,10 +126,15 @@
mAms.mActivityTaskManager.initialize(null, null, mContext.getMainLooper());
mAms.mAtmInternal = spy(mAms.mActivityTaskManager.getAtmInternal());
mAms.mPackageManagerInt = mPackageManagerInt;
+ doReturn(new ComponentName("", "")).when(mPackageManagerInt).getSystemUiServiceComponent();
+ // Remove stale instance of PackageManagerInternal if there is any
+ LocalServices.removeServiceForTest(PackageManagerInternal.class);
+ LocalServices.addService(PackageManagerInternal.class, mPackageManagerInt);
}
@After
public void tearDown() {
+ LocalServices.removeServiceForTest(PackageManagerInternal.class);
mHandlerThread.quit();
}
@@ -847,8 +853,8 @@
app.connectionGroup = connectionGroup;
app.setProcState = procState;
app.lastMemInfo = spy(new Debug.MemoryInfo());
- doReturn((int) pss).when(app.lastMemInfo).getTotalPss();
- doReturn((int) rss).when(app.lastMemInfo).getTotalRss();
+ app.lastPss = pss;
+ app.mLastRss = rss;
return app;
}
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/CachedAppOptimizerTest.java b/services/tests/mockingservicestests/src/com/android/server/am/CachedAppOptimizerTest.java
index 4722b39..e5ec1f7 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/CachedAppOptimizerTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/CachedAppOptimizerTest.java
@@ -36,6 +36,7 @@
import com.android.server.testables.TestableDeviceConfig;
import org.junit.After;
+import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -267,9 +268,7 @@
@Test
public void useFreeze_doesNotListenToDeviceConfigChanges() throws InterruptedException {
- if (!mCachedAppOptimizerUnderTest.isFreezerSupported()) {
- return;
- }
+ Assume.assumeTrue(mCachedAppOptimizerUnderTest.isFreezerSupported());
assertThat(mCachedAppOptimizerUnderTest.useFreezer()).isEqualTo(
CachedAppOptimizer.DEFAULT_USE_FREEZER);
diff --git a/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java b/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
index fc2ae40..7a175ca1 100644
--- a/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
+++ b/services/tests/mockingservicestests/src/com/android/server/am/MockingOomAdjusterTests.java
@@ -75,8 +75,10 @@
import android.app.IApplicationThread;
import android.app.IServiceConnection;
+import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManagerInternal;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
@@ -87,10 +89,12 @@
import android.util.ArraySet;
import android.util.SparseArray;
+import com.android.server.LocalServices;
import com.android.server.wm.ActivityServiceConnectionsHolder;
import com.android.server.wm.ActivityTaskManagerService;
import com.android.server.wm.WindowProcessController;
+import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -127,6 +131,7 @@
private static final String MOCKAPP5_PROCESSNAME = "test #5";
private static final String MOCKAPP5_PACKAGENAME = "com.android.test.test5";
private static Context sContext;
+ private static PackageManagerInternal sPackageManagerInternal;
private static ActivityManagerService sService;
@BeforeClass
@@ -134,13 +139,23 @@
sContext = getInstrumentation().getTargetContext();
System.setProperty("dexmaker.share_classloader", "true");
+ sPackageManagerInternal = mock(PackageManagerInternal.class);
+ doReturn(new ComponentName("", "")).when(sPackageManagerInternal)
+ .getSystemUiServiceComponent();
+ // Remove stale instance of PackageManagerInternal if there is any
+ LocalServices.removeServiceForTest(PackageManagerInternal.class);
+ LocalServices.addService(PackageManagerInternal.class, sPackageManagerInternal);
+
sService = mock(ActivityManagerService.class);
sService.mActivityTaskManager = new ActivityTaskManagerService(sContext);
sService.mActivityTaskManager.initialize(null, null, sContext.getMainLooper());
+ sService.mPackageManagerInt = sPackageManagerInternal;
sService.mAtmInternal = spy(sService.mActivityTaskManager.getAtmInternal());
sService.mConstants = new ActivityManagerConstants(sContext, sService,
sContext.getMainThreadHandler());
+ setFieldValue(ActivityManagerService.class, sService, "mContext",
+ sContext);
ProcessList pr = new ProcessList();
pr.init(sService, new ActiveUids(sService, false), null);
setFieldValue(ActivityManagerService.class, sService, "mProcessList",
@@ -160,6 +175,11 @@
sService.mOomAdjuster.mAdjSeq = 10000;
}
+ @AfterClass
+ public static void tearDownOnce() {
+ LocalServices.removeServiceForTest(PackageManagerInternal.class);
+ }
+
private static <T> void setFieldValue(Class clazz, Object obj, String fieldName, T val) {
try {
Field field = clazz.getDeclaredField(fieldName);
@@ -972,7 +992,7 @@
sService.mOomAdjuster.updateOomAdjLocked(app, false, OomAdjuster.OOM_ADJ_REASON_NONE);
doReturn(null).when(sService).getTopAppLocked();
- assertProcStates(app, PROCESS_STATE_FOREGROUND_SERVICE, VISIBLE_APP_ADJ,
+ assertProcStates(app, PROCESS_STATE_BOUND_TOP, VISIBLE_APP_ADJ,
SCHED_GROUP_DEFAULT);
}
diff --git a/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsServiceTest.java
index 959dc05..de6f55b 100644
--- a/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsServiceTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsServiceTest.java
@@ -147,7 +147,7 @@
AndroidPackage mockMyPkg = mock(AndroidPackage.class);
when(mockMyPkg.isPrivileged()).thenReturn(false);
when(mockMyPkg.getUid()).thenReturn(mMyUid);
- when(mockMyPkg.getFeatures()).thenReturn(Collections.emptyList());
+ when(mockMyPkg.getAttributions()).thenReturn(Collections.emptyList());
when(mockPackageManagerInternal.getPackage(sMyPackageName)).thenReturn(mockMyPkg);
doReturn(mockPackageManagerInternal).when(
diff --git a/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreConfigTest.java b/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreConfigTest.java
new file mode 100644
index 0000000..ad19a48
--- /dev/null
+++ b/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreConfigTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2020 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.blob;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static junit.framework.Assert.fail;
+
+import android.content.Context;
+import android.os.Environment;
+import android.platform.test.annotations.Presubmit;
+import android.provider.DeviceConfig;
+import android.util.DataUnit;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.testables.TestableDeviceConfig;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+@Presubmit
+public class BlobStoreConfigTest {
+ private static final long TIMEOUT_UPDATE_PROPERTIES_MS = 1_000;
+
+ @Rule
+ public TestableDeviceConfig.TestableDeviceConfigRule
+ mDeviceConfigRule = new TestableDeviceConfig.TestableDeviceConfigRule();
+
+ private Context mContext;
+
+ @Before
+ public void setUp() {
+ mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+ BlobStoreConfig.initialize(mContext);
+ }
+
+ @Test
+ public void testGetAppDataBytesLimit() throws Exception {
+ DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BLOBSTORE,
+ BlobStoreConfig.DeviceConfigProperties.KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR,
+ String.valueOf(DataUnit.MEBIBYTES.toBytes(1000)),
+ false /* makeDefault */);
+ DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BLOBSTORE,
+ BlobStoreConfig.DeviceConfigProperties.KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION,
+ String.valueOf(0.002f),
+ false /* makeDefault */);
+ waitForListenerToHandle();
+ assertThat(BlobStoreConfig.getAppDataBytesLimit()).isEqualTo(
+ DataUnit.MEBIBYTES.toBytes(1000));
+
+ DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BLOBSTORE,
+ BlobStoreConfig.DeviceConfigProperties.KEY_TOTAL_BYTES_PER_APP_LIMIT_FLOOR,
+ String.valueOf(DataUnit.MEBIBYTES.toBytes(100)),
+ false /* makeDefault */);
+ DeviceConfig.setProperty(DeviceConfig.NAMESPACE_BLOBSTORE,
+ BlobStoreConfig.DeviceConfigProperties.KEY_TOTAL_BYTES_PER_APP_LIMIT_FRACTION,
+ String.valueOf(0.1f),
+ false /* makeDefault */);
+ waitForListenerToHandle();
+ final long expectedLimit = (long) (Environment.getDataDirectory().getTotalSpace() * 0.1f);
+ assertThat(BlobStoreConfig.getAppDataBytesLimit()).isEqualTo(expectedLimit);
+ }
+
+ private void waitForListenerToHandle() throws Exception {
+ final CountDownLatch latch = new CountDownLatch(1);
+ mContext.getMainExecutor().execute(latch::countDown);
+ if (!latch.await(TIMEOUT_UPDATE_PROPERTIES_MS, TimeUnit.MILLISECONDS)) {
+ fail("Timed out waiting for properties to get updated");
+ }
+ }
+}
diff --git a/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreManagerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreManagerServiceTest.java
index 6e0df3e..cd39144 100644
--- a/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreManagerServiceTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/blob/BlobStoreManagerServiceTest.java
@@ -303,6 +303,37 @@
assertThat(mService.getKnownIdsForTest()).containsExactly(blobId1, blobId2, blobId3);
}
+ @Test
+ public void testGetTotalUsageBytes() throws Exception {
+ // Setup blobs
+ final BlobMetadata blobMetadata1 = mock(BlobMetadata.class);
+ final long size1 = 4567;
+ doReturn(size1).when(blobMetadata1).getSize();
+ doReturn(true).when(blobMetadata1).isALeasee(TEST_PKG1, TEST_UID1);
+ doReturn(true).when(blobMetadata1).isALeasee(TEST_PKG2, TEST_UID2);
+ mUserBlobs.put(mock(BlobHandle.class), blobMetadata1);
+
+ final BlobMetadata blobMetadata2 = mock(BlobMetadata.class);
+ final long size2 = 89475;
+ doReturn(size2).when(blobMetadata2).getSize();
+ doReturn(false).when(blobMetadata2).isALeasee(TEST_PKG1, TEST_UID1);
+ doReturn(true).when(blobMetadata2).isALeasee(TEST_PKG2, TEST_UID2);
+ mUserBlobs.put(mock(BlobHandle.class), blobMetadata2);
+
+ final BlobMetadata blobMetadata3 = mock(BlobMetadata.class);
+ final long size3 = 328732;
+ doReturn(size3).when(blobMetadata3).getSize();
+ doReturn(true).when(blobMetadata3).isALeasee(TEST_PKG1, TEST_UID1);
+ doReturn(false).when(blobMetadata3).isALeasee(TEST_PKG2, TEST_UID2);
+ mUserBlobs.put(mock(BlobHandle.class), blobMetadata3);
+
+ // Verify usage is calculated correctly
+ assertThat(mService.getTotalUsageBytesLocked(TEST_UID1, TEST_PKG1))
+ .isEqualTo(size1 + size3);
+ assertThat(mService.getTotalUsageBytesLocked(TEST_UID2, TEST_PKG2))
+ .isEqualTo(size1 + size2);
+ }
+
private BlobStoreSession createBlobStoreSessionMock(String ownerPackageName, int ownerUid,
long sessionId, File sessionFile) {
return createBlobStoreSessionMock(ownerPackageName, ownerUid, sessionId, sessionFile,
diff --git a/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java
index 32631be..64b24c1 100644
--- a/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java
+++ b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfig.java
@@ -24,15 +24,18 @@
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.when;
import android.provider.DeviceConfig;
import android.provider.DeviceConfig.Properties;
+import android.util.ArrayMap;
import android.util.Pair;
import com.android.dx.mockito.inline.extended.StaticMockitoSessionBuilder;
import org.junit.rules.TestRule;
+import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
@@ -109,6 +112,27 @@
String name = invocationOnMock.getArgument(1);
return mKeyValueMap.get(getKey(namespace, name));
}).when(() -> DeviceConfig.getProperty(anyString(), anyString()));
+
+ doAnswer((Answer<Properties>) invocationOnMock -> {
+ String namespace = invocationOnMock.getArgument(0);
+ final int varargStartIdx = 1;
+ Map<String, String> keyValues = new ArrayMap<>();
+ if (invocationOnMock.getArguments().length == varargStartIdx) {
+ mKeyValueMap.entrySet().forEach(entry -> {
+ Pair<String, String> nameSpaceAndName = getNameSpaceAndName(entry.getKey());
+ if (!nameSpaceAndName.first.equals(namespace)) {
+ return;
+ }
+ keyValues.put(nameSpaceAndName.second.toLowerCase(), entry.getValue());
+ });
+ } else {
+ for (int i = varargStartIdx; i < invocationOnMock.getArguments().length; ++i) {
+ String name = invocationOnMock.getArgument(i);
+ keyValues.put(name.toLowerCase(), mKeyValueMap.get(getKey(namespace, name)));
+ }
+ }
+ return getProperties(namespace, keyValues);
+ }).when(() -> DeviceConfig.getProperties(anyString(), ArgumentMatchers.<String>any()));
}
/**
@@ -124,15 +148,25 @@
return namespace + "/" + name;
}
+ private Pair<String, String> getNameSpaceAndName(String key) {
+ final String[] values = key.split("/");
+ return Pair.create(values[0], values[1]);
+ }
+
private Properties getProperties(String namespace, String name, String value) {
+ return getProperties(namespace, Collections.singletonMap(name.toLowerCase(), value));
+ }
+
+ private Properties getProperties(String namespace, Map<String, String> keyValues) {
Properties properties = Mockito.mock(Properties.class);
when(properties.getNamespace()).thenReturn(namespace);
- when(properties.getKeyset()).thenReturn(Collections.singleton(name));
+ when(properties.getKeyset()).thenReturn(keyValues.keySet());
when(properties.getBoolean(anyString(), anyBoolean())).thenAnswer(
invocation -> {
String key = invocation.getArgument(0);
boolean defaultValue = invocation.getArgument(1);
- if (name.equalsIgnoreCase(key) && value != null) {
+ final String value = keyValues.get(key.toLowerCase());
+ if (value != null) {
return Boolean.parseBoolean(value);
} else {
return defaultValue;
@@ -143,7 +177,8 @@
invocation -> {
String key = invocation.getArgument(0);
float defaultValue = invocation.getArgument(1);
- if (name.equalsIgnoreCase(key) && value != null) {
+ final String value = keyValues.get(key.toLowerCase());
+ if (value != null) {
try {
return Float.parseFloat(value);
} catch (NumberFormatException e) {
@@ -158,7 +193,8 @@
invocation -> {
String key = invocation.getArgument(0);
int defaultValue = invocation.getArgument(1);
- if (name.equalsIgnoreCase(key) && value != null) {
+ final String value = keyValues.get(key.toLowerCase());
+ if (value != null) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
@@ -173,7 +209,8 @@
invocation -> {
String key = invocation.getArgument(0);
long defaultValue = invocation.getArgument(1);
- if (name.equalsIgnoreCase(key) && value != null) {
+ final String value = keyValues.get(key.toLowerCase());
+ if (value != null) {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
@@ -184,11 +221,12 @@
}
}
);
- when(properties.getString(anyString(), anyString())).thenAnswer(
+ when(properties.getString(anyString(), nullable(String.class))).thenAnswer(
invocation -> {
String key = invocation.getArgument(0);
String defaultValue = invocation.getArgument(1);
- if (name.equalsIgnoreCase(key) && value != null) {
+ final String value = keyValues.get(key.toLowerCase());
+ if (value != null) {
return value;
} else {
return defaultValue;
diff --git a/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java
index d76c938..0e40669 100644
--- a/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/testables/TestableDeviceConfigTest.java
@@ -23,6 +23,7 @@
import android.app.ActivityThread;
import android.platform.test.annotations.Presubmit;
import android.provider.DeviceConfig;
+import android.provider.DeviceConfig.Properties;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -91,6 +92,45 @@
}
@Test
+ public void getProperties_empty() {
+ String newKey = "key2";
+ String newValue = "value2";
+ DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+ Properties properties = DeviceConfig.getProperties(sNamespace);
+ assertThat(properties.getString(sKey, null)).isEqualTo(sValue);
+ assertThat(properties.getString(newKey, null)).isNull();
+
+ DeviceConfig.setProperty(sNamespace, newKey, newValue, false);
+ properties = DeviceConfig.getProperties(sNamespace);
+ assertThat(properties.getString(sKey, null)).isEqualTo(sValue);
+ assertThat(properties.getString(newKey, null)).isEqualTo(newValue);
+
+ }
+
+ @Test
+ public void getProperties() {
+ Properties properties = DeviceConfig.getProperties(sNamespace, sKey);
+ assertThat(properties.getString(sKey, null)).isNull();
+
+ DeviceConfig.setProperty(sNamespace, sKey, sValue, false);
+ properties = DeviceConfig.getProperties(sNamespace, sKey);
+ assertThat(properties.getString(sKey, null)).isEqualTo(sValue);
+
+ String newKey = "key2";
+ String newValue = "value2";
+ DeviceConfig.setProperty(sNamespace, newKey, newValue, false);
+ properties = DeviceConfig.getProperties(sNamespace, sKey, newKey);
+ assertThat(properties.getString(sKey, null)).isEqualTo(sValue);
+ assertThat(properties.getString(newKey, null)).isEqualTo(newValue);
+
+ String unsetKey = "key3";
+ properties = DeviceConfig.getProperties(sNamespace, newKey, unsetKey);
+ assertThat(properties.getKeyset()).containsExactly(newKey, unsetKey);
+ assertThat(properties.getString(newKey, null)).isEqualTo(newValue);
+ assertThat(properties.getString(unsetKey, null)).isNull();
+ }
+
+ @Test
public void testListener() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
diff --git a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
index 164ee31..3ad9054 100644
--- a/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/biometrics/BiometricServiceTest.java
@@ -182,7 +182,8 @@
eq(0),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
}
@Test
@@ -264,7 +265,8 @@
eq(BiometricAuthenticator.TYPE_FACE),
eq(false) /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
}
@Test
@@ -391,7 +393,8 @@
eq(BiometricAuthenticator.TYPE_FINGERPRINT),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
// Hardware authenticated
mBiometricService.mInternalReceiver.onAuthenticationSucceeded(
@@ -406,7 +409,8 @@
// SystemUI sends callback with dismissed reason
mBiometricService.mInternalReceiver.onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED);
+ BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED,
+ null /* credentialAttestation */);
waitForIdle();
// HAT sent to keystore
verify(mBiometricService.mKeyStore).addAuthToken(any(byte[].class));
@@ -438,7 +442,8 @@
eq(0 /* biometricModality */),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
}
@Test
@@ -460,7 +465,8 @@
// SystemUI sends confirm, HAT is sent to keystore and client is notified.
mBiometricService.mInternalReceiver.onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED);
+ BiometricPrompt.DISMISSED_REASON_BIOMETRIC_CONFIRMED,
+ null /* credentialAttestation */);
waitForIdle();
verify(mBiometricService.mKeyStore).addAuthToken(any(byte[].class));
verify(mReceiver1).onAuthenticationSucceeded(
@@ -567,7 +573,8 @@
anyInt(),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- anyString());
+ anyString(),
+ anyLong() /* sessionId */);
}
@Test
@@ -627,8 +634,8 @@
verify(mReceiver1, never()).onError(anyInt(), anyInt(), anyInt());
// SystemUI animation completed, client is notified, auth session is over
- mBiometricService.mInternalReceiver
- .onDialogDismissed(BiometricPrompt.DISMISSED_REASON_ERROR);
+ mBiometricService.mInternalReceiver.onDialogDismissed(
+ BiometricPrompt.DISMISSED_REASON_ERROR, null /* credentialAttestation */);
waitForIdle();
verify(mReceiver1).onError(
eq(BiometricAuthenticator.TYPE_FINGERPRINT),
@@ -667,7 +674,8 @@
eq(0 /* biometricModality */),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
}
@Test
@@ -825,8 +833,8 @@
invokeAuthenticateAndStart(mBiometricService.mImpl, mReceiver1,
false /* requireConfirmation */, null /* authenticators */);
- mBiometricService.mInternalReceiver
- .onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ mBiometricService.mInternalReceiver.onDialogDismissed(
+ BiometricPrompt.DISMISSED_REASON_USER_CANCEL, null /* credentialAttestation */);
waitForIdle();
verify(mReceiver1).onError(
eq(BiometricAuthenticator.TYPE_FINGERPRINT),
@@ -854,7 +862,7 @@
BiometricConstants.BIOMETRIC_ERROR_TIMEOUT,
0 /* vendorCode */);
mBiometricService.mInternalReceiver.onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_NEGATIVE);
+ BiometricPrompt.DISMISSED_REASON_NEGATIVE, null /* credentialAttestation */);
waitForIdle();
verify(mBiometricService.mAuthenticators.get(0).impl,
@@ -880,7 +888,7 @@
BiometricConstants.BIOMETRIC_ERROR_TIMEOUT,
0 /* vendorCode */);
mBiometricService.mInternalReceiver.onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ BiometricPrompt.DISMISSED_REASON_USER_CANCEL, null /* credentialAttestation */);
waitForIdle();
verify(mBiometricService.mAuthenticators.get(0).impl,
@@ -903,7 +911,7 @@
true /* requireConfirmation */,
new byte[69] /* HAT */);
mBiometricService.mInternalReceiver.onDialogDismissed(
- BiometricPrompt.DISMISSED_REASON_USER_CANCEL);
+ BiometricPrompt.DISMISSED_REASON_USER_CANCEL, null /* credentialAttestation */);
waitForIdle();
// doesn't send cancel to HAL
@@ -1160,7 +1168,8 @@
eq(BiometricAuthenticator.TYPE_FINGERPRINT /* biometricModality */),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
// Requesting strong and credential, when credential is setup
resetReceiver();
@@ -1179,7 +1188,8 @@
eq(BiometricAuthenticator.TYPE_NONE /* biometricModality */),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
// Un-downgrading the authenticator allows successful strong auth
for (BiometricService.AuthenticatorWrapper wrapper : mBiometricService.mAuthenticators) {
@@ -1201,7 +1211,8 @@
eq(BiometricAuthenticator.TYPE_FINGERPRINT /* biometricModality */),
anyBoolean() /* requireConfirmation */,
anyInt() /* userId */,
- eq(TEST_PACKAGE_NAME));
+ eq(TEST_PACKAGE_NAME),
+ anyLong() /* sessionId */);
}
@Test(expected = IllegalStateException.class)
diff --git a/services/tests/servicestests/src/com/android/server/compat/CompatConfigBuilder.java b/services/tests/servicestests/src/com/android/server/compat/CompatConfigBuilder.java
index 328c71d..2cbe7be 100644
--- a/services/tests/servicestests/src/com/android/server/compat/CompatConfigBuilder.java
+++ b/services/tests/servicestests/src/com/android/server/compat/CompatConfigBuilder.java
@@ -40,52 +40,57 @@
}
CompatConfigBuilder addTargetSdkChangeWithId(int sdk, long id) {
- mChanges.add(new CompatChange(id, "", sdk, false, ""));
+ mChanges.add(new CompatChange(id, "", sdk, false, false, ""));
return this;
}
CompatConfigBuilder addTargetSdkDisabledChangeWithId(int sdk, long id) {
- mChanges.add(new CompatChange(id, "", sdk, true, ""));
+ mChanges.add(new CompatChange(id, "", sdk, true, false, ""));
return this;
}
CompatConfigBuilder addTargetSdkChangeWithIdAndName(int sdk, long id, String name) {
- mChanges.add(new CompatChange(id, name, sdk, false, ""));
+ mChanges.add(new CompatChange(id, name, sdk, false, false, ""));
return this;
}
CompatConfigBuilder addTargetSdkChangeWithIdAndDescription(int sdk, long id,
String description) {
- mChanges.add(new CompatChange(id, "", sdk, false, description));
+ mChanges.add(new CompatChange(id, "", sdk, false, false, description));
return this;
}
CompatConfigBuilder addEnabledChangeWithId(long id) {
- mChanges.add(new CompatChange(id, "", -1, false, ""));
+ mChanges.add(new CompatChange(id, "", -1, false, false, ""));
return this;
}
CompatConfigBuilder addEnabledChangeWithIdAndName(long id, String name) {
- mChanges.add(new CompatChange(id, name, -1, false, ""));
+ mChanges.add(new CompatChange(id, name, -1, false, false, ""));
return this;
}
CompatConfigBuilder addEnabledChangeWithIdAndDescription(long id, String description) {
- mChanges.add(new CompatChange(id, "", -1, false, description));
+ mChanges.add(new CompatChange(id, "", -1, false, false, description));
return this;
}
CompatConfigBuilder addDisabledChangeWithId(long id) {
- mChanges.add(new CompatChange(id, "", -1, true, ""));
+ mChanges.add(new CompatChange(id, "", -1, true, false, ""));
return this;
}
CompatConfigBuilder addDisabledChangeWithIdAndName(long id, String name) {
- mChanges.add(new CompatChange(id, name, -1, true, ""));
+ mChanges.add(new CompatChange(id, name, -1, true, false, ""));
return this;
}
CompatConfigBuilder addDisabledChangeWithIdAndDescription(long id, String description) {
- mChanges.add(new CompatChange(id, "", -1, true, description));
+ mChanges.add(new CompatChange(id, "", -1, true, false, description));
+ return this;
+ }
+
+ CompatConfigBuilder addLoggingOnlyChangeWithId(long id) {
+ mChanges.add(new CompatChange(id, "", -1, false, true, ""));
return this;
}
diff --git a/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java b/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java
index 44f4ccf..8be9213 100644
--- a/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java
+++ b/services/tests/servicestests/src/com/android/server/compat/CompatConfigTest.java
@@ -214,6 +214,17 @@
}
@Test
+ public void testLoggingOnlyChangePreventAddOverride() throws Exception {
+ CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
+ .addLoggingOnlyChangeWithId(1234L)
+ .build();
+
+ assertThrows(SecurityException.class,
+ () -> compatConfig.addOverride(1234L, "com.some.package", true)
+ );
+ }
+
+ @Test
public void testPreventRemoveOverride() throws Exception {
CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
.addDisabledChangeWithId(1234L)
@@ -240,6 +251,28 @@
}
@Test
+ public void testAllowRemoveOverrideNoOverride() throws Exception {
+ CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
+ .addDisabledChangeWithId(1234L)
+ .addLoggingOnlyChangeWithId(2L)
+ .build();
+ ApplicationInfo applicationInfo = ApplicationInfoBuilder.create()
+ .withPackageName("com.some.package")
+ .build();
+ when(mPackageManager.getApplicationInfo(eq("com.some.package"), anyInt()))
+ .thenReturn(applicationInfo);
+
+ // Reject all override attempts.
+ // Force the validator to prevent overriding the change by using a user build.
+ when(mBuildClassifier.isDebuggableBuild()).thenReturn(false);
+ when(mBuildClassifier.isFinalBuild()).thenReturn(true);
+ // Try to remove a non existing override, and it doesn't fail.
+ assertThat(compatConfig.removeOverride(1234L, "com.some.package")).isFalse();
+ assertThat(compatConfig.removeOverride(2L, "com.some.package")).isFalse();
+ compatConfig.removePackageOverrides("com.some.package");
+ }
+
+ @Test
public void testRemovePackageOverride() throws Exception {
CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
.addEnabledChangeWithId(1234L)
@@ -256,6 +289,49 @@
}
@Test
+ public void testEnableTargetSdkChangesForPackage() throws Exception {
+ CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
+ .addEnabledChangeWithId(1L)
+ .addDisabledChangeWithId(2L)
+ .addTargetSdkChangeWithId(3, 3L)
+ .addTargetSdkChangeWithId(4, 4L)
+ .build();
+ ApplicationInfo applicationInfo = ApplicationInfoBuilder.create()
+ .withPackageName("foo.bar")
+ .withTargetSdk(2)
+ .build();
+
+ assertThat(compatConfig.isChangeEnabled(3, applicationInfo)).isFalse();
+ assertThat(compatConfig.isChangeEnabled(4, applicationInfo)).isFalse();
+
+ assertThat(compatConfig.enableTargetSdkChangesForPackage("foo.bar", 3)).isEqualTo(1);
+ assertThat(compatConfig.isChangeEnabled(3, applicationInfo)).isTrue();
+ assertThat(compatConfig.isChangeEnabled(4, applicationInfo)).isFalse();
+ }
+
+ @Test
+ public void testDisableTargetSdkChangesForPackage() throws Exception {
+ CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
+ .addEnabledChangeWithId(1L)
+ .addDisabledChangeWithId(2L)
+ .addTargetSdkChangeWithId(3, 3L)
+ .addTargetSdkChangeWithId(4, 4L)
+ .build();
+ ApplicationInfo applicationInfo = ApplicationInfoBuilder.create()
+ .withPackageName("foo.bar")
+ .withTargetSdk(2)
+ .build();
+
+ assertThat(compatConfig.enableTargetSdkChangesForPackage("foo.bar", 3)).isEqualTo(1);
+ assertThat(compatConfig.isChangeEnabled(3, applicationInfo)).isTrue();
+ assertThat(compatConfig.isChangeEnabled(4, applicationInfo)).isFalse();
+
+ assertThat(compatConfig.disableTargetSdkChangesForPackage("foo.bar", 3)).isEqualTo(1);
+ assertThat(compatConfig.isChangeEnabled(3, applicationInfo)).isFalse();
+ assertThat(compatConfig.isChangeEnabled(4, applicationInfo)).isFalse();
+ }
+
+ @Test
public void testLookupChangeId() throws Exception {
CompatConfig compatConfig = CompatConfigBuilder.create(mBuildClassifier, mContext)
.addEnabledChangeWithIdAndName(1234L, "MY_CHANGE")
diff --git a/services/tests/servicestests/src/com/android/server/compat/OverrideValidatorImplTest.java b/services/tests/servicestests/src/com/android/server/compat/OverrideValidatorImplTest.java
index b14291b..425c724 100644
--- a/services/tests/servicestests/src/com/android/server/compat/OverrideValidatorImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/compat/OverrideValidatorImplTest.java
@@ -20,6 +20,7 @@
import static com.android.internal.compat.OverrideAllowedState.DISABLED_NON_TARGET_SDK;
import static com.android.internal.compat.OverrideAllowedState.DISABLED_NOT_DEBUGGABLE;
import static com.android.internal.compat.OverrideAllowedState.DISABLED_TARGET_SDK_TOO_HIGH;
+import static com.android.internal.compat.OverrideAllowedState.LOGGING_ONLY_CHANGE;
import static com.google.common.truth.Truth.assertThat;
@@ -78,6 +79,7 @@
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+ android.app.compat.ChangeIdStateCache.disable();
when(mContext.getPackageManager()).thenReturn(mPackageManager);
}
@@ -89,7 +91,8 @@
.addTargetSdkChangeWithId(TARGET_SDK, 2)
.addTargetSdkChangeWithId(TARGET_SDK_AFTER, 3)
.addEnabledChangeWithId(4)
- .addDisabledChangeWithId(5).build();
+ .addDisabledChangeWithId(5)
+ .addLoggingOnlyChangeWithId(6).build();
IOverrideValidator overrideValidator = config.getOverrideValidator();
when(mPackageManager.getApplicationInfo(eq(PACKAGE_NAME), anyInt()))
.thenReturn(ApplicationInfoBuilder.create()
@@ -107,6 +110,8 @@
overrideValidator.getOverrideAllowedState(4, PACKAGE_NAME);
OverrideAllowedState stateDisabledChange =
overrideValidator.getOverrideAllowedState(5, PACKAGE_NAME);
+ OverrideAllowedState stateDLoggingOnlyChange =
+ overrideValidator.getOverrideAllowedState(6, PACKAGE_NAME);
assertThat(stateTargetSdkLessChange)
.isEqualTo(new OverrideAllowedState(ALLOWED, -1, -1));
@@ -118,6 +123,8 @@
.isEqualTo(new OverrideAllowedState(ALLOWED, -1, -1));
assertThat(stateDisabledChange)
.isEqualTo(new OverrideAllowedState(ALLOWED, -1, -1));
+ assertThat(stateDLoggingOnlyChange)
+ .isEqualTo(new OverrideAllowedState(LOGGING_ONLY_CHANGE, -1, -1));
}
@Test
@@ -128,7 +135,8 @@
.addTargetSdkChangeWithId(TARGET_SDK, 2)
.addTargetSdkChangeWithId(TARGET_SDK_AFTER, 3)
.addEnabledChangeWithId(4)
- .addDisabledChangeWithId(5).build();
+ .addDisabledChangeWithId(5)
+ .addLoggingOnlyChangeWithId(6).build();
IOverrideValidator overrideValidator = config.getOverrideValidator();
when(mPackageManager.getApplicationInfo(eq(PACKAGE_NAME), anyInt()))
.thenReturn(ApplicationInfoBuilder.create()
@@ -145,6 +153,8 @@
overrideValidator.getOverrideAllowedState(4, PACKAGE_NAME);
OverrideAllowedState stateDisabledChange =
overrideValidator.getOverrideAllowedState(5, PACKAGE_NAME);
+ OverrideAllowedState stateDLoggingOnlyChange =
+ overrideValidator.getOverrideAllowedState(6, PACKAGE_NAME);
assertThat(stateTargetSdkLessChange)
.isEqualTo(new OverrideAllowedState(ALLOWED, -1, -1));
@@ -156,6 +166,8 @@
.isEqualTo(new OverrideAllowedState(ALLOWED, -1, -1));
assertThat(stateDisabledChange)
.isEqualTo(new OverrideAllowedState(ALLOWED, -1, -1));
+ assertThat(stateDLoggingOnlyChange)
+ .isEqualTo(new OverrideAllowedState(LOGGING_ONLY_CHANGE, -1, -1));
}
@Test
@@ -164,7 +176,8 @@
CompatConfig config = CompatConfigBuilder.create(betaBuild(), mContext)
.addTargetSdkChangeWithId(TARGET_SDK_BEFORE, 1)
.addTargetSdkChangeWithId(TARGET_SDK, 2)
- .addTargetSdkChangeWithId(TARGET_SDK_AFTER, 3).build();
+ .addTargetSdkChangeWithId(TARGET_SDK_AFTER, 3)
+ .addDisabledChangeWithId(4).build();
IOverrideValidator overrideValidator = config.getOverrideValidator();
when(mPackageManager.getApplicationInfo(eq(PACKAGE_NAME), anyInt()))
.thenReturn(ApplicationInfoBuilder.create()
@@ -178,6 +191,8 @@
overrideValidator.getOverrideAllowedState(2, PACKAGE_NAME);
OverrideAllowedState stateTargetSdkAfterChange =
overrideValidator.getOverrideAllowedState(3, PACKAGE_NAME);
+ OverrideAllowedState stateDisabledChange =
+ overrideValidator.getOverrideAllowedState(4, PACKAGE_NAME);
assertThat(stateTargetSdkLessChange)
.isEqualTo(new OverrideAllowedState(ALLOWED, TARGET_SDK, TARGET_SDK_BEFORE));
@@ -185,6 +200,8 @@
.isEqualTo(new OverrideAllowedState(ALLOWED, TARGET_SDK, TARGET_SDK));
assertThat(stateTargetSdkAfterChange)
.isEqualTo(new OverrideAllowedState(ALLOWED, TARGET_SDK, TARGET_SDK_AFTER));
+ assertThat(stateDisabledChange)
+ .isEqualTo(new OverrideAllowedState(ALLOWED, TARGET_SDK, -1));
}
@Test
@@ -232,7 +249,8 @@
.addTargetSdkChangeWithId(TARGET_SDK, 2)
.addTargetSdkChangeWithId(TARGET_SDK_AFTER, 3)
.addEnabledChangeWithId(4)
- .addDisabledChangeWithId(5).build();
+ .addDisabledChangeWithId(5)
+ .addLoggingOnlyChangeWithId(6).build();
IOverrideValidator overrideValidator = config.getOverrideValidator();
when(mPackageManager.getApplicationInfo(eq(PACKAGE_NAME), anyInt()))
.thenReturn(ApplicationInfoBuilder.create()
@@ -249,6 +267,8 @@
overrideValidator.getOverrideAllowedState(4, PACKAGE_NAME);
OverrideAllowedState stateDisabledChange =
overrideValidator.getOverrideAllowedState(5, PACKAGE_NAME);
+ OverrideAllowedState stateDLoggingOnlyChange =
+ overrideValidator.getOverrideAllowedState(6, PACKAGE_NAME);
assertThat(stateTargetSdkLessChange)
.isEqualTo(new OverrideAllowedState(DISABLED_NOT_DEBUGGABLE, -1, -1));
@@ -260,6 +280,8 @@
.isEqualTo(new OverrideAllowedState(DISABLED_NOT_DEBUGGABLE, -1, -1));
assertThat(stateDisabledChange)
.isEqualTo(new OverrideAllowedState(DISABLED_NOT_DEBUGGABLE, -1, -1));
+ assertThat(stateDLoggingOnlyChange)
+ .isEqualTo(new OverrideAllowedState(LOGGING_ONLY_CHANGE, -1, -1));
}
@Test
@@ -326,21 +348,22 @@
}
@Test
- public void getOverrideAllowedState_finalBuildDisabledChangeDebugApp_rejectOverride()
+ public void getOverrideAllowedState_finalBuildDisabledChangeDebugApp_allowOverride()
throws Exception {
CompatConfig config = CompatConfigBuilder.create(finalBuild(), mContext)
- .addDisabledChangeWithId(1).build();
+ .addDisabledChangeWithId(1).build();
IOverrideValidator overrideValidator = config.getOverrideValidator();
when(mPackageManager.getApplicationInfo(eq(PACKAGE_NAME), anyInt()))
.thenReturn(ApplicationInfoBuilder.create()
.withPackageName(PACKAGE_NAME)
+ .withTargetSdk(TARGET_SDK)
.debuggable().build());
OverrideAllowedState allowedState =
overrideValidator.getOverrideAllowedState(1, PACKAGE_NAME);
assertThat(allowedState)
- .isEqualTo(new OverrideAllowedState(DISABLED_NON_TARGET_SDK, -1, -1));
+ .isEqualTo(new OverrideAllowedState(ALLOWED, TARGET_SDK, -1));
}
@Test
@@ -351,7 +374,8 @@
.addTargetSdkChangeWithId(TARGET_SDK, 2)
.addTargetSdkChangeWithId(TARGET_SDK_AFTER, 3)
.addEnabledChangeWithId(4)
- .addDisabledChangeWithId(5).build();
+ .addDisabledChangeWithId(5)
+ .addLoggingOnlyChangeWithId(6).build();
IOverrideValidator overrideValidator = config.getOverrideValidator();
when(mPackageManager.getApplicationInfo(eq(PACKAGE_NAME), anyInt()))
.thenReturn(ApplicationInfoBuilder.create()
@@ -368,6 +392,8 @@
overrideValidator.getOverrideAllowedState(4, PACKAGE_NAME);
OverrideAllowedState stateDisabledChange =
overrideValidator.getOverrideAllowedState(5, PACKAGE_NAME);
+ OverrideAllowedState stateDLoggingOnlyChange =
+ overrideValidator.getOverrideAllowedState(6, PACKAGE_NAME);
assertThat(stateTargetSdkLessChange)
.isEqualTo(new OverrideAllowedState(DISABLED_NOT_DEBUGGABLE, -1, -1));
@@ -379,5 +405,7 @@
.isEqualTo(new OverrideAllowedState(DISABLED_NOT_DEBUGGABLE, -1, -1));
assertThat(stateDisabledChange)
.isEqualTo(new OverrideAllowedState(DISABLED_NOT_DEBUGGABLE, -1, -1));
+ assertThat(stateDLoggingOnlyChange)
+ .isEqualTo(new OverrideAllowedState(LOGGING_ONLY_CHANGE, -1, -1));
}
}
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
index 5ad81b2..c1bcf1f 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java
@@ -22,8 +22,6 @@
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.backup.IBackupManager;
-import android.app.timedetector.TimeDetector;
-import android.app.timezonedetector.TimeZoneDetector;
import android.app.usage.UsageStatsManagerInternal;
import android.content.Context;
import android.content.Intent;
@@ -236,16 +234,6 @@
AlarmManager getAlarmManager() {return services.alarmManager;}
@Override
- TimeDetector getTimeDetector() {
- return services.timeDetector;
- }
-
- @Override
- TimeZoneDetector getTimeZoneDetector() {
- return services.timeZoneDetector;
- }
-
- @Override
LockPatternUtils newLockPatternUtils() {
return services.lockPatternUtils;
}
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
index ac818ea..d038d6c 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java
@@ -67,9 +67,6 @@
import android.app.admin.DevicePolicyManagerInternal;
import android.app.admin.FactoryResetProtectionPolicy;
import android.app.admin.PasswordMetrics;
-import android.app.timedetector.ManualTimeSuggestion;
-import android.app.timezonedetector.ManualTimeZoneSuggestion;
-import android.app.timezonedetector.TimeZoneDetector;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
@@ -3875,79 +3872,80 @@
Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
}
- public void testSetAutoTimeModifiesSetting() throws Exception {
+ public void testSetAutoTimeEnabledModifiesSetting() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupDeviceOwner();
- dpm.setAutoTime(admin1, true);
+ dpm.setAutoTimeEnabled(admin1, true);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
- dpm.setAutoTime(admin1, false);
+ dpm.setAutoTimeEnabled(admin1, false);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
}
- public void testSetAutoTimeWithPOOnUser0() throws Exception {
+ public void testSetAutoTimeEnabledWithPOOnUser0() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupProfileOwnerOnUser0();
- dpm.setAutoTime(admin1, true);
+ dpm.setAutoTimeEnabled(admin1, true);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
- dpm.setAutoTime(admin1, false);
+ dpm.setAutoTimeEnabled(admin1, false);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
}
- public void testSetAutoTimeFailWithPONotOnUser0() throws Exception {
+ public void testSetAutoTimeEnabledFailWithPONotOnUser0() throws Exception {
setupProfileOwner();
- assertExpectException(SecurityException.class, null, () -> dpm.setAutoTime(admin1, false));
+ assertExpectException(SecurityException.class, null,
+ () -> dpm.setAutoTimeEnabled(admin1, false));
verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
}
- public void testSetAutoTimeWithPOOfOrganizationOwnedDevice() throws Exception {
+ public void testSetAutoTimeEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
setupProfileOwner();
configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
- dpm.setAutoTime(admin1, true);
+ dpm.setAutoTimeEnabled(admin1, true);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
- dpm.setAutoTime(admin1, false);
+ dpm.setAutoTimeEnabled(admin1, false);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
}
- public void testSetAutoTimeZoneModifiesSetting() throws Exception {
+ public void testSetAutoTimeZoneEnabledModifiesSetting() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupDeviceOwner();
- dpm.setAutoTimeZone(admin1, true);
+ dpm.setAutoTimeZoneEnabled(admin1, true);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
- dpm.setAutoTimeZone(admin1, false);
+ dpm.setAutoTimeZoneEnabled(admin1, false);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
}
- public void testSetAutoTimeZoneWithPOOnUser0() throws Exception {
+ public void testSetAutoTimeZoneEnabledWithPOOnUser0() throws Exception {
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupProfileOwnerOnUser0();
- dpm.setAutoTimeZone(admin1, true);
+ dpm.setAutoTimeZoneEnabled(admin1, true);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
- dpm.setAutoTimeZone(admin1, false);
+ dpm.setAutoTimeZoneEnabled(admin1, false);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
}
- public void testSetAutoTimeZoneFailWithPONotOnUser0() throws Exception {
+ public void testSetAutoTimeZoneEnabledFailWithPONotOnUser0() throws Exception {
setupProfileOwner();
assertExpectException(SecurityException.class, null,
- () -> dpm.setAutoTimeZone(admin1, false));
+ () -> dpm.setAutoTimeZoneEnabled(admin1, false));
verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE,
0);
}
- public void testSetAutoTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
+ public void testSetAutoTimeZoneEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
setupProfileOwner();
configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
- dpm.setAutoTimeZone(admin1, true);
+ dpm.setAutoTimeZoneEnabled(admin1, true);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
- dpm.setAutoTimeZone(admin1, false);
+ dpm.setAutoTimeZoneEnabled(admin1, false);
verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
}
@@ -3969,19 +3967,7 @@
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupDeviceOwner();
dpm.setTime(admin1, 0);
-
- BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
- @Override
- public boolean matches(Object item) {
- final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
- return suggestion.getUtcTime().getValue() == 0;
- }
- @Override
- public void describeTo(Description description) {
- description.appendText("ManualTimeSuggestion{utcTime.value=0}");
- }
- };
- verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
+ verify(getServices().alarmManager).setTime(0);
}
public void testSetTimeFailWithPO() throws Exception {
@@ -3993,19 +3979,7 @@
setupProfileOwner();
configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
dpm.setTime(admin1, 0);
-
- BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
- @Override
- public boolean matches(Object item) {
- final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
- return suggestion.getUtcTime().getValue() == 0;
- }
- @Override
- public void describeTo(Description description) {
- description.appendText("ManualTimeSuggestion{utcTime.value=0}");
- }
- };
- verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
+ verify(getServices().alarmManager).setTime(0);
}
public void testSetTimeWithAutoTimeOn() throws Exception {
@@ -4020,9 +3994,7 @@
mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
setupDeviceOwner();
dpm.setTimeZone(admin1, "Asia/Shanghai");
- ManualTimeZoneSuggestion suggestion =
- TimeZoneDetector.createManualTimeZoneSuggestion("Asia/Shanghai", "Test debug info");
- verify(getServices().timeZoneDetector).suggestManualTimeZone(suggestion);
+ verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
}
public void testSetTimeZoneFailWithPO() throws Exception {
@@ -4035,9 +4007,7 @@
setupProfileOwner();
configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
dpm.setTimeZone(admin1, "Asia/Shanghai");
- ManualTimeZoneSuggestion suggestion =
- TimeZoneDetector.createManualTimeZoneSuggestion("Asia/Shanghai", "Test debug info");
- verify(getServices().timeZoneDetector).suggestManualTimeZone(suggestion);
+ verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
}
public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
@@ -5873,7 +5843,7 @@
assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
}
- public void testSetProtectedPackages_asDO() throws Exception {
+ public void testSetUserControlDisabledPackages_asDO() throws Exception {
final List<String> testPackages = new ArrayList<>();
testPackages.add("package_1");
testPackages.add("package_2");
@@ -5881,14 +5851,14 @@
mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
setDeviceOwner();
- dpm.setProtectedPackages(admin1, testPackages);
+ dpm.setUserControlDisabledPackages(admin1, testPackages);
verify(getServices().packageManagerInternal).setDeviceOwnerProtectedPackages(testPackages);
- assertEquals(testPackages, dpm.getProtectedPackages(admin1));
+ assertEquals(testPackages, dpm.getUserControlDisabledPackages(admin1));
}
- public void testSetProtectedPackages_failingAsPO() throws Exception {
+ public void testSetUserControlDisabledPackages_failingAsPO() throws Exception {
final List<String> testPackages = new ArrayList<>();
testPackages.add("package_1");
testPackages.add("package_2");
@@ -5897,10 +5867,10 @@
setAsProfileOwner(admin1);
assertExpectException(SecurityException.class, /* messageRegex= */ null,
- () -> dpm.setProtectedPackages(admin1, testPackages));
+ () -> dpm.setUserControlDisabledPackages(admin1, testPackages));
assertExpectException(SecurityException.class, /* messageRegex= */ null,
- () -> dpm.getProtectedPackages(admin1));
+ () -> dpm.getUserControlDisabledPackages(admin1));
}
private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java
index 12228c1..8625a1e 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java
@@ -207,8 +207,6 @@
switch (name) {
case Context.ALARM_SERVICE:
return mMockSystemServices.alarmManager;
- case Context.TIME_DETECTOR_SERVICE:
- return mMockSystemServices.timeDetector;
case Context.USER_SERVICE:
return mMockSystemServices.userManager;
case Context.POWER_SERVICE:
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
index 01f1a3e..bbd4472 100644
--- a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
+++ b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java
@@ -33,8 +33,6 @@
import android.app.IActivityTaskManager;
import android.app.NotificationManager;
import android.app.backup.IBackupManager;
-import android.app.timedetector.TimeDetector;
-import android.app.timezonedetector.TimeZoneDetector;
import android.app.usage.UsageStatsManagerInternal;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
@@ -118,8 +116,6 @@
public final TelephonyManager telephonyManager;
public final AccountManager accountManager;
public final AlarmManager alarmManager;
- public final TimeDetector timeDetector;
- public final TimeZoneDetector timeZoneDetector;
public final KeyChain.KeyChainConnection keyChainConnection;
public final CrossProfileApps crossProfileApps;
public final PersistentDataBlockManagerInternal persistentDataBlockManagerInternal;
@@ -164,8 +160,6 @@
telephonyManager = mock(TelephonyManager.class);
accountManager = mock(AccountManager.class);
alarmManager = mock(AlarmManager.class);
- timeDetector = mock(TimeDetector.class);
- timeZoneDetector = mock(TimeZoneDetector.class);
keyChainConnection = mock(KeyChain.KeyChainConnection.class, RETURNS_DEEP_STUBS);
crossProfileApps = mock(CrossProfileApps.class);
persistentDataBlockManagerInternal = mock(PersistentDataBlockManagerInternal.class);
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
index 0551f2e..a587029 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceAudioSystemTest.java
@@ -538,6 +538,7 @@
}
@Test
+ @Ignore("b/151150320")
public void handleSystemAudioModeRequest_fromNonTV_tVNotSupport() {
HdmiCecMessage message =
HdmiCecMessageBuilder.buildSystemAudioModeRequest(
@@ -587,6 +588,7 @@
}
@Test
+ @Ignore("b/151150320")
public void handleRoutingChange_currentActivePortIsHome() {
HdmiCecMessage message =
HdmiCecMessageBuilder.buildRoutingChange(ADDR_TV, 0x3000, SELF_PHYSICAL_ADDRESS);
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
index 4a1af51..f72d622 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDevicePlaybackTest.java
@@ -139,6 +139,7 @@
}
@Test
+ @Ignore("b/151147315")
public void doNotWakeUpOnHotPlug_PlugIn() {
mWokenUp = false;
mHdmiCecLocalDevicePlayback.onHotplug(0, true);
@@ -146,6 +147,7 @@
}
@Test
+ @Ignore("b/151147315")
public void doNotWakeUpOnHotPlug_PlugOut() {
mWokenUp = false;
mHdmiCecLocalDevicePlayback.onHotplug(0, false);
diff --git a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
index e2b63e2..d3a3e7e 100644
--- a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
@@ -28,6 +28,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -62,7 +63,6 @@
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
-import android.security.FileIntegrityManager;
import androidx.test.InstrumentationRegistry;
@@ -136,7 +136,6 @@
@Mock RuleEvaluationEngine mRuleEvaluationEngine;
@Mock IntegrityFileManager mIntegrityFileManager;
@Mock Handler mHandler;
- FileIntegrityManager mFileIntegrityManager;
private final Context mRealContext = InstrumentationRegistry.getTargetContext();
@@ -165,16 +164,12 @@
Files.copy(inputStream, mTestApkSourceStamp.toPath(), REPLACE_EXISTING);
}
- mFileIntegrityManager =
- (FileIntegrityManager)
- mRealContext.getSystemService(Context.FILE_INTEGRITY_SERVICE);
mService =
new AppIntegrityManagerServiceImpl(
mMockContext,
mPackageManagerInternal,
mRuleEvaluationEngine,
mIntegrityFileManager,
- mFileIntegrityManager,
mHandler);
mSpyPackageManager = spy(mRealContext.getPackageManager());
@@ -327,6 +322,11 @@
// we cannot check installer cert because it seems to be device specific.
assertEquals(VERSION_CODE, appInstallMetadata.getVersionCode());
assertFalse(appInstallMetadata.isPreInstalled());
+ // Asserting source stamp not present.
+ assertFalse(appInstallMetadata.isStampPresent());
+ assertFalse(appInstallMetadata.isStampVerified());
+ assertFalse(appInstallMetadata.isStampTrusted());
+ assertNull(appInstallMetadata.getStampCertificateHash());
// These are hardcoded in the test apk android manifest
Map<String, String> allowedInstallers =
appInstallMetadata.getAllowedInstallersAndCertificates();
@@ -379,7 +379,7 @@
AppInstallMetadata appInstallMetadata = metadataCaptor.getValue();
assertTrue(appInstallMetadata.isStampPresent());
assertTrue(appInstallMetadata.isStampVerified());
- assertFalse(appInstallMetadata.isStampTrusted());
+ assertTrue(appInstallMetadata.isStampTrusted());
assertEquals(SOURCE_STAMP_CERTIFICATE_HASH, appInstallMetadata.getStampCertificateHash());
}
@@ -480,6 +480,13 @@
assertThat(mService.getCurrentRules().getList()).containsExactly(rule);
}
+ @Test
+ public void getWhitelistedRuleProviders() throws Exception {
+ whitelistUsAsRuleProvider();
+
+ assertThat(mService.getWhitelistedRuleProviders()).containsExactly(TEST_FRAMEWORK_PACKAGE);
+ }
+
private void whitelistUsAsRuleProvider() {
Resources mockResources = mock(Resources.class);
when(mockResources.getStringArray(R.array.config_integrityRuleProviderPackages))
diff --git a/services/tests/servicestests/src/com/android/server/lights/LightsServiceTest.java b/services/tests/servicestests/src/com/android/server/lights/LightsServiceTest.java
index b0def60..ccbaee4 100644
--- a/services/tests/servicestests/src/com/android/server/lights/LightsServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/lights/LightsServiceTest.java
@@ -18,6 +18,11 @@
import static android.hardware.lights.LightsRequest.Builder;
+import static android.graphics.Color.BLACK;
+import static android.graphics.Color.BLUE;
+import static android.graphics.Color.GREEN;
+import static android.graphics.Color.WHITE;
+
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
@@ -92,7 +97,7 @@
// When the session requests to turn 3/4 lights on:
LightsManager.LightsSession session = manager.openSession();
- session.setLights(new Builder()
+ session.requestLights(new Builder()
.setLight(manager.getLights().get(0), new LightState(0xf1))
.setLight(manager.getLights().get(1), new LightState(0xf2))
.setLight(manager.getLights().get(2), new LightState(0xf3))
@@ -114,18 +119,18 @@
Light micLight = manager.getLights().get(0);
// The light should begin by being off.
- assertThat(manager.getLightState(micLight).getColor()).isEqualTo(0x00000000);
+ assertThat(manager.getLightState(micLight).getColor()).isEqualTo(BLACK);
// When a session commits changes:
LightsManager.LightsSession session = manager.openSession();
- session.setLights(new Builder().setLight(micLight, new LightState(0xff00ff00)).build());
+ session.requestLights(new Builder().setLight(micLight, new LightState(GREEN)).build());
// Then the light should turn on.
- assertThat(manager.getLightState(micLight).getColor()).isEqualTo(0xff00ff00);
+ assertThat(manager.getLightState(micLight).getColor()).isEqualTo(GREEN);
// When the session goes away:
session.close();
// Then the light should turn off.
- assertThat(manager.getLightState(micLight).getColor()).isEqualTo(0x00000000);
+ assertThat(manager.getLightState(micLight).getColor()).isEqualTo(BLACK);
}
@Test
@@ -138,15 +143,15 @@
LightsManager.LightsSession session2 = manager.openSession();
// When session1 and session2 both request the same light:
- session1.setLights(new Builder().setLight(micLight, new LightState(0xff0000ff)).build());
- session2.setLights(new Builder().setLight(micLight, new LightState(0xffffffff)).build());
+ session1.requestLights(new Builder().setLight(micLight, new LightState(BLUE)).build());
+ session2.requestLights(new Builder().setLight(micLight, new LightState(WHITE)).build());
// Then session1 should win because it was created first.
- assertThat(manager.getLightState(micLight).getColor()).isEqualTo(0xff0000ff);
+ assertThat(manager.getLightState(micLight).getColor()).isEqualTo(BLUE);
// When session1 goes away:
session1.close();
// Then session2 should have its request go into effect.
- assertThat(manager.getLightState(micLight).getColor()).isEqualTo(0xffffffff);
+ assertThat(manager.getLightState(micLight).getColor()).isEqualTo(WHITE);
// When session2 goes away:
session2.close();
@@ -162,10 +167,10 @@
// When the session turns a light on:
LightsManager.LightsSession session = manager.openSession();
- session.setLights(new Builder().setLight(micLight, new LightState(0xffffffff)).build());
+ session.requestLights(new Builder().setLight(micLight, new LightState(WHITE)).build());
// And then the session clears it again:
- session.setLights(new Builder().clearLight(micLight).build());
+ session.requestLights(new Builder().clearLight(micLight).build());
// Then the light should turn back off.
assertThat(manager.getLightState(micLight).getColor()).isEqualTo(0);
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
index 2e77c9f..684bbd4 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
@@ -236,6 +236,7 @@
@Test
public void testSetLockCredential_forProfileWithSeparateChallenge_updatesCredentials()
throws Exception {
+ mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, true, null);
initializeStorageWithCredential(
MANAGED_PROFILE_USER_ID,
newPattern("12345"),
diff --git a/services/tests/servicestests/src/com/android/server/people/data/ConversationStoreTest.java b/services/tests/servicestests/src/com/android/server/people/data/ConversationStoreTest.java
index 4e63237..e10cbbf 100644
--- a/services/tests/servicestests/src/com/android/server/people/data/ConversationStoreTest.java
+++ b/services/tests/servicestests/src/com/android/server/people/data/ConversationStoreTest.java
@@ -273,9 +273,8 @@
// Ensure that futures were cancelled and the immediate flush occurred.
assertEquals(0, mMockScheduledExecutorService.getFutures().size());
- // Expect to see 2 executes: loadConversationFromDisk and saveConversationsToDisk.
- // loadConversationFromDisk gets called each time we call #resetConversationStore().
- assertEquals(2, mMockScheduledExecutorService.getExecutes().size());
+ // Expect to see 1 execute: saveConversationsToDisk.
+ assertEquals(1, mMockScheduledExecutorService.getExecutes().size());
resetConversationStore();
ConversationInfo out1 = mConversationStore.getConversation(SHORTCUT_ID);
diff --git a/services/tests/servicestests/src/com/android/server/people/data/DataManagerTest.java b/services/tests/servicestests/src/com/android/server/people/data/DataManagerTest.java
index 624b67c..5199604 100644
--- a/services/tests/servicestests/src/com/android/server/people/data/DataManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/people/data/DataManagerTest.java
@@ -183,6 +183,11 @@
when(mExecutorService.scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(
TimeUnit.class))).thenReturn(mScheduledFuture);
+ doAnswer(ans -> {
+ Runnable runnable = (Runnable) ans.getArguments()[0];
+ runnable.run();
+ return null;
+ }).when(mExecutorService).execute(any(Runnable.class));
when(mUserManager.getEnabledProfiles(USER_ID_PRIMARY))
.thenReturn(Arrays.asList(
@@ -269,7 +274,7 @@
assertEquals(1, conversations.size());
assertEquals("sc_1", conversations.get(0).getShortcutId());
- mDataManager.onUserStopped(USER_ID_PRIMARY);
+ mDataManager.onUserStopping(USER_ID_PRIMARY);
conversations = getConversationsInPrimary();
assertTrue(conversations.isEmpty());
}
diff --git a/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java
index bd63f3c..155c6dd 100644
--- a/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/tv/tunerresourcemanager/TunerResourceManagerServiceTest.java
@@ -26,12 +26,14 @@
import android.media.tv.TvInputManager;
import android.media.tv.TvInputService;
import android.media.tv.tuner.frontend.FrontendSettings;
+import android.media.tv.tunerresourcemanager.IResourcesReclaimListener;
import android.media.tv.tunerresourcemanager.ResourceClientProfile;
+import android.media.tv.tunerresourcemanager.TunerDemuxRequest;
+import android.media.tv.tunerresourcemanager.TunerDescramblerRequest;
import android.media.tv.tunerresourcemanager.TunerFrontendInfo;
import android.media.tv.tunerresourcemanager.TunerFrontendRequest;
import android.media.tv.tunerresourcemanager.TunerResourceManager;
import android.os.RemoteException;
-import android.util.SparseArray;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
@@ -45,9 +47,8 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.List;
+import java.util.Map;
/**
* Tests for {@link TunerResourceManagerService} class.
@@ -59,7 +60,19 @@
private Context mContextSpy;
@Mock private ITvInputManager mITvInputManagerMock;
private TunerResourceManagerService mTunerResourceManagerService;
- private int mReclaimingId;
+
+ private static final class TestResourcesReclaimListener extends IResourcesReclaimListener.Stub {
+ boolean mReclaimed;
+
+ @Override
+ public void onReclaimResources() {
+ mReclaimed = true;
+ }
+
+ public boolean isRelaimed() {
+ return mReclaimed;
+ }
+ }
// A correspondence to compare a FrontendResource and a TunerFrontendInfo.
private static final Correspondence<FrontendResource, TunerFrontendInfo> FR_TFI_COMPARE =
@@ -81,15 +94,11 @@
}
};
- private static <T> List<T> sparseArrayToList(SparseArray<T> sparseArray) {
- if (sparseArray == null) {
- return null;
+ private static int getResourceIdFromHandle(int resourceHandle) {
+ if (resourceHandle == TunerResourceManager.INVALID_RESOURCE_HANDLE) {
+ return resourceHandle;
}
- List<T> arrayList = new ArrayList<T>(sparseArray.size());
- for (int i = 0; i < sparseArray.size(); i++) {
- arrayList.add(sparseArray.valueAt(i));
- }
- return arrayList;
+ return (resourceHandle & 0x00ff0000) >> 16;
}
@Before
@@ -98,14 +107,8 @@
TvInputManager tvInputManager = new TvInputManager(mITvInputManagerMock, 0);
mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getTargetContext()));
when(mContextSpy.getSystemService(Context.TV_INPUT_SERVICE)).thenReturn(tvInputManager);
- mTunerResourceManagerService = new TunerResourceManagerService(mContextSpy) {
- @Override
- protected void reclaimFrontendResource(int reclaimingId) {
- mReclaimingId = reclaimingId;
- }
- };
+ mTunerResourceManagerService = new TunerResourceManagerService(mContextSpy);
mTunerResourceManagerService.onStart(true /*isForTesting*/);
- mReclaimingId = -1;
}
@Test
@@ -118,7 +121,7 @@
new TunerFrontendInfo(1 /*id*/, FrontendSettings.TYPE_DVBT, 1 /*exclusiveGroupId*/);
mTunerResourceManagerService.setFrontendInfoListInternal(infos);
- SparseArray<FrontendResource> resources =
+ Map<Integer, FrontendResource> resources =
mTunerResourceManagerService.getFrontendResources();
for (int id = 0; id < infos.length; id++) {
assertThat(resources.get(infos[id].getId())
@@ -128,7 +131,7 @@
assertThat(resources.get(infos[id].getId())
.getExclusiveGroupMemberFeIds().size()).isEqualTo(0);
}
- assertThat(sparseArrayToList(resources)).comparingElementsUsing(FR_TFI_COMPARE)
+ assertThat(resources.values()).comparingElementsUsing(FR_TFI_COMPARE)
.containsExactlyElementsIn(Arrays.asList(infos));
}
@@ -146,19 +149,15 @@
new TunerFrontendInfo(3 /*id*/, FrontendSettings.TYPE_ATSC, 1 /*exclusiveGroupId*/);
mTunerResourceManagerService.setFrontendInfoListInternal(infos);
- SparseArray<FrontendResource> resources =
+ Map<Integer, FrontendResource> resources =
mTunerResourceManagerService.getFrontendResources();
- assertThat(sparseArrayToList(resources)).comparingElementsUsing(FR_TFI_COMPARE)
+ assertThat(resources.values()).comparingElementsUsing(FR_TFI_COMPARE)
.containsExactlyElementsIn(Arrays.asList(infos));
- assertThat(resources.get(0).getExclusiveGroupMemberFeIds())
- .isEqualTo(new ArrayList<Integer>());
- assertThat(resources.get(1).getExclusiveGroupMemberFeIds())
- .isEqualTo(new ArrayList<Integer>(Arrays.asList(2, 3)));
- assertThat(resources.get(2).getExclusiveGroupMemberFeIds())
- .isEqualTo(new ArrayList<Integer>(Arrays.asList(1, 3)));
- assertThat(resources.get(3).getExclusiveGroupMemberFeIds())
- .isEqualTo(new ArrayList<Integer>(Arrays.asList(1, 2)));
+ assertThat(resources.get(0).getExclusiveGroupMemberFeIds()).isEmpty();
+ assertThat(resources.get(1).getExclusiveGroupMemberFeIds()).containsExactly(2, 3);
+ assertThat(resources.get(2).getExclusiveGroupMemberFeIds()).containsExactly(1, 3);
+ assertThat(resources.get(3).getExclusiveGroupMemberFeIds()).containsExactly(1, 2);
}
@Test
@@ -171,11 +170,11 @@
new TunerFrontendInfo(1 /*id*/, FrontendSettings.TYPE_DVBS, 1 /*exclusiveGroupId*/);
mTunerResourceManagerService.setFrontendInfoListInternal(infos);
- SparseArray<FrontendResource> resources0 =
+ Map<Integer, FrontendResource> resources0 =
mTunerResourceManagerService.getFrontendResources();
mTunerResourceManagerService.setFrontendInfoListInternal(infos);
- SparseArray<FrontendResource> resources1 =
+ Map<Integer, FrontendResource> resources1 =
mTunerResourceManagerService.getFrontendResources();
assertThat(resources0).isEqualTo(resources1);
@@ -198,13 +197,13 @@
new TunerFrontendInfo(1 /*id*/, FrontendSettings.TYPE_DVBT, 1 /*exclusiveGroupId*/);
mTunerResourceManagerService.setFrontendInfoListInternal(infos1);
- SparseArray<FrontendResource> resources =
+ Map<Integer, FrontendResource> resources =
mTunerResourceManagerService.getFrontendResources();
for (int id = 0; id < infos1.length; id++) {
assertThat(resources.get(infos1[id].getId())
.getExclusiveGroupMemberFeIds().size()).isEqualTo(0);
}
- assertThat(sparseArrayToList(resources)).comparingElementsUsing(FR_TFI_COMPARE)
+ assertThat(resources.values()).comparingElementsUsing(FR_TFI_COMPARE)
.containsExactlyElementsIn(Arrays.asList(infos1));
}
@@ -225,13 +224,13 @@
new TunerFrontendInfo(1 /*id*/, FrontendSettings.TYPE_DVBT, 1 /*exclusiveGroupId*/);
mTunerResourceManagerService.setFrontendInfoListInternal(infos1);
- SparseArray<FrontendResource> resources =
+ Map<Integer, FrontendResource> resources =
mTunerResourceManagerService.getFrontendResources();
for (int id = 0; id < infos1.length; id++) {
assertThat(resources.get(infos1[id].getId())
.getExclusiveGroupMemberFeIds().size()).isEqualTo(0);
}
- assertThat(sparseArrayToList(resources)).comparingElementsUsing(FR_TFI_COMPARE)
+ assertThat(resources.values()).comparingElementsUsing(FR_TFI_COMPARE)
.containsExactlyElementsIn(Arrays.asList(infos1));
}
@@ -239,14 +238,15 @@
public void requestFrontendTest_ClientNotRegistered() {
TunerFrontendRequest request =
new TunerFrontendRequest(0 /*clientId*/, FrontendSettings.TYPE_DVBT);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isFalse();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isFalse();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(TunerResourceManager.INVALID_FRONTEND_ID);
+ assertThat(getResourceIdFromHandle(frontendHandle[0]))
+ .isEqualTo(TunerResourceManager.INVALID_RESOURCE_HANDLE);
}
@Test
@@ -266,14 +266,15 @@
TunerFrontendRequest request =
new TunerFrontendRequest(clientId[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isFalse();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isFalse();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(TunerResourceManager.INVALID_FRONTEND_ID);
+ assertThat(getResourceIdFromHandle(frontendHandle[0]))
+ .isEqualTo(TunerResourceManager.INVALID_RESOURCE_HANDLE);
}
@Test
@@ -297,14 +298,14 @@
TunerFrontendRequest request =
new TunerFrontendRequest(clientId[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(0);
+ assertThat(getResourceIdFromHandle(frontendHandle[0])).isEqualTo(0);
}
@Test
@@ -332,29 +333,29 @@
new TunerFrontendInfo(2 /*id*/, FrontendSettings.TYPE_DVBS, 1 /*exclusiveGroupId*/);
mTunerResourceManagerService.setFrontendInfoListInternal(infos);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
TunerFrontendRequest request =
new TunerFrontendRequest(clientId1[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(infos[0].getId());
+ assertThat(getResourceIdFromHandle(frontendHandle[0])).isEqualTo(infos[0].getId());
request =
new TunerFrontendRequest(clientId0[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(infos[1].getId());
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[1].getId())
+ assertThat(getResourceIdFromHandle(frontendHandle[0])).isEqualTo(infos[1].getId());
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[1].getId())
.isInUse()).isTrue();
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[2].getId())
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[2].getId())
.isInUse()).isTrue();
}
@@ -369,15 +370,17 @@
int[] clientPriorities = {100, 50};
int[] clientId0 = new int[1];
int[] clientId1 = new int[1];
+ TestResourcesReclaimListener listener = new TestResourcesReclaimListener();
+
mTunerResourceManagerService.registerClientProfileInternal(
- profiles[0], null /*listener*/, clientId0);
+ profiles[0], listener, clientId0);
assertThat(clientId0[0]).isNotEqualTo(TunerResourceManagerService.INVALID_CLIENT_ID);
- mTunerResourceManagerService.getClientProfiles().get(clientId0[0])
+ mTunerResourceManagerService.getClientProfile(clientId0[0])
.setPriority(clientPriorities[0]);
mTunerResourceManagerService.registerClientProfileInternal(
- profiles[1], null /*listener*/, clientId1);
+ profiles[1], new TestResourcesReclaimListener(), clientId1);
assertThat(clientId1[0]).isNotEqualTo(TunerResourceManagerService.INVALID_CLIENT_ID);
- mTunerResourceManagerService.getClientProfiles().get(clientId1[0])
+ mTunerResourceManagerService.getClientProfile(clientId1[0])
.setPriority(clientPriorities[1]);
// Init frontend resources.
@@ -390,10 +393,10 @@
TunerFrontendRequest request =
new TunerFrontendRequest(clientId0[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -401,19 +404,19 @@
request =
new TunerFrontendRequest(clientId1[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isFalse();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isFalse();
+ assertThat(listener.isRelaimed()).isFalse();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(mReclaimingId).isEqualTo(-1);
request =
new TunerFrontendRequest(clientId1[0] /*clientId*/, FrontendSettings.TYPE_DVBS);
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isFalse();
- assertThat(mReclaimingId).isEqualTo(-1);
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isFalse();
+ assertThat(listener.isRelaimed()).isFalse();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -430,15 +433,16 @@
int[] clientPriorities = {100, 500};
int[] clientId0 = new int[1];
int[] clientId1 = new int[1];
+ TestResourcesReclaimListener listener = new TestResourcesReclaimListener();
mTunerResourceManagerService.registerClientProfileInternal(
- profiles[0], null /*listener*/, clientId0);
+ profiles[0], listener, clientId0);
assertThat(clientId0[0]).isNotEqualTo(TunerResourceManagerService.INVALID_CLIENT_ID);
- mTunerResourceManagerService.getClientProfiles().get(clientId0[0])
+ mTunerResourceManagerService.getClientProfile(clientId0[0])
.setPriority(clientPriorities[0]);
mTunerResourceManagerService.registerClientProfileInternal(
- profiles[1], null /*listener*/, clientId1);
+ profiles[1], new TestResourcesReclaimListener(), clientId1);
assertThat(clientId1[0]).isNotEqualTo(TunerResourceManagerService.INVALID_CLIENT_ID);
- mTunerResourceManagerService.getClientProfiles().get(clientId1[0])
+ mTunerResourceManagerService.getClientProfile(clientId1[0])
.setPriority(clientPriorities[1]);
// Init frontend resources.
@@ -451,33 +455,33 @@
TunerFrontendRequest request =
new TunerFrontendRequest(clientId0[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(infos[0].getId());
+ assertThat(getResourceIdFromHandle(frontendHandle[0])).isEqualTo(infos[0].getId());
request =
new TunerFrontendRequest(clientId1[0] /*clientId*/, FrontendSettings.TYPE_DVBS);
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(infos[1].getId());
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[0].getId())
+ assertThat(getResourceIdFromHandle(frontendHandle[0])).isEqualTo(infos[1].getId());
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[0].getId())
.isInUse()).isTrue();
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[1].getId())
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[1].getId())
.isInUse()).isTrue();
- assertThat(mTunerResourceManagerService.getFrontendResources()
- .get(infos[0].getId()).getOwnerClientId()).isEqualTo(clientId1[0]);
- assertThat(mTunerResourceManagerService.getFrontendResources()
- .get(infos[1].getId()).getOwnerClientId()).isEqualTo(clientId1[0]);
- assertThat(mReclaimingId).isEqualTo(clientId0[0]);
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[0].getId())
+ .getOwnerClientId()).isEqualTo(clientId1[0]);
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[1].getId())
+ .getOwnerClientId()).isEqualTo(clientId1[0]);
+ assertThat(listener.isRelaimed()).isTrue();
}
@Test
@@ -500,25 +504,60 @@
TunerFrontendRequest request =
new TunerFrontendRequest(clientId[0] /*clientId*/, FrontendSettings.TYPE_DVBT);
- int[] frontendId = new int[1];
+ int[] frontendHandle = new int[1];
try {
- assertThat(mTunerResourceManagerService.requestFrontendInternal(request, frontendId))
- .isTrue();
+ assertThat(mTunerResourceManagerService
+ .requestFrontendInternal(request, frontendHandle)).isTrue();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- assertThat(frontendId[0]).isEqualTo(infos[0].getId());
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[0].getId())
+ assertThat(getResourceIdFromHandle(frontendHandle[0])).isEqualTo(infos[0].getId());
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[0].getId())
.isInUse()).isTrue();
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[1].getId())
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[1].getId())
.isInUse()).isTrue();
// Unregister client when using frontend
mTunerResourceManagerService.unregisterClientProfileInternal(clientId[0]);
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[0].getId())
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[0].getId())
.isInUse()).isFalse();
- assertThat(mTunerResourceManagerService.getFrontendResources().get(infos[1].getId())
+ assertThat(mTunerResourceManagerService.getFrontendResource(infos[1].getId())
.isInUse()).isFalse();
+ assertThat(mTunerResourceManagerService.checkClientExists(clientId[0])).isFalse();
}
+
+ @Test
+ public void requestDemuxTest() {
+ // Register client
+ ResourceClientProfile profile = new ResourceClientProfile("0" /*sessionId*/,
+ TvInputService.PRIORITY_HINT_USE_CASE_TYPE_PLAYBACK);
+ int[] clientId = new int[1];
+ mTunerResourceManagerService.registerClientProfileInternal(
+ profile, null /*listener*/, clientId);
+ assertThat(clientId[0]).isNotEqualTo(TunerResourceManagerService.INVALID_CLIENT_ID);
+
+ int[] demuxHandle = new int[1];
+ TunerDemuxRequest request = new TunerDemuxRequest(clientId[0]);
+ assertThat(mTunerResourceManagerService.requestDemuxInternal(request, demuxHandle))
+ .isTrue();
+ assertThat(getResourceIdFromHandle(demuxHandle[0])).isEqualTo(0);
+ }
+
+ @Test
+ public void requestDescramblerTest() {
+ // Register client
+ ResourceClientProfile profile = new ResourceClientProfile("0" /*sessionId*/,
+ TvInputService.PRIORITY_HINT_USE_CASE_TYPE_PLAYBACK);
+ int[] clientId = new int[1];
+ mTunerResourceManagerService.registerClientProfileInternal(
+ profile, null /*listener*/, clientId);
+ assertThat(clientId[0]).isNotEqualTo(TunerResourceManagerService.INVALID_CLIENT_ID);
+
+ int[] desHandle = new int[1];
+ TunerDescramblerRequest request = new TunerDescramblerRequest(clientId[0]);
+ assertThat(mTunerResourceManagerService.requestDescramblerInternal(request, desHandle))
+ .isTrue();
+ assertThat(getResourceIdFromHandle(desHandle[0])).isEqualTo(0);
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/usage/AppIdleHistoryTests.java b/services/tests/servicestests/src/com/android/server/usage/AppIdleHistoryTests.java
index 7af3ec6..88f368e 100644
--- a/services/tests/servicestests/src/com/android/server/usage/AppIdleHistoryTests.java
+++ b/services/tests/servicestests/src/com/android/server/usage/AppIdleHistoryTests.java
@@ -20,7 +20,7 @@
import static android.app.usage.UsageStatsManager.REASON_MAIN_FORCED_BY_USER;
import static android.app.usage.UsageStatsManager.REASON_MAIN_TIMEOUT;
import static android.app.usage.UsageStatsManager.REASON_MAIN_USAGE;
-import static android.app.usage.UsageStatsManager.REASON_SUB_RESTRICT_BACKGROUND_RESOURCE_USAGE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE;
import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_ACTIVE;
import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_FREQUENT;
@@ -103,7 +103,8 @@
aih.setAppStandbyBucket(PACKAGE_2, USER_ID, 2000, STANDBY_BUCKET_ACTIVE,
REASON_MAIN_USAGE);
aih.setAppStandbyBucket(PACKAGE_3, USER_ID, 2500, STANDBY_BUCKET_RESTRICTED,
- REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_RESTRICT_BACKGROUND_RESOURCE_USAGE);
+ REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE);
aih.setAppStandbyBucket(PACKAGE_4, USER_ID, 2750, STANDBY_BUCKET_RESTRICTED,
REASON_MAIN_FORCED_BY_USER);
aih.setAppStandbyBucket(PACKAGE_1, USER_ID, 3000, STANDBY_BUCKET_RARE,
@@ -114,7 +115,8 @@
assertEquals(aih.getAppStandbyReason(PACKAGE_1, USER_ID, 3000), REASON_MAIN_TIMEOUT);
assertEquals(aih.getAppStandbyBucket(PACKAGE_3, USER_ID, 3000), STANDBY_BUCKET_RESTRICTED);
assertEquals(aih.getAppStandbyReason(PACKAGE_3, USER_ID, 3000),
- REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_RESTRICT_BACKGROUND_RESOURCE_USAGE);
+ REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE);
assertEquals(aih.getAppStandbyReason(PACKAGE_4, USER_ID, 3000),
REASON_MAIN_FORCED_BY_USER);
@@ -133,7 +135,8 @@
assertEquals(aih.getAppStandbyReason(PACKAGE_1, USER_ID, 5000), REASON_MAIN_TIMEOUT);
assertEquals(aih.getAppStandbyBucket(PACKAGE_3, USER_ID, 3000), STANDBY_BUCKET_RESTRICTED);
assertEquals(aih.getAppStandbyReason(PACKAGE_3, USER_ID, 3000),
- REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_RESTRICT_BACKGROUND_RESOURCE_USAGE);
+ REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE);
assertEquals(aih.getAppStandbyReason(PACKAGE_4, USER_ID, 3000),
REASON_MAIN_FORCED_BY_USER);
diff --git a/services/tests/servicestests/src/com/android/server/usage/AppStandbyControllerTests.java b/services/tests/servicestests/src/com/android/server/usage/AppStandbyControllerTests.java
index 387e62d..f070bff 100644
--- a/services/tests/servicestests/src/com/android/server/usage/AppStandbyControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/usage/AppStandbyControllerTests.java
@@ -28,6 +28,10 @@
import static android.app.usage.UsageStatsManager.REASON_MAIN_PREDICTED;
import static android.app.usage.UsageStatsManager.REASON_MAIN_TIMEOUT;
import static android.app.usage.UsageStatsManager.REASON_MAIN_USAGE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE;
+import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY;
+import static android.app.usage.UsageStatsManager.REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED;
import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE;
import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_MOVE_TO_FOREGROUND;
import static android.app.usage.UsageStatsManager.REASON_SUB_USAGE_SYNC_ADAPTER;
@@ -434,6 +438,11 @@
true);
}
+ private int getStandbyBucketReason(String packageName) {
+ return mController.getAppStandbyBucketReason(packageName, USER_ID,
+ mInjector.mElapsedRealtime);
+ }
+
private void assertBucket(int bucket) {
assertEquals(bucket, getStandbyBucket(mController, PACKAGE_1));
}
@@ -810,7 +819,7 @@
}
@Test
- public void testPredictionRaiseFromRestrictedTimeout() {
+ public void testPredictionRaiseFromRestrictedTimeout_highBucket() {
reportEvent(mController, USER_INTERACTION, mInjector.mElapsedRealtime, PACKAGE_1);
// Way past all timeouts. App times out into RESTRICTED bucket.
@@ -823,6 +832,24 @@
mInjector.mElapsedRealtime += RESTRICTED_THRESHOLD;
mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_ACTIVE,
REASON_MAIN_PREDICTED);
+ assertBucket(STANDBY_BUCKET_ACTIVE);
+ }
+
+ @Test
+ public void testPredictionRaiseFromRestrictedTimeout_lowBucket() {
+ reportEvent(mController, USER_INTERACTION, mInjector.mElapsedRealtime, PACKAGE_1);
+
+ // Way past all timeouts. App times out into RESTRICTED bucket.
+ mInjector.mElapsedRealtime += RESTRICTED_THRESHOLD * 4;
+ mController.checkIdleStates(USER_ID);
+ assertBucket(STANDBY_BUCKET_RESTRICTED);
+
+ // Prediction into a low bucket means no expectation of the app being used, so we shouldn't
+ // elevate the app from RESTRICTED.
+ mInjector.mElapsedRealtime += RESTRICTED_THRESHOLD;
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_RARE,
+ REASON_MAIN_PREDICTED);
+ assertBucket(STANDBY_BUCKET_RESTRICTED);
}
@Test
@@ -987,6 +1014,79 @@
}
@Test
+ public void testSystemForcedFlags_NotAddedForUserForce() throws Exception {
+ final int expectedReason = REASON_MAIN_FORCED_BY_USER;
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_RESTRICTED,
+ REASON_MAIN_FORCED_BY_USER);
+ assertEquals(STANDBY_BUCKET_RESTRICTED, getStandbyBucket(mController, PACKAGE_1));
+ assertEquals(expectedReason, getStandbyBucketReason(PACKAGE_1));
+
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_RESTRICTED,
+ REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE);
+ assertEquals(STANDBY_BUCKET_RESTRICTED, getStandbyBucket(mController, PACKAGE_1));
+ assertEquals(expectedReason, getStandbyBucketReason(PACKAGE_1));
+ }
+
+ @Test
+ public void testSystemForcedFlags_AddedForSystemForce() throws Exception {
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_ACTIVE,
+ REASON_MAIN_DEFAULT);
+ mInjector.mElapsedRealtime += 4 * RESTRICTED_THRESHOLD;
+
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_RESTRICTED,
+ REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE);
+ assertEquals(STANDBY_BUCKET_RESTRICTED, getStandbyBucket(mController, PACKAGE_1));
+ assertEquals(REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE,
+ getStandbyBucketReason(PACKAGE_1));
+
+ mController.restrictApp(PACKAGE_1, USER_ID, REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE);
+ assertEquals(STANDBY_BUCKET_RESTRICTED, getStandbyBucket(mController, PACKAGE_1));
+ // Flags should be combined
+ assertEquals(REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE
+ | REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE, getStandbyBucketReason(PACKAGE_1));
+ }
+
+ @Test
+ public void testSystemForcedFlags_SystemForceChangesBuckets() throws Exception {
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_ACTIVE,
+ REASON_MAIN_DEFAULT);
+ mInjector.mElapsedRealtime += 4 * RESTRICTED_THRESHOLD;
+
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_FREQUENT,
+ REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE);
+ assertEquals(STANDBY_BUCKET_FREQUENT, getStandbyBucket(mController, PACKAGE_1));
+ assertEquals(REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE,
+ getStandbyBucketReason(PACKAGE_1));
+
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_FREQUENT,
+ REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE);
+ assertEquals(STANDBY_BUCKET_FREQUENT, getStandbyBucket(mController, PACKAGE_1));
+ // Flags should be combined
+ assertEquals(REASON_MAIN_FORCED_BY_SYSTEM
+ | REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE
+ | REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE,
+ getStandbyBucketReason(PACKAGE_1));
+
+ mController.setAppStandbyBucket(PACKAGE_1, USER_ID, STANDBY_BUCKET_RARE,
+ REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY);
+ assertEquals(STANDBY_BUCKET_RARE, getStandbyBucket(mController, PACKAGE_1));
+ // Flags should be combined
+ assertEquals(REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY,
+ getStandbyBucketReason(PACKAGE_1));
+
+ mController.restrictApp(PACKAGE_1, USER_ID, REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED);
+ assertEquals(STANDBY_BUCKET_RESTRICTED, getStandbyBucket(mController, PACKAGE_1));
+ // Flags should not be combined since the bucket changed.
+ assertEquals(REASON_MAIN_FORCED_BY_SYSTEM | REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED,
+ getStandbyBucketReason(PACKAGE_1));
+ }
+
+ @Test
public void testAddActiveDeviceAdmin() {
assertActiveAdmins(USER_ID, (String[]) null);
assertActiveAdmins(USER_ID2, (String[]) null);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BubbleCheckerTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BubbleCheckerTest.java
new file mode 100644
index 0000000..9636342
--- /dev/null
+++ b/services/tests/uiservicestests/src/com/android/server/notification/BubbleCheckerTest.java
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2020 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.notification;
+
+import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
+import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
+
+import static junit.framework.Assert.assertTrue;
+
+import static org.junit.Assert.assertFalse;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
+import android.app.ActivityManager;
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.os.UserHandle;
+import android.service.notification.StatusBarNotification;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.UiServiceTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class BubbleCheckerTest extends UiServiceTestCase {
+
+ private static final String SHORTCUT_ID = "shortcut";
+ private static final String PKG = "pkg";
+ private static final String KEY = "key";
+ private static final int USER_ID = 1;
+
+ @Mock
+ ActivityManager mActivityManager;
+ @Mock
+ RankingConfig mRankingConfig;
+ @Mock
+ ShortcutHelper mShortcutHelper;
+
+ @Mock
+ NotificationRecord mNr;
+ @Mock
+ UserHandle mUserHandle;
+ @Mock
+ Notification mNotif;
+ @Mock
+ StatusBarNotification mSbn;
+ @Mock
+ NotificationChannel mChannel;
+ @Mock
+ Notification.BubbleMetadata mBubbleMetadata;
+ @Mock
+ PendingIntent mPendingIntent;
+ @Mock
+ Intent mIntent;
+
+ BubbleExtractor.BubbleChecker mBubbleChecker;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ when(mNr.getKey()).thenReturn(KEY);
+ when(mNr.getSbn()).thenReturn(mSbn);
+ when(mNr.getUser()).thenReturn(mUserHandle);
+ when(mUserHandle.getIdentifier()).thenReturn(USER_ID);
+ when(mNr.getChannel()).thenReturn(mChannel);
+ when(mSbn.getPackageName()).thenReturn(PKG);
+ when(mSbn.getUser()).thenReturn(mUserHandle);
+ when(mNr.getNotification()).thenReturn(mNotif);
+ when(mNotif.getBubbleMetadata()).thenReturn(mBubbleMetadata);
+
+ mBubbleChecker = new BubbleExtractor.BubbleChecker(mContext,
+ mShortcutHelper,
+ mRankingConfig,
+ mActivityManager);
+ }
+
+ void setUpIntentBubble() {
+ when(mPendingIntent.getIntent()).thenReturn(mIntent);
+ when(mBubbleMetadata.getBubbleIntent()).thenReturn(mPendingIntent);
+ when(mBubbleMetadata.getShortcutId()).thenReturn(null);
+ }
+
+ void setUpShortcutBubble(boolean isValid) {
+ when(mBubbleMetadata.getShortcutId()).thenReturn(SHORTCUT_ID);
+ when(mShortcutHelper.hasValidShortcutInfo(SHORTCUT_ID, PKG, mUserHandle))
+ .thenReturn(isValid);
+ when(mBubbleMetadata.getBubbleIntent()).thenReturn(null);
+ }
+
+ void setUpBubblesEnabled(boolean feature, boolean app, boolean channel) {
+ when(mRankingConfig.bubblesEnabled()).thenReturn(feature);
+ when(mRankingConfig.areBubblesAllowed(PKG, USER_ID)).thenReturn(app);
+ when(mChannel.canBubble()).thenReturn(channel);
+ }
+
+ void setUpActivityIntent(boolean isResizable) {
+ when(mPendingIntent.getIntent()).thenReturn(mIntent);
+ ActivityInfo info = new ActivityInfo();
+ info.resizeMode = isResizable
+ ? RESIZE_MODE_RESIZEABLE
+ : RESIZE_MODE_UNRESIZEABLE;
+ when(mIntent.resolveActivityInfo(any(), anyInt())).thenReturn(info);
+ }
+
+ //
+ // canBubble
+ //
+
+ @Test
+ public void testCanBubble_true_intentBubble() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ setUpIntentBubble();
+ setUpActivityIntent(true /* isResizable */);
+ when(mActivityManager.isLowRamDevice()).thenReturn(false);
+ assertTrue(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubble_true_shortcutBubble() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ setUpShortcutBubble(true /* isValid */);
+ assertTrue(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubble_false_noIntentInvalidShortcut() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ setUpShortcutBubble(false /* isValid */);
+ assertFalse(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubble_false_noIntentNoShortcut() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ when(mBubbleMetadata.getBubbleIntent()).thenReturn(null);
+ when(mBubbleMetadata.getShortcutId()).thenReturn(null);
+ assertFalse(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubbble_false_noMetadata() {
+ setUpBubblesEnabled(true/* feature */, true /* app */, true /* channel */);
+ when(mNotif.getBubbleMetadata()).thenReturn(null);
+ assertFalse(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubble_false_bubblesNotEnabled() {
+ setUpBubblesEnabled(false /* feature */, true /* app */, true /* channel */);
+ assertFalse(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubble_false_packageNotAllowed() {
+ setUpBubblesEnabled(true /* feature */, false /* app */, true /* channel */);
+ assertFalse(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ @Test
+ public void testCanBubble_false_channelNotAllowed() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, false /* channel */);
+ assertFalse(mBubbleChecker.canBubble(mNr, PKG, USER_ID));
+ }
+
+ //
+ // canLaunchInActivityView
+ //
+
+ @Test
+ public void testCanLaunchInActivityView_true() {
+ setUpActivityIntent(true /* resizable */);
+ assertTrue(mBubbleChecker.canLaunchInActivityView(mContext, mPendingIntent, PKG));
+ }
+
+ @Test
+ public void testCanLaunchInActivityView_false_noIntent() {
+ when(mPendingIntent.getIntent()).thenReturn(null);
+ assertFalse(mBubbleChecker.canLaunchInActivityView(mContext, mPendingIntent, PKG));
+ }
+
+ @Test
+ public void testCanLaunchInActivityView_false_noInfo() {
+ when(mPendingIntent.getIntent()).thenReturn(mIntent);
+ when(mIntent.resolveActivityInfo(any(), anyInt())).thenReturn(null);
+ assertFalse(mBubbleChecker.canLaunchInActivityView(mContext, mPendingIntent, PKG));
+ }
+
+ @Test
+ public void testCanLaunchInActivityView_false_notResizable() {
+ setUpActivityIntent(false /* resizable */);
+ assertFalse(mBubbleChecker.canLaunchInActivityView(mContext, mPendingIntent, PKG));
+ }
+
+ //
+ // isNotificationAppropriateToBubble
+ //
+
+ @Test
+ public void testIsNotifAppropriateToBubble_true() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ setUpIntentBubble();
+ when(mActivityManager.isLowRamDevice()).thenReturn(false);
+ setUpActivityIntent(true /* resizable */);
+ doReturn(Notification.MessagingStyle.class).when(mNotif).getNotificationStyle();
+
+ assertTrue(mBubbleChecker.isNotificationAppropriateToBubble(mNr));
+ }
+
+ @Test
+ public void testIsNotifAppropriateToBubble_false_lowRam() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ when(mActivityManager.isLowRamDevice()).thenReturn(true);
+ setUpActivityIntent(true /* resizable */);
+ doReturn(Notification.MessagingStyle.class).when(mNotif).getNotificationStyle();
+
+ assertFalse(mBubbleChecker.isNotificationAppropriateToBubble(mNr));
+ }
+
+ @Test
+ public void testIsNotifAppropriateToBubble_false_notMessageStyle() {
+ setUpBubblesEnabled(true /* feature */, true /* app */, true /* channel */);
+ when(mActivityManager.isLowRamDevice()).thenReturn(false);
+ setUpActivityIntent(true /* resizable */);
+ doReturn(Notification.BigPictureStyle.class).when(mNotif).getNotificationStyle();
+
+ assertFalse(mBubbleChecker.isNotificationAppropriateToBubble(mNr));
+ }
+
+}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java
index 7459c4b..c7cef05 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/BubbleExtractorTest.java
@@ -21,6 +21,7 @@
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.app.ActivityManager;
@@ -46,6 +47,7 @@
public class BubbleExtractorTest extends UiServiceTestCase {
@Mock RankingConfig mConfig;
+ BubbleExtractor mBubbleExtractor;
private String mPkg = "com.android.server.notification";
private int mId = 1001;
@@ -57,6 +59,10 @@
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
+ mBubbleExtractor = new BubbleExtractor();
+ mBubbleExtractor.initialize(mContext, mock(NotificationUsageStats.class));
+ mBubbleExtractor.setConfig(mConfig);
+ mBubbleExtractor.setShortcutHelper(mock(ShortcutHelper.class));
}
private NotificationRecord getNotificationRecord(boolean allow, int importanceHigh) {
@@ -83,70 +89,55 @@
@Test
public void testAppYesChannelNo() {
- BubbleExtractor extractor = new BubbleExtractor();
- extractor.setConfig(mConfig);
-
when(mConfig.bubblesEnabled()).thenReturn(true);
when(mConfig.areBubblesAllowed(mPkg, mUid)).thenReturn(true);
NotificationRecord r = getNotificationRecord(false, IMPORTANCE_UNSPECIFIED);
- extractor.process(r);
+ mBubbleExtractor.process(r);
assertFalse(r.canBubble());
}
@Test
public void testAppNoChannelYes() throws Exception {
- BubbleExtractor extractor = new BubbleExtractor();
- extractor.setConfig(mConfig);
-
when(mConfig.bubblesEnabled()).thenReturn(true);
when(mConfig.areBubblesAllowed(mPkg, mUid)).thenReturn(false);
NotificationRecord r = getNotificationRecord(true, IMPORTANCE_HIGH);
- extractor.process(r);
+ mBubbleExtractor.process(r);
assertFalse(r.canBubble());
}
@Test
public void testAppYesChannelYes() {
- BubbleExtractor extractor = new BubbleExtractor();
- extractor.setConfig(mConfig);
-
when(mConfig.bubblesEnabled()).thenReturn(true);
when(mConfig.areBubblesAllowed(mPkg, mUid)).thenReturn(true);
NotificationRecord r = getNotificationRecord(true, IMPORTANCE_UNSPECIFIED);
- extractor.process(r);
+ mBubbleExtractor.process(r);
assertTrue(r.canBubble());
}
@Test
public void testAppNoChannelNo() {
- BubbleExtractor extractor = new BubbleExtractor();
- extractor.setConfig(mConfig);
-
when(mConfig.bubblesEnabled()).thenReturn(true);
when(mConfig.areBubblesAllowed(mPkg, mUid)).thenReturn(false);
NotificationRecord r = getNotificationRecord(false, IMPORTANCE_UNSPECIFIED);
- extractor.process(r);
+ mBubbleExtractor.process(r);
assertFalse(r.canBubble());
}
@Test
public void testAppYesChannelYesUserNo() {
- BubbleExtractor extractor = new BubbleExtractor();
- extractor.setConfig(mConfig);
-
when(mConfig.bubblesEnabled()).thenReturn(false);
when(mConfig.areBubblesAllowed(mPkg, mUid)).thenReturn(true);
NotificationRecord r = getNotificationRecord(true, IMPORTANCE_HIGH);
- extractor.process(r);
+ mBubbleExtractor.process(r);
assertFalse(r.canBubble());
}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java
index f7c2609..2341c10 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationHistoryManagerTest.java
@@ -31,7 +31,6 @@
import android.app.NotificationHistory.HistoricalNotification;
import android.content.pm.UserInfo;
import android.graphics.drawable.Icon;
-import android.os.Handler;
import android.os.UserManager;
import android.provider.Settings;
@@ -40,7 +39,6 @@
import com.android.server.UiServiceTestCase;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -58,9 +56,9 @@
UserManager mUserManager;
@Mock
NotificationHistoryDatabase mDb;
- @Mock
- Handler mHandler;
List<UserInfo> mUsers;
+ int[] mProfiles;
+ int mProfileId = 11;
NotificationHistoryManager mHistoryManager;
@@ -98,26 +96,32 @@
UserInfo userSystem = new UserInfo();
userSystem.id = USER_SYSTEM;
mUsers.add(userSystem);
- UserInfo userAll = new UserInfo();
- userAll.id = MIN_SECONDARY_USER_ID;
- mUsers.add(userAll);
- mUsers.add(userAll);
+ UserInfo userFullSecondary = new UserInfo();
+ userFullSecondary.id = MIN_SECONDARY_USER_ID;
+ mUsers.add(userFullSecondary);
+ UserInfo userProfile = new UserInfo();
+ userProfile.id = mProfileId;
+ mUsers.add(userProfile);
when(mUserManager.getUsers()).thenReturn(mUsers);
+ mProfiles = new int[] {userSystem.id, userProfile.id};
+ when(mUserManager.getProfileIds(userSystem.id, true)).thenReturn(mProfiles);
+ when(mUserManager.getProfileIds(userFullSecondary.id, true))
+ .thenReturn(new int[] {userFullSecondary.id});
+ when(mUserManager.getProfileIds(userProfile.id, true))
+ .thenReturn(new int[] {userProfile.id});
+
+ when(mUserManager.getProfileParent(userProfile.id)).thenReturn(userSystem);
+
+ NotificationHistoryDatabaseFactory.setTestingNotificationHistoryDatabase(mDb);
+
+ mHistoryManager = new NotificationHistoryManager(getContext(), null);
+
for (UserInfo info : mUsers) {
Settings.Secure.putIntForUser(getContext().getContentResolver(),
Settings.Secure.NOTIFICATION_HISTORY_ENABLED, 1, info.id);
+ mHistoryManager.mSettingsObserver.update(null, info.id);
}
-
- NotificationHistoryDatabaseFactory.setTestingNotificationHistoryDatabase(mDb);
-
- mHistoryManager = new NotificationHistoryManager(getContext(), mHandler);
- mHistoryManager.onBootPhaseAppsCanStart();
- }
-
- @After
- public void tearDown() {
- mHistoryManager.onDestroy();
}
@Test
@@ -151,6 +155,31 @@
}
@Test
+ public void testOnUserUnlocked_historyDisabled_withProfile() {
+ // create a history
+ mHistoryManager.onUserUnlocked(USER_SYSTEM);
+ assertThat(mHistoryManager.doesHistoryExistForUser(USER_SYSTEM)).isTrue();
+ mHistoryManager.onUserUnlocked(mProfileId);
+ assertThat(mHistoryManager.doesHistoryExistForUser(mProfileId)).isTrue();
+ // lock user
+ mHistoryManager.onUserStopped(USER_SYSTEM);
+ mHistoryManager.onUserStopped(mProfileId);
+
+ // turn off history
+ Settings.Secure.putIntForUser(getContext().getContentResolver(),
+ Settings.Secure.NOTIFICATION_HISTORY_ENABLED, 0, USER_SYSTEM);
+ mHistoryManager.mSettingsObserver.update(null, USER_SYSTEM);
+
+ // unlock user, verify that history is disabled for self and profile
+ mHistoryManager.onUserUnlocked(USER_SYSTEM);
+ mHistoryManager.onUserUnlocked(mProfileId);
+
+ assertThat(mHistoryManager.doesHistoryExistForUser(USER_SYSTEM)).isFalse();
+ assertThat(mHistoryManager.doesHistoryExistForUser(mProfileId)).isFalse();
+ verify(mDb, times(2)).disableHistory();
+ }
+
+ @Test
public void testOnUserUnlocked_historyDisabledThenEnabled() {
// create a history
mHistoryManager.onUserUnlocked(USER_SYSTEM);
@@ -177,6 +206,37 @@
}
@Test
+ public void testOnUserUnlocked_historyDisabledThenEnabled_multiProfile() {
+ // create a history
+ mHistoryManager.onUserUnlocked(USER_SYSTEM);
+ assertThat(mHistoryManager.doesHistoryExistForUser(USER_SYSTEM)).isTrue();
+ mHistoryManager.onUserUnlocked(mProfileId);
+ assertThat(mHistoryManager.doesHistoryExistForUser(mProfileId)).isTrue();
+
+ // lock user
+ mHistoryManager.onUserStopped(USER_SYSTEM);
+ mHistoryManager.onUserStopped(mProfileId);
+
+ // turn off history
+ Settings.Secure.putIntForUser(getContext().getContentResolver(),
+ Settings.Secure.NOTIFICATION_HISTORY_ENABLED, 0, USER_SYSTEM);
+ mHistoryManager.mSettingsObserver.update(null, USER_SYSTEM);
+
+ // turn on history
+ Settings.Secure.putIntForUser(getContext().getContentResolver(),
+ Settings.Secure.NOTIFICATION_HISTORY_ENABLED, 1, USER_SYSTEM);
+ mHistoryManager.mSettingsObserver.update(null, USER_SYSTEM);
+
+ // unlock user, verify that history is NOT disabled
+ mHistoryManager.onUserUnlocked(USER_SYSTEM);
+ mHistoryManager.onUserUnlocked(mProfileId);
+
+ assertThat(mHistoryManager.doesHistoryExistForUser(USER_SYSTEM)).isTrue();
+ assertThat(mHistoryManager.doesHistoryExistForUser(mProfileId)).isTrue();
+ verify(mDb, never()).disableHistory();
+ }
+
+ @Test
public void testOnUserUnlocked_cleansUpRemovedPackages() {
String pkg = "pkg";
mHistoryManager.onPackageRemoved(USER_SYSTEM, pkg);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java
index dc8d010..8e78047 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationListenerServiceTest.java
@@ -35,7 +35,6 @@
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.PendingIntent;
-import android.app.Person;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -191,7 +190,8 @@
tweak.canBubble(),
tweak.visuallyInterruptive(),
tweak.isConversation(),
- tweak.getShortcutInfo()
+ tweak.getShortcutInfo(),
+ tweak.isBubble()
);
assertNotEquals(nru, nru2);
}
@@ -270,7 +270,8 @@
canBubble(i),
visuallyInterruptive(i),
isConversation(i),
- getShortcutInfo(i)
+ getShortcutInfo(i),
+ isBubble(i)
);
rankings[i] = ranking;
}
@@ -394,6 +395,10 @@
return si;
}
+ private boolean isBubble(int index) {
+ return index % 4 == 0;
+ }
+
private void assertActionsEqual(
List<Notification.Action> expecteds, List<Notification.Action> actuals) {
assertEquals(expecteds.size(), actuals.size());
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 b6cdbfb..f179840 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -41,8 +41,6 @@
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.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC;
-import static android.content.pm.LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED;
import static android.content.pm.PackageManager.FEATURE_WATCH;
import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
@@ -204,6 +202,8 @@
private TestableNotificationManagerService mService;
private INotificationManager mBinderService;
private NotificationManagerInternal mInternalService;
+ private TestableBubbleChecker mTestableBubbleChecker;
+ private ShortcutHelper mShortcutHelper;
@Mock
private IPackageManager mPackageManager;
@Mock
@@ -286,6 +286,10 @@
super(context, logger, notificationInstanceIdSequence);
}
+ RankingHelper getRankingHelper() {
+ return mRankingHelper;
+ }
+
@Override
protected boolean isCallingUidSystem() {
countSystemChecks++;
@@ -337,6 +341,14 @@
interface NotificationAssistantAccessGrantedCallback {
void onGranted(ComponentName assistant, int userId, boolean granted);
}
+ }
+
+ private class TestableBubbleChecker extends BubbleExtractor.BubbleChecker {
+
+ TestableBubbleChecker(Context context, ShortcutHelper helper, RankingConfig config,
+ ActivityManager manager) {
+ super(context, helper, config, manager);
+ }
@Override
protected boolean canLaunchInActivityView(Context context, PendingIntent pendingIntent,
@@ -448,7 +460,16 @@
mService.onBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
mService.setAudioManager(mAudioManager);
- mService.setLauncherApps(mLauncherApps);
+
+ mShortcutHelper = mService.getShortcutHelper();
+ mShortcutHelper.setLauncherApps(mLauncherApps);
+
+ // Set the testable bubble extractor
+ RankingHelper rankingHelper = mService.getRankingHelper();
+ BubbleExtractor extractor = rankingHelper.findExtractor(BubbleExtractor.class);
+ mTestableBubbleChecker = new TestableBubbleChecker(mContext, mShortcutHelper,
+ mService.mPreferencesHelper, mActivityManager);
+ extractor.setBubbleChecker(mTestableBubbleChecker);
// Tests call directly into the Binder.
mBinderService = mService.getBinderService();
@@ -462,6 +483,15 @@
}
@After
+ public void assertNotificationRecordLoggerCallsValid() {
+ for (NotificationRecordLoggerFake.CallRecord call : mNotificationRecordLogger.getCalls()) {
+ if (call.wasLogged) {
+ assertNotNull(call.event);
+ }
+ }
+ }
+
+ @After
public void tearDown() throws Exception {
if (mFile != null) mFile.delete();
clearDeviceConfig();
@@ -1150,10 +1180,10 @@
mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0,
generateNotificationRecord(null).getNotification(), 0);
waitForIdle();
- assertEquals(1, mNotificationRecordLogger.getCalls().size());
+ assertEquals(1, mNotificationRecordLogger.numCalls());
NotificationRecordLoggerFake.CallRecord call = mNotificationRecordLogger.get(0);
- assertTrue(call.shouldLogReported);
+ assertTrue(call.wasLogged);
assertEquals(NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
call.event);
assertNotNull(call.r);
@@ -1179,18 +1209,18 @@
.setCategory(Notification.CATEGORY_ALARM).build();
mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, update, 0);
waitForIdle();
- assertEquals(2, mNotificationRecordLogger.getCalls().size());
+ assertEquals(2, mNotificationRecordLogger.numCalls());
- assertTrue(mNotificationRecordLogger.get(0).shouldLogReported);
+ assertTrue(mNotificationRecordLogger.get(0).wasLogged);
assertEquals(
NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
- mNotificationRecordLogger.get(0).event);
+ mNotificationRecordLogger.event(0));
assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
- assertTrue(mNotificationRecordLogger.get(1).shouldLogReported);
+ assertTrue(mNotificationRecordLogger.get(1).wasLogged);
assertEquals(
NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_UPDATED,
- mNotificationRecordLogger.get(1).event);
+ mNotificationRecordLogger.event(1));
// Instance ID doesn't change on update of an active notification
assertEquals(1, mNotificationRecordLogger.get(1).getInstanceId());
}
@@ -1203,13 +1233,13 @@
mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0,
generateNotificationRecord(null).getNotification(), 0);
waitForIdle();
- assertEquals(2, mNotificationRecordLogger.getCalls().size());
- assertTrue(mNotificationRecordLogger.get(0).shouldLogReported);
+ assertEquals(2, mNotificationRecordLogger.numCalls());
+ assertTrue(mNotificationRecordLogger.get(0).wasLogged);
assertEquals(
NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
- mNotificationRecordLogger.get(0).event);
- assertFalse(mNotificationRecordLogger.get(1).shouldLogReported);
- assertNull(mNotificationRecordLogger.get(1).event);
+ mNotificationRecordLogger.event(0));
+ assertFalse(mNotificationRecordLogger.get(1).wasLogged);
+ assertNull(mNotificationRecordLogger.event(1));
}
@Test
@@ -1222,11 +1252,11 @@
notif.extras.putString(Notification.EXTRA_TITLE, "Changed title");
mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, notif, 0);
waitForIdle();
- assertEquals(2, mNotificationRecordLogger.getCalls().size());
+ assertEquals(2, mNotificationRecordLogger.numCalls());
assertEquals(
NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
- mNotificationRecordLogger.get(0).event);
- assertNull(mNotificationRecordLogger.get(1).event);
+ mNotificationRecordLogger.event(0));
+ assertNull(mNotificationRecordLogger.event(1));
}
@Test
@@ -1241,23 +1271,23 @@
waitForIdle();
mBinderService.enqueueNotificationWithTag(PKG, PKG, tag, 0, notification, 0);
waitForIdle();
- assertEquals(3, mNotificationRecordLogger.getCalls().size());
+ assertEquals(3, mNotificationRecordLogger.numCalls());
assertEquals(
NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
- mNotificationRecordLogger.get(0).event);
- assertTrue(mNotificationRecordLogger.get(0).shouldLogReported);
+ mNotificationRecordLogger.event(0));
+ assertTrue(mNotificationRecordLogger.get(0).wasLogged);
assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
assertEquals(
NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_APP_CANCEL,
- mNotificationRecordLogger.get(1).event);
+ mNotificationRecordLogger.event(1));
assertEquals(1, mNotificationRecordLogger.get(1).getInstanceId());
assertEquals(
NotificationRecordLogger.NotificationReportedEvent.NOTIFICATION_POSTED,
- mNotificationRecordLogger.get(2).event);
- assertTrue(mNotificationRecordLogger.get(2).shouldLogReported);
+ mNotificationRecordLogger.event(2));
+ assertTrue(mNotificationRecordLogger.get(2).wasLogged);
// New instance ID because notification was canceled before re-post
assertEquals(2, mNotificationRecordLogger.get(2).getInstanceId());
}
@@ -1269,7 +1299,7 @@
waitForIdle();
// The notification record logger doesn't even get called when a nonexistent notification
// is cancelled, because that happens very frequently and is not interesting.
- assertEquals(0, mNotificationRecordLogger.getCalls().size());
+ assertEquals(0, mNotificationRecordLogger.numCalls());
}
@Test
@@ -2527,6 +2557,13 @@
// only snooze the one notification
verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
assertTrue(nonGrouped.getStats().hasSnoozed());
+
+ assertEquals(2, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
+ mNotificationRecordLogger.event(0));
+ assertEquals(
+ NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
+ mNotificationRecordLogger.event(1));
}
@Test
@@ -2569,6 +2606,12 @@
// only snooze the one child
verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
+
+ assertEquals(2, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
+ mNotificationRecordLogger.event(0));
+ assertEquals(NotificationRecordLogger.NotificationCancelledEvent
+ .NOTIFICATION_CANCEL_SNOOZED, mNotificationRecordLogger.event(1));
}
@Test
@@ -2588,6 +2631,18 @@
// snooze child and summary
verify(mSnoozeHelper, times(2)).snooze(any(NotificationRecord.class), anyLong());
+
+ assertEquals(4, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
+ mNotificationRecordLogger.event(0));
+ assertEquals(
+ NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
+ mNotificationRecordLogger.event(1));
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
+ mNotificationRecordLogger.event(2));
+ assertEquals(
+ NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
+ mNotificationRecordLogger.event(3));
}
@Test
@@ -2603,6 +2658,13 @@
// snooze child only
verify(mSnoozeHelper, times(1)).snooze(any(NotificationRecord.class), anyLong());
+
+ assertEquals(2, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SNOOZED,
+ mNotificationRecordLogger.event(0));
+ assertEquals(
+ NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_SNOOZED,
+ mNotificationRecordLogger.event(1));
}
@Test
@@ -3386,6 +3448,10 @@
mService.mNotificationDelegate.onNotificationDirectReplied(r.getKey());
assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasDirectReplied());
verify(mAssistants).notifyAssistantNotificationDirectReplyLocked(eq(r.getSbn()));
+
+ assertEquals(1, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_DIRECT_REPLIED,
+ mNotificationRecordLogger.event(0));
}
@Test
@@ -3404,6 +3470,12 @@
verify(mAssistants).notifyAssistantExpansionChangedLocked(eq(r.getSbn()), eq(true),
eq((false)));
assertTrue(mService.getNotificationRecord(r.getKey()).getStats().hasExpanded());
+
+ assertEquals(2, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_DETAIL_OPEN_USER,
+ mNotificationRecordLogger.event(0));
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_DETAIL_CLOSE_USER,
+ mNotificationRecordLogger.event(1));
}
@Test
@@ -3465,11 +3537,11 @@
// Using mService.addNotification() does not generate a NotificationRecordLogger log,
// so we only get the cancel notification.
- assertEquals(1, mNotificationRecordLogger.getCalls().size());
+ assertEquals(1, mNotificationRecordLogger.numCalls());
assertEquals(
NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_USER_AOD,
- mNotificationRecordLogger.get(0).event);
+ mNotificationRecordLogger.event(0));
assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
}
@@ -4351,9 +4423,9 @@
{NotificationVisibility.obtain(r.getKey(), 1, 1, true)},
new NotificationVisibility[]{});
- assertEquals(1, mNotificationRecordLogger.getCalls().size());
+ assertEquals(1, mNotificationRecordLogger.numCalls());
assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_OPEN,
- mNotificationRecordLogger.get(0).event);
+ mNotificationRecordLogger.event(0));
assertEquals(1, mNotificationRecordLogger.get(0).getInstanceId());
mService.mNotificationDelegate.onNotificationVisibilityChanged(
@@ -4362,9 +4434,9 @@
{NotificationVisibility.obtain(r.getKey(), 1, 1, true)}
);
- assertEquals(2, mNotificationRecordLogger.getCalls().size());
+ assertEquals(2, mNotificationRecordLogger.numCalls());
assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLOSE,
- mNotificationRecordLogger.get(1).event);
+ mNotificationRecordLogger.event(1));
assertEquals(1, mNotificationRecordLogger.get(1).getInstanceId());
}
@@ -4394,6 +4466,7 @@
verify(mAppUsageStats, times(1)).reportInterruptiveNotification(
anyString(), anyString(), anyInt());
+ verify(mHistoryManager, times(1)).addNotification(any());
}
@Test
@@ -4787,6 +4860,12 @@
mService.mNotificationDelegate.onPanelHidden();
verify(mAssistants, times(1)).onPanelHidden();
+
+ assertEquals(2, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationPanelEvent.NOTIFICATION_PANEL_OPEN,
+ mNotificationRecordLogger.event(0));
+ assertEquals(NotificationRecordLogger.NotificationPanelEvent.NOTIFICATION_PANEL_CLOSE,
+ mNotificationRecordLogger.event(1));
}
@Test
@@ -4805,6 +4884,9 @@
modifiedBeforeSending);
verify(mAssistants).notifyAssistantSuggestedReplySent(
eq(r.getSbn()), eq(reply), eq(generatedByAssistant));
+ assertEquals(1, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_SMART_REPLIED,
+ mNotificationRecordLogger.event(0));
}
@Test
@@ -4824,6 +4906,10 @@
generatedByAssistant);
verify(mAssistants).notifyAssistantActionClicked(
eq(r.getSbn()), eq(actionIndex), eq(action), eq(generatedByAssistant));
+
+ assertEquals(1, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_ACTION_CLICKED,
+ mNotificationRecordLogger.event(0));
}
@Test
@@ -5488,6 +5574,10 @@
StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
assertEquals(1, notifs.length);
assertEquals(1, mService.getNotificationRecordCount());
+
+ assertEquals(1, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationCancelledEvent
+ .NOTIFICATION_CANCEL_LISTENER_CANCEL, mNotificationRecordLogger.event(0));
}
@Test
@@ -5709,6 +5799,9 @@
@Test
public void testOnBubbleNotificationSuppressionChanged() throws Exception {
+ // Bubbles are allowed!
+ setUpPrefsForBubbles(PKG, mUid, true /* global */, true /* app */, true /* channel */);
+
// Bubble notification
NotificationRecord nr = generateMessageBubbleNotifRecord(mTestNotificationChannel, "tag");
@@ -6110,8 +6203,10 @@
assertTrue(notif.isBubbleNotification());
// Test: Remove the shortcut
+ when(mLauncherApps.getShortcuts(any(), any())).thenReturn(null);
launcherAppsCallback.getValue().onShortcutsChanged(PKG, Collections.emptyList(),
new UserHandle(mUid));
+ waitForIdle();
// Verify:
@@ -6124,6 +6219,58 @@
assertFalse(notif2.isBubbleNotification());
}
+
+ @Test
+ public void testNotificationBubbles_shortcut_stopListeningWhenNotifRemoved()
+ throws RemoteException {
+ // Bubbles are allowed!
+ setUpPrefsForBubbles(PKG, mUid, true /* global */, true /* app */, true /* channel */);
+
+ ArgumentCaptor<LauncherApps.Callback> launcherAppsCallback =
+ ArgumentCaptor.forClass(LauncherApps.Callback.class);
+
+ // Messaging notification with shortcut info
+ Notification.BubbleMetadata metadata =
+ getBubbleMetadataBuilder().createShortcutBubble("someshortcutId").build();
+ Notification.Builder nb = getMessageStyleNotifBuilder(false /* addDefaultMetadata */,
+ null /* groupKey */, false /* isSummary */);
+ nb.setBubbleMetadata(metadata);
+ StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1,
+ "tag", mUid, 0, nb.build(), new UserHandle(mUid), null, 0);
+ NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+ // Pretend the shortcut exists
+ List<ShortcutInfo> shortcutInfos = new ArrayList<>();
+ ShortcutInfo info = mock(ShortcutInfo.class);
+ when(info.isLongLived()).thenReturn(true);
+ shortcutInfos.add(info);
+ when(mLauncherApps.getShortcuts(any(), any())).thenReturn(shortcutInfos);
+
+ // Test: Send the bubble notification
+ mBinderService.enqueueNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
+ nr.getSbn().getId(), nr.getSbn().getNotification(), nr.getSbn().getUserId());
+ waitForIdle();
+
+ // Verify:
+
+ // Make sure we register the callback for shortcut changes
+ verify(mLauncherApps, times(1)).registerCallback(launcherAppsCallback.capture(), any());
+
+ // yes allowed, yes messaging w/shortcut, yes bubble
+ Notification notif = mService.getNotificationRecord(nr.getSbn().getKey()).getNotification();
+ assertTrue(notif.isBubbleNotification());
+
+ // Test: Remove the notification
+ mBinderService.cancelNotificationWithTag(PKG, PKG, nr.getSbn().getTag(),
+ nr.getSbn().getId(), nr.getSbn().getUserId());
+ waitForIdle();
+
+ // Verify:
+
+ // Make sure callback is unregistered
+ verify(mLauncherApps, times(1)).unregisterCallback(launcherAppsCallback.getValue());
+ }
+
@Test
public void testNotificationBubbles_bubbleChildrenStay_whenGroupSummaryDismissed()
throws Exception {
@@ -6167,6 +6314,17 @@
// The bubble should still exist
StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
assertEquals(1, notifsAfter.length);
+
+ // Check we got the click log and associated dismissal logs
+ assertEquals(6, mNotificationRecordLogger.numCalls());
+ // Skip the notification-creation logs
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLICKED,
+ mNotificationRecordLogger.event(3));
+ assertEquals(NotificationRecordLogger.NotificationCancelledEvent.NOTIFICATION_CANCEL_CLICK,
+ mNotificationRecordLogger.event(4));
+ assertEquals(NotificationRecordLogger.NotificationCancelledEvent
+ .NOTIFICATION_CANCEL_GROUP_SUMMARY_CANCELED,
+ mNotificationRecordLogger.event(5));
}
@Test
@@ -6187,6 +6345,11 @@
// THEN the bubble should still exist
StatusBarNotification[] notifsAfter = mBinderService.getActiveNotifications(PKG);
assertEquals(1, notifsAfter.length);
+
+ // Check we got the click log
+ assertEquals(1, mNotificationRecordLogger.numCalls());
+ assertEquals(NotificationRecordLogger.NotificationEvent.NOTIFICATION_CLICKED,
+ mNotificationRecordLogger.event(0));
}
@Test
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordLoggerFake.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordLoggerFake.java
index 2a17bae..6b18cc6 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordLoggerFake.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationRecordLoggerFake.java
@@ -31,25 +31,29 @@
// The following fields are only relevant to maybeLogNotificationPosted() calls.
static final int INVALID = -1;
public int position = INVALID, buzzBeepBlink = INVALID;
- public boolean shouldLogReported;
+ public boolean wasLogged;
CallRecord(NotificationRecord r, NotificationRecord old, int position,
int buzzBeepBlink) {
super(r, old);
this.position = position;
this.buzzBeepBlink = buzzBeepBlink;
- shouldLogReported = shouldLogReported(buzzBeepBlink);
- event = shouldLogReported ? NotificationReportedEvent.fromRecordPair(this) : null;
+ wasLogged = shouldLogReported(buzzBeepBlink);
+ event = wasLogged ? NotificationReportedEvent.fromRecordPair(this) : null;
}
CallRecord(NotificationRecord r, UiEventLogger.UiEventEnum event) {
super(r, null);
- shouldLogReported = false;
+ wasLogged = true;
this.event = event;
}
}
private List<CallRecord> mCalls = new ArrayList<>();
+ public int numCalls() {
+ return mCalls.size();
+ }
+
List<CallRecord> getCalls() {
return mCalls;
}
@@ -57,6 +61,9 @@
CallRecord get(int index) {
return mCalls.get(index);
}
+ UiEventLogger.UiEventEnum event(int index) {
+ return mCalls.get(index).event;
+ }
@Override
public void maybeLogNotificationPosted(NotificationRecord r, NotificationRecord old,
@@ -65,13 +72,12 @@
}
@Override
- public void logNotificationCancelled(NotificationRecord r, int reason, int dismissalSurface) {
- mCalls.add(new CallRecord(r,
- NotificationCancelledEvent.fromCancelReason(reason, dismissalSurface)));
+ public void log(UiEventLogger.UiEventEnum event, NotificationRecord r) {
+ mCalls.add(new CallRecord(r, event));
}
@Override
- public void logNotificationVisibility(NotificationRecord r, boolean visible) {
- mCalls.add(new CallRecord(r, NotificationEvent.fromVisibility(visible)));
+ public void log(UiEventLogger.UiEventEnum event) {
+ mCalls.add(new CallRecord(null, event));
}
}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java
index 551e186..5a527a2 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ScheduleConditionProviderTest.java
@@ -3,8 +3,10 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
+import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.service.notification.Condition;
@@ -45,7 +47,7 @@
null, // ActivityThread not actually used in Service
ScheduleConditionProvider.class.getName(),
null, // token not needed when not talking with the activity manager
- null,
+ mock(Application.class),
null // mocked services don't talk with the activity manager
);
service.onCreate();
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ShortcutHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ShortcutHelperTest.java
new file mode 100644
index 0000000..50fb9b4
--- /dev/null
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ShortcutHelperTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2020 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.notification;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Notification;
+import android.content.pm.LauncherApps;
+import android.content.pm.ShortcutInfo;
+import android.os.UserHandle;
+import android.service.notification.StatusBarNotification;
+import android.test.suitebuilder.annotation.SmallTest;
+import android.testing.TestableLooper;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.server.UiServiceTestCase;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+@TestableLooper.RunWithLooper
+public class ShortcutHelperTest extends UiServiceTestCase {
+
+ private static final String SHORTCUT_ID = "shortcut";
+ private static final String PKG = "pkg";
+ private static final String KEY = "key";
+
+ @Mock
+ LauncherApps mLauncherApps;
+ @Mock
+ ShortcutHelper.ShortcutListener mShortcutListener;
+ @Mock
+ NotificationRecord mNr;
+ @Mock
+ Notification mNotif;
+ @Mock
+ StatusBarNotification mSbn;
+ @Mock
+ Notification.BubbleMetadata mBubbleMetadata;
+
+ ShortcutHelper mShortcutHelper;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ mShortcutHelper = new ShortcutHelper(mLauncherApps, mShortcutListener);
+ when(mNr.getKey()).thenReturn(KEY);
+ when(mNr.getSbn()).thenReturn(mSbn);
+ when(mSbn.getPackageName()).thenReturn(PKG);
+ when(mNr.getNotification()).thenReturn(mNotif);
+ when(mNotif.getBubbleMetadata()).thenReturn(mBubbleMetadata);
+ when(mBubbleMetadata.getShortcutId()).thenReturn(SHORTCUT_ID);
+ }
+
+ private LauncherApps.Callback addShortcutBubbleAndVerifyListener() {
+ when(mNotif.isBubbleNotification()).thenReturn(true);
+
+ mShortcutHelper.maybeListenForShortcutChangesForBubbles(mNr,
+ false /* removed */,
+ null /* handler */);
+
+ ArgumentCaptor<LauncherApps.Callback> launcherAppsCallback =
+ ArgumentCaptor.forClass(LauncherApps.Callback.class);
+
+ verify(mLauncherApps, times(1)).registerCallback(
+ launcherAppsCallback.capture(), any());
+ return launcherAppsCallback.getValue();
+ }
+
+ @Test
+ public void testBubbleAdded_listenedAdded() {
+ addShortcutBubbleAndVerifyListener();
+ }
+
+ @Test
+ public void testBubbleRemoved_listenerRemoved() {
+ // First set it up to listen
+ addShortcutBubbleAndVerifyListener();
+
+ // Then remove the notif
+ mShortcutHelper.maybeListenForShortcutChangesForBubbles(mNr,
+ true /* removed */,
+ null /* handler */);
+
+ verify(mLauncherApps, times(1)).unregisterCallback(any());
+ }
+
+ @Test
+ public void testBubbleNoLongerBubble_listenerRemoved() {
+ // First set it up to listen
+ addShortcutBubbleAndVerifyListener();
+
+ // Then make it not a bubble
+ when(mNotif.isBubbleNotification()).thenReturn(false);
+ mShortcutHelper.maybeListenForShortcutChangesForBubbles(mNr,
+ false /* removed */,
+ null /* handler */);
+
+ verify(mLauncherApps, times(1)).unregisterCallback(any());
+ }
+
+ @Test
+ public void testListenerNotifiedOnShortcutRemoved() {
+ LauncherApps.Callback callback = addShortcutBubbleAndVerifyListener();
+
+ List<ShortcutInfo> shortcutInfos = new ArrayList<>();
+ when(mLauncherApps.getShortcuts(any(), any())).thenReturn(shortcutInfos);
+
+ callback.onShortcutsChanged(PKG, shortcutInfos, mock(UserHandle.class));
+ verify(mShortcutListener).onShortcutRemoved(mNr.getKey());
+ }
+}
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index c9c3649..9e87421 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -1332,6 +1332,40 @@
assertNotEquals(initialConf, wpc.getRequestedOverrideConfiguration());
}
+ @Test
+ public void testActivityDestroyDoesntChangeProcessOverride() {
+ final ActivityRecord firstActivity =
+ createActivityOnDisplay(true /* defaultDisplay */, null /* process */);
+ final WindowProcessController wpc = firstActivity.app;
+ assertTrue(wpc.registeredForActivityConfigChanges());
+ assertEquals(0, firstActivity.getMergedOverrideConfiguration()
+ .diff(wpc.getRequestedOverrideConfiguration()));
+
+ final ActivityRecord secondActivity =
+ createActivityOnDisplay(false /* defaultDisplay */, wpc);
+ assertTrue(wpc.registeredForActivityConfigChanges());
+ assertEquals(0, secondActivity.getMergedOverrideConfiguration()
+ .diff(wpc.getRequestedOverrideConfiguration()));
+
+ final ActivityRecord thirdActivity =
+ createActivityOnDisplay(false /* defaultDisplay */, wpc);
+ assertTrue(wpc.registeredForActivityConfigChanges());
+ assertEquals(0, thirdActivity.getMergedOverrideConfiguration()
+ .diff(wpc.getRequestedOverrideConfiguration()));
+
+ secondActivity.destroyImmediately(true, "");
+
+ assertTrue(wpc.registeredForActivityConfigChanges());
+ assertEquals(0, thirdActivity.getMergedOverrideConfiguration()
+ .diff(wpc.getRequestedOverrideConfiguration()));
+
+ firstActivity.destroyImmediately(true, "");
+
+ assertTrue(wpc.registeredForActivityConfigChanges());
+ assertEquals(0, thirdActivity.getMergedOverrideConfiguration()
+ .diff(wpc.getRequestedOverrideConfiguration()));
+ }
+
/**
* Creates an activity on display. For non-default display request it will also create a new
* display with custom DisplayInfo.
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index 049c8e1..6eec649 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -18,6 +18,7 @@
import static android.app.ActivityManager.PROCESS_STATE_TOP;
import static android.app.ActivityManager.START_ABORTED;
+import static android.app.ActivityManager.START_CANCELED;
import static android.app.ActivityManager.START_CLASS_NOT_FOUND;
import static android.app.ActivityManager.START_DELIVERED_TO_TOP;
import static android.app.ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
@@ -202,10 +203,11 @@
final IApplicationThread caller = mock(IApplicationThread.class);
final WindowProcessListener listener = mock(WindowProcessListener.class);
+ final ApplicationInfo ai = new ApplicationInfo();
+ ai.packageName = "com.android.test.package";
final WindowProcessController wpc =
containsConditions(preconditions, PRECONDITION_NO_CALLER_APP)
- ? null : new WindowProcessController(
- service, mock(ApplicationInfo.class), null, 0, -1, null, listener);
+ ? null : new WindowProcessController(service, ai, null, 0, -1, null, listener);
doReturn(wpc).when(service).getProcessController(anyObject());
final Intent intent = new Intent();
@@ -344,6 +346,7 @@
doReturn(false).when(mMockPackageManager).isInstantAppInstallerComponent(any());
doReturn(null).when(mMockPackageManager).resolveIntent(any(), any(), anyInt(), anyInt(),
anyInt(), anyBoolean(), anyInt());
+ doReturn(new ComponentName("", "")).when(mMockPackageManager).getSystemUiServiceComponent();
// Never review permissions
doReturn(false).when(mMockPackageManager).isPermissionsReviewRequired(any(), anyInt());
@@ -655,6 +658,7 @@
final WindowProcessListener listener = mock(WindowProcessListener.class);
final ApplicationInfo ai = new ApplicationInfo();
ai.uid = callingUid;
+ ai.packageName = "com.android.test.package";
final WindowProcessController callerApp =
new WindowProcessController(mService, ai, null, callingUid, -1, null, listener);
callerApp.setHasForegroundActivities(hasForegroundActivities);
@@ -892,7 +896,7 @@
.execute();
// Simulate a failed start
- starter.postStartActivityProcessing(null, START_ABORTED, null);
+ starter.postStartActivityProcessing(null, START_CANCELED, null);
verify(recentTasks, times(1)).setFreezeTaskListReordering();
verify(recentTasks, times(1)).resetFreezeTaskListReorderingOnTimeout();
@@ -1019,7 +1023,7 @@
public void taskAppeared(ActivityManager.RunningTaskInfo info) {
}
@Override
- public void taskVanished(IWindowContainer wc) {
+ public void taskVanished(ActivityManager.RunningTaskInfo info) {
}
@Override
public void transactionReady(int id, SurfaceControl.Transaction t) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
index 1796d85..4634e2d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
@@ -234,6 +234,10 @@
mTask = new TaskBuilder(mService.mStackSupervisor)
.setComponent(mComponent)
.setStack(mStack).build();
+ } else if (mTask == null && mStack != null && DisplayContent.alwaysCreateStack(
+ mStack.getWindowingMode(), mStack.getActivityType())) {
+ // The stack can be the task root.
+ mTask = mStack;
}
Intent intent = new Intent();
diff --git a/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
index 5cf1fbb..a380ece 100644
--- a/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/InsetsStateControllerTest.java
@@ -16,6 +16,8 @@
package com.android.server.wm;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
+import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.view.InsetsState.ITYPE_IME;
import static android.view.InsetsState.ITYPE_NAVIGATION_BAR;
import static android.view.InsetsState.ITYPE_STATUS_BAR;
@@ -69,7 +71,7 @@
final WindowState app = createWindow(null, TYPE_APPLICATION, "app");
getController().getSourceProvider(ITYPE_STATUS_BAR).setWindow(statusBar, null, null);
statusBar.setControllableInsetProvider(getController().getSourceProvider(ITYPE_STATUS_BAR));
- assertNotNull(getController().getInsetsForDispatch(app).getSource(ITYPE_STATUS_BAR));
+ assertNotNull(getController().getInsetsForDispatch(app).peekSource(ITYPE_STATUS_BAR));
}
@Test
@@ -101,6 +103,34 @@
}
@Test
+ public void testStripForDispatch_pip() {
+ final WindowState statusBar = createWindow(null, TYPE_APPLICATION, "statusBar");
+ final WindowState navBar = createWindow(null, TYPE_APPLICATION, "navBar");
+ final WindowState app = createWindow(null, TYPE_APPLICATION, "app");
+
+ getController().getSourceProvider(ITYPE_STATUS_BAR).setWindow(statusBar, null, null);
+ getController().getSourceProvider(ITYPE_NAVIGATION_BAR).setWindow(navBar, null, null);
+ app.setWindowingMode(WINDOWING_MODE_PINNED);
+
+ assertNull(getController().getInsetsForDispatch(app).peekSource(ITYPE_STATUS_BAR));
+ assertNull(getController().getInsetsForDispatch(app).peekSource(ITYPE_NAVIGATION_BAR));
+ }
+
+ @Test
+ public void testStripForDispatch_freeform() {
+ final WindowState statusBar = createWindow(null, TYPE_APPLICATION, "statusBar");
+ final WindowState navBar = createWindow(null, TYPE_APPLICATION, "navBar");
+ final WindowState app = createWindow(null, TYPE_APPLICATION, "app");
+
+ getController().getSourceProvider(ITYPE_STATUS_BAR).setWindow(statusBar, null, null);
+ getController().getSourceProvider(ITYPE_NAVIGATION_BAR).setWindow(navBar, null, null);
+ app.setWindowingMode(WINDOWING_MODE_FREEFORM);
+
+ assertNull(getController().getInsetsForDispatch(app).peekSource(ITYPE_STATUS_BAR));
+ assertNull(getController().getInsetsForDispatch(app).peekSource(ITYPE_NAVIGATION_BAR));
+ }
+
+ @Test
public void testImeForDispatch() {
final WindowState statusBar = createWindow(null, TYPE_APPLICATION, "statusBar");
final WindowState ime = createWindow(null, TYPE_APPLICATION, "ime");
diff --git a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
index ac4c228..8f3ff52 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java
@@ -37,8 +37,8 @@
import android.os.UserHandle;
import android.platform.test.annotations.Presubmit;
-import androidx.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
+import androidx.test.platform.app.InstrumentationRegistry;
import com.android.server.LocalServices;
import com.android.server.pm.PackageList;
@@ -72,6 +72,10 @@
ComponentName.createRelative("com.android.foo", ".BarActivity");
private static final ComponentName ALTERNATIVE_COMPONENT =
ComponentName.createRelative("com.android.foo", ".AlternativeBarActivity");
+ private static final String TEST_WINDOW_LAYOUT_AFFINITY = "135:.Affinity";
+ private static final String TEST_ALTERNATIVE_WINDOW_LAYOUT_AFFINITY =
+ "246:.AlternativeAffinity";
+ private static final String TEST_DIFFERENT_AFFINITY_WITH_SAME_UID = "135:.DifferentAffinity";
private static final int TEST_WINDOWING_MODE = WINDOWING_MODE_FREEFORM;
private static final Rect TEST_BOUNDS = new Rect(100, 200, 300, 400);
@@ -99,11 +103,12 @@
public void setUp() throws Exception {
mPersisterQueue = new TestPersisterQueue();
- final File cacheFolder = InstrumentationRegistry.getContext().getCacheDir();
+ final File cacheFolder =
+ InstrumentationRegistry.getInstrumentation().getContext().getCacheDir();
mFolder = new File(cacheFolder, "launch_params_tests");
deleteRecursively(mFolder);
- mDisplayUniqueId = "test:" + Integer.toString(sNextUniqueId++);
+ mDisplayUniqueId = "test:" + sNextUniqueId++;
mTestDisplay = new TestDisplayContent.Builder(mService, 1000, 1500)
.setUniqueId(mDisplayUniqueId).build();
when(mRootWindowContainer.getDisplayContent(eq(mDisplayUniqueId)))
@@ -131,6 +136,7 @@
LocalServices.addService(PackageManagerInternal.class, mMockPmi);
when(mMockPmi.getPackageList(any())).thenReturn(new PackageList(
Collections.singletonList(TEST_COMPONENT.getPackageName()), /* observer */ null));
+ when(mMockPmi.getSystemUiServiceComponent()).thenReturn(new ComponentName("", ""));
mTarget.onSystemReady();
final ArgumentCaptor<PackageManagerInternal.PackageListObserver> observerCaptor =
@@ -210,6 +216,61 @@
}
@Test
+ public void testUsesRecordWithSameWindowLayoutAffinityInSameInstance_NoPreviousRecord() {
+ mTestTask.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTestTask);
+
+ mTaskWithDifferentComponent.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.getLaunchParams(mTaskWithDifferentComponent, null, mResult);
+
+ assertEquals(mTestDisplay.mDisplayId, mResult.mPreferredDisplayId);
+ assertEquals(TEST_WINDOWING_MODE, mResult.mWindowingMode);
+ assertEquals(TEST_BOUNDS, mResult.mBounds);
+ }
+
+ @Test
+ public void testUsesRecordWithSameWindowLayoutAffinityInSameInstance_HasOldPreviousRecord()
+ throws Exception {
+ mTaskWithDifferentComponent.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTaskWithDifferentComponent);
+
+ Thread.sleep(1); // Sleep 1ms so that the timestamp can for sure increase.
+
+ mTestTask.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTestTask);
+
+ mTarget.getLaunchParams(mTaskWithDifferentComponent, null, mResult);
+
+ assertEquals(mTestDisplay.mDisplayId, mResult.mPreferredDisplayId);
+ assertEquals(TEST_WINDOWING_MODE, mResult.mWindowingMode);
+ assertEquals(TEST_BOUNDS, mResult.mBounds);
+ }
+
+ @Test
+ public void testReturnsEmptyLaunchParamsUidInLaunchAffinityMismatch() {
+ mTestTask.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTestTask);
+
+ mTaskWithDifferentComponent.mWindowLayoutAffinity = TEST_DIFFERENT_AFFINITY_WITH_SAME_UID;
+ mResult.mWindowingMode = WINDOWING_MODE_FULLSCREEN;
+ mTarget.getLaunchParams(mTaskWithDifferentComponent, null, mResult);
+
+ assertTrue("Result must be empty.", mResult.isEmpty());
+ }
+
+ @Test
+ public void testReturnsEmptyLaunchParamsWindowLayoutAffinityMismatch() {
+ mTestTask.affinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTestTask);
+
+ mTaskWithDifferentComponent.mWindowLayoutAffinity = TEST_ALTERNATIVE_WINDOW_LAYOUT_AFFINITY;
+ mResult.mWindowingMode = WINDOWING_MODE_FULLSCREEN;
+ mTarget.getLaunchParams(mTaskWithDifferentComponent, null, mResult);
+
+ assertTrue("Result must be empty.", mResult.isEmpty());
+ }
+
+ @Test
public void testSavesAndRestoresLaunchParamsAcrossInstances() {
mTarget.saveTask(mTestTask);
mPersisterQueue.flush();
@@ -227,6 +288,52 @@
}
@Test
+ public void testUsesRecordWithSameWindowLayoutAffinityAcrossInstances_NoPreviousRecord() {
+ mTestTask.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTestTask);
+ mPersisterQueue.flush();
+
+ final LaunchParamsPersister target = new LaunchParamsPersister(mPersisterQueue, mSupervisor,
+ mUserFolderGetter);
+ target.onSystemReady();
+ target.onUnlockUser(TEST_USER_ID);
+
+ mTaskWithDifferentComponent.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ target.getLaunchParams(mTaskWithDifferentComponent, null, mResult);
+
+ assertEquals(mTestDisplay.mDisplayId, mResult.mPreferredDisplayId);
+ assertEquals(TEST_WINDOWING_MODE, mResult.mWindowingMode);
+ assertEquals(TEST_BOUNDS, mResult.mBounds);
+ }
+
+ @Test
+ public void testUsesRecordWithSameWindowLayoutAffinityAcrossInstances_HasOldPreviousRecord()
+ throws Exception {
+ mTaskWithDifferentComponent.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTaskWithDifferentComponent);
+ mPersisterQueue.flush();
+
+ // Sleep 1s because many file systems only save last modified time as precise as 1s so we
+ // can for sure know the last modified time is different.
+ Thread.sleep(1000);
+
+ mTestTask.mWindowLayoutAffinity = TEST_WINDOW_LAYOUT_AFFINITY;
+ mTarget.saveTask(mTestTask);
+ mPersisterQueue.flush();
+
+ final LaunchParamsPersister target = new LaunchParamsPersister(mPersisterQueue, mSupervisor,
+ mUserFolderGetter);
+ target.onSystemReady();
+ target.onUnlockUser(TEST_USER_ID);
+
+ target.getLaunchParams(mTaskWithDifferentComponent, null, mResult);
+
+ assertEquals(mTestDisplay.mDisplayId, mResult.mPreferredDisplayId);
+ assertEquals(TEST_WINDOWING_MODE, mResult.mWindowingMode);
+ assertEquals(TEST_BOUNDS, mResult.mBounds);
+ }
+
+ @Test
public void testClearsRecordsOfTheUserOnUserCleanUp() {
mTarget.saveTask(mTestTask);
diff --git a/services/tests/wmtests/src/com/android/server/wm/RemoteAnimationControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/RemoteAnimationControllerTest.java
index c7f94ef..34ac835 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RemoteAnimationControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RemoteAnimationControllerTest.java
@@ -98,7 +98,7 @@
mDisplayContent.mOpeningApps.add(win.mActivityRecord);
try {
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
@@ -136,7 +136,7 @@
public void testCancel() throws Exception {
final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin");
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
@@ -150,7 +150,7 @@
public void testTimeout() throws Exception {
final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin");
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
@@ -170,7 +170,8 @@
final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION,
"testWin");
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(
- win.mActivityRecord, new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ win.mActivityRecord, new Point(50, 100), null, new Rect(50, 100, 150, 150),
+ null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
@@ -201,7 +202,7 @@
public void testNotReallyStarted() {
final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin");
mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null);
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null);
mController.goodToGo();
verifyNoMoreInteractionsExceptAsBinder(mMockRunner);
}
@@ -211,9 +212,9 @@
final WindowState win1 = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin1");
final WindowState win2 = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin2");
mController.createRemoteAnimationRecord(win1.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null);
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null);
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win2.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
@@ -234,7 +235,7 @@
public void testRemovedBeforeStarted() {
final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin");
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
win.mActivityRecord.removeImmediately();
@@ -250,7 +251,7 @@
mDisplayContent.mChangingContainers.add(win.mActivityRecord);
try {
final RemoteAnimationRecord record = mController.createRemoteAnimationRecord(
- win.mActivityRecord, new Point(50, 100), new Rect(50, 100, 150, 150),
+ win.mActivityRecord, new Point(50, 100), null, new Rect(50, 100, 150, 150),
new Rect(0, 0, 200, 200));
assertNotNull(record.mThumbnailAdapter);
((AnimationAdapter) record.mAdapter)
@@ -304,7 +305,7 @@
mDisplayContent.mOpeningApps.add(win.mActivityRecord);
try {
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
@@ -333,7 +334,7 @@
mDisplayContent.mOpeningApps.add(win.mActivityRecord);
try {
final AnimationAdapter adapter = mController.createRemoteAnimationRecord(win.mActivityRecord,
- new Point(50, 100), new Rect(50, 100, 150, 150), null).mAdapter;
+ new Point(50, 100), null, new Rect(50, 100, 150, 150), null).mAdapter;
adapter.startAnimation(mMockLeash, mMockTransaction, ANIMATION_TYPE_APP_TRANSITION,
mFinishedCallback);
mController.goodToGo();
diff --git a/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java
index 277bc41..67b1dac 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RootWindowContainerTests.java
@@ -27,6 +27,8 @@
import static org.junit.Assert.assertTrue;
import android.app.WindowConfiguration;
+import android.content.ComponentName;
+import android.content.pm.ActivityInfo;
import android.platform.test.annotations.Presubmit;
import androidx.test.filters.SmallTest;
@@ -109,5 +111,27 @@
assertEquals(WindowConfiguration.WINDOWING_MODE_FREEFORM,
mWm.getDefaultDisplayContentLocked().getWindowingMode());
}
+
+ /**
+ * This test ensures that an existing single instance activity with alias name can be found by
+ * the same activity info. So {@link ActivityStarter#getReusableTask} won't miss it that leads
+ * to create an unexpected new instance.
+ */
+ @Test
+ public void testFindActivityByTargetComponent() {
+ final ComponentName aliasComponent = ComponentName.createRelative(
+ ActivityTestsBase.DEFAULT_COMPONENT_PACKAGE_NAME, ".AliasActivity");
+ final ComponentName targetComponent = ComponentName.createRelative(
+ aliasComponent.getPackageName(), ".TargetActivity");
+ final ActivityRecord activity = new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
+ .setComponent(aliasComponent)
+ .setTargetActivity(targetComponent.getClassName())
+ .setLaunchMode(ActivityInfo.LAUNCH_SINGLE_INSTANCE)
+ .setCreateTask(true)
+ .build();
+
+ assertEquals(activity, mWm.mRoot.findActivity(activity.intent, activity.info,
+ false /* compareIntentFilters */));
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
index ba4a82f..edf81ea 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SizeCompatTests.java
@@ -107,10 +107,16 @@
setUpApp(display);
// Put app window into freeform and then make it a compat app.
- mTask.setBounds(100, 100, 400, 600);
+ final Rect bounds = new Rect(100, 100, 400, 600);
+ mTask.setBounds(bounds);
prepareUnresizable(-1.f /* maxAspect */, SCREEN_ORIENTATION_PORTRAIT);
+ assertEquals(bounds, mActivity.getBounds());
- final Rect bounds = new Rect(mActivity.getBounds());
+ // The activity should be able to accept negative x position [-150, 100 - 150, 600].
+ final int dx = bounds.left + bounds.width() / 2;
+ mTask.setBounds(bounds.left - dx, bounds.top, bounds.right - dx, bounds.bottom);
+ assertEquals(mTask.getBounds(), mActivity.getBounds());
+
final int density = mActivity.getConfiguration().densityDpi;
// change display configuration to fullscreen
@@ -231,11 +237,7 @@
// The position should be horizontal centered.
assertEquals((displayWidth - bounds.width()) / 2, bounds.left);
- final WindowTestUtils.TestWindowState w = new WindowTestUtils.TestWindowState(
- mService.mWindowManager, mock(Session.class), new TestIWindow(),
- new WindowManager.LayoutParams(), mActivity);
- mActivity.addWindow(w);
- mActivity.mDisplayContent.mInputMethodTarget = w;
+ mActivity.mDisplayContent.mInputMethodTarget = addWindowToActivity(mActivity);
// Make sure IME cannot attach to the app, otherwise IME window will also be shifted.
assertFalse(mActivity.mDisplayContent.isImeAttachedToApp());
}
@@ -475,6 +477,25 @@
assertEquals((int) (dw * maxAspect), mActivity.getBounds().width());
// The bounds should be horizontal centered: (2500-1900)/2=350.
assertEquals((dh - mActivity.getBounds().width()) / 2, mActivity.getBounds().left);
+
+ // The letterbox needs a main window to layout.
+ addWindowToActivity(mActivity);
+ // Compute the frames of the window and invoke {@link ActivityRecord#layoutLetterbox}.
+ mActivity.mRootWindowContainer.performSurfacePlacement(false /* recoveringMemory */);
+ // The letterbox insets should be [350, 0 - 350, 0].
+ assertEquals(new Rect(mActivity.getBounds().left, 0, dh - mActivity.getBounds().right, 0),
+ mActivity.getLetterboxInsets());
+ }
+
+ private WindowState addWindowToActivity(ActivityRecord activity) {
+ final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
+ params.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
+ final WindowTestUtils.TestWindowState w = new WindowTestUtils.TestWindowState(
+ mService.mWindowManager, mock(Session.class), new TestIWindow(), params, mActivity);
+ WindowTestsBase.makeWindowVisible(w);
+ w.mWinAnimator.mDrawState = WindowStateAnimator.HAS_DRAWN;
+ mActivity.addWindow(w);
+ return w;
}
/**
diff --git a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
index 55d12db..091f493 100644
--- a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java
@@ -40,6 +40,7 @@
import android.app.AppOpsManager;
import android.app.usage.UsageStatsManagerInternal;
import android.content.BroadcastReceiver;
+import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.IntentFilter;
@@ -213,6 +214,9 @@
anyString(), anyInt());
doReturn(null).when(packageManagerInternal).getDefaultHomeActivity(anyInt());
+ ComponentName systemServiceComponent = new ComponentName("android.test.system.service", "");
+ doReturn(systemServiceComponent).when(packageManagerInternal).getSystemUiServiceComponent();
+
// PowerManagerInternal
final PowerManagerInternal pmi = mock(PowerManagerInternal.class);
final PowerSaveState state = new PowerSaveState.Builder().build();
@@ -318,6 +322,8 @@
}
private void tearDown() {
+ mWmService.mRoot.forAllDisplayPolicies(DisplayPolicy::release);
+
// Unregister display listener from root to avoid issues with subsequent tests.
mContext.getSystemService(DisplayManager.class)
.unregisterDisplayListener(mAtmService.mRootWindowContainer);
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskOrganizerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskOrganizerTests.java
index e501452..bc81d5e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskOrganizerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskOrganizerTests.java
@@ -32,6 +32,7 @@
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.never;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.reset;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.times;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
@@ -39,6 +40,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -128,7 +130,7 @@
final Task task = createTaskInStack(stack, 0 /* userId */);
final ITaskOrganizer organizer = registerMockOrganizer(WINDOWING_MODE_MULTI_WINDOW);
final ITaskOrganizer organizer2 = registerMockOrganizer(WINDOWING_MODE_PINNED);
-
+
stack.setWindowingMode(WINDOWING_MODE_MULTI_WINDOW);
verify(organizer).taskAppeared(any());
stack.setWindowingMode(WINDOWING_MODE_PINNED);
@@ -212,6 +214,16 @@
}
@Test
+ public void testRegisterTaskOrganizerWithExistingTasks() throws RemoteException {
+ final ActivityStack stack = createTaskStackOnDisplay(mDisplayContent);
+ final Task task = createTaskInStack(stack, 0 /* userId */);
+ stack.setWindowingMode(WINDOWING_MODE_PINNED);
+
+ final ITaskOrganizer organizer = registerMockOrganizer(WINDOWING_MODE_PINNED);
+ verify(organizer, times(1)).taskAppeared(any());
+ }
+
+ @Test
public void testTaskTransaction() {
removeGlobalMinSizeRestriction();
final ActivityStack stack = new ActivityTestsBase.StackBuilder(mWm.mRoot)
@@ -240,6 +252,32 @@
}
@Test
+ public void testSetWindowingMode() {
+ final ActivityStack stack = new ActivityTestsBase.StackBuilder(mWm.mRoot)
+ .setWindowingMode(WINDOWING_MODE_FREEFORM).build();
+ final WindowContainerTransaction t = new WindowContainerTransaction();
+
+ t.setWindowingMode(stack.mRemoteToken, WINDOWING_MODE_FULLSCREEN);
+ mWm.mAtmService.mTaskOrganizerController.applyContainerTransaction(t, null);
+
+ assertEquals(WINDOWING_MODE_FULLSCREEN, stack.getWindowingMode());
+ }
+
+ @Test
+ public void testSetActivityWindowingMode() {
+ final ActivityRecord record = makePipableActivity();
+ final ActivityStack stack = record.getStack();
+ final WindowContainerTransaction t = new WindowContainerTransaction();
+
+ t.setWindowingMode(stack.mRemoteToken, WINDOWING_MODE_PINNED);
+ t.setActivityWindowingMode(stack.mRemoteToken, WINDOWING_MODE_FULLSCREEN);
+ mWm.mAtmService.mTaskOrganizerController.applyContainerTransaction(t, null);
+
+ assertEquals(WINDOWING_MODE_FULLSCREEN, record.getWindowingMode());
+ assertEquals(WINDOWING_MODE_PINNED, stack.getWindowingMode());
+ }
+
+ @Test
public void testContainerChanges() {
removeGlobalMinSizeRestriction();
final ActivityStack stack = new ActivityTestsBase.StackBuilder(mWm.mRoot)
@@ -253,6 +291,30 @@
}
@Test
+ public void testOverrideConfigSize() {
+ removeGlobalMinSizeRestriction();
+ final ActivityStack stack = new ActivityTestsBase.StackBuilder(mWm.mRoot)
+ .setWindowingMode(WINDOWING_MODE_FREEFORM).build();
+ final Task task = stack.getTopMostTask();
+ WindowContainerTransaction t = new WindowContainerTransaction();
+ t.setBounds(task.mRemoteToken, new Rect(10, 10, 100, 100));
+ mWm.mAtmService.mTaskOrganizerController.applyContainerTransaction(t, null);
+ final int origScreenWDp = task.getConfiguration().screenHeightDp;
+ final int origScreenHDp = task.getConfiguration().screenHeightDp;
+ t = new WindowContainerTransaction();
+ // verify that setting config overrides on parent restricts children.
+ t.setScreenSizeDp(stack.mRemoteToken, origScreenWDp, origScreenHDp);
+ t.setBounds(task.mRemoteToken, new Rect(10, 10, 150, 200));
+ mWm.mAtmService.mTaskOrganizerController.applyContainerTransaction(t, null);
+ assertEquals(origScreenHDp, task.getConfiguration().screenHeightDp);
+ t = new WindowContainerTransaction();
+ t.setScreenSizeDp(stack.mRemoteToken, Configuration.SCREEN_WIDTH_DP_UNDEFINED,
+ Configuration.SCREEN_HEIGHT_DP_UNDEFINED);
+ mWm.mAtmService.mTaskOrganizerController.applyContainerTransaction(t, null);
+ assertNotEquals(origScreenHDp, task.getConfiguration().screenHeightDp);
+ }
+
+ @Test
public void testCreateDeleteRootTasks() {
RunningTaskInfo info1 = mWm.mAtmService.mTaskOrganizerController.createRootTask(
Display.DEFAULT_DISPLAY,
@@ -320,7 +382,7 @@
public void taskAppeared(RunningTaskInfo taskInfo) { }
@Override
- public void taskVanished(IWindowContainer container) { }
+ public void taskVanished(RunningTaskInfo container) { }
@Override
public void transactionReady(int id, SurfaceControl.Transaction t) { }
@@ -374,7 +436,7 @@
public void taskAppeared(RunningTaskInfo taskInfo) { }
@Override
- public void taskVanished(IWindowContainer container) { }
+ public void taskVanished(RunningTaskInfo container) { }
@Override
public void transactionReady(int id, SurfaceControl.Transaction t) { }
@@ -489,6 +551,7 @@
final Task task = createTaskInStack(stackController1, 0 /* userId */);
final ITaskOrganizer organizer = registerMockOrganizer();
final WindowState w = createAppWindow(task, TYPE_APPLICATION, "Enlightened Window");
+ makeWindowVisible(w);
BLASTSyncEngine bse = new BLASTSyncEngine();
@@ -506,6 +569,60 @@
.transactionReady(anyInt(), any());
}
+ @Test
+ public void testBLASTCallbackWithInvisibleWindow() {
+ final ActivityStack stackController1 = createTaskStackOnDisplay(mDisplayContent);
+ final Task task = createTaskInStack(stackController1, 0 /* userId */);
+ final ITaskOrganizer organizer = registerMockOrganizer();
+ final WindowState w = createAppWindow(task, TYPE_APPLICATION, "Enlightened Window");
+
+ BLASTSyncEngine bse = new BLASTSyncEngine();
+
+ BLASTSyncEngine.TransactionReadyListener transactionListener =
+ mock(BLASTSyncEngine.TransactionReadyListener.class);
+
+ int id = bse.startSyncSet(transactionListener);
+ bse.addToSyncSet(id, task);
+ bse.setReady(id);
+
+ // Since the window was invisible, the Task had no visible leaves and the sync should
+ // complete as soon as we call setReady.
+ verify(transactionListener)
+ .transactionReady(anyInt(), any());
+ }
+
+ @Test
+ public void testBLASTCallbackWithChildWindow() {
+ final ActivityStack stackController1 = createTaskStackOnDisplay(mDisplayContent);
+ final Task task = createTaskInStack(stackController1, 0 /* userId */);
+ final ITaskOrganizer organizer = registerMockOrganizer();
+ final WindowState w = createAppWindow(task, TYPE_APPLICATION, "Enlightened Window");
+ final WindowState child = createWindow(w, TYPE_APPLICATION, "Other Window");
+
+ w.mActivityRecord.setVisible(true);
+ makeWindowVisible(w, child);
+
+ BLASTSyncEngine bse = new BLASTSyncEngine();
+
+ BLASTSyncEngine.TransactionReadyListener transactionListener =
+ mock(BLASTSyncEngine.TransactionReadyListener.class);
+
+ int id = bse.startSyncSet(transactionListener);
+ assertEquals(true, bse.addToSyncSet(id, task));
+ bse.setReady(id);
+ w.finishDrawing(null);
+
+ // Since we have a child window we still shouldn't be done.
+ verify(transactionListener, never())
+ .transactionReady(anyInt(), any());
+ reset(transactionListener);
+
+ child.finishDrawing(null);
+ // Ah finally! Done
+ verify(transactionListener)
+ .transactionReady(anyInt(), any());
+ }
+
class StubOrganizer extends ITaskOrganizer.Stub {
RunningTaskInfo mInfo;
@@ -514,7 +631,7 @@
mInfo = info;
}
@Override
- public void taskVanished(IWindowContainer wc) {
+ public void taskVanished(RunningTaskInfo info) {
}
@Override
public void transactionReady(int id, SurfaceControl.Transaction t) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java
index 52b465f..ea52d7d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java
@@ -36,7 +36,6 @@
import android.platform.test.annotations.Presubmit;
import android.util.DisplayMetrics;
import android.util.Log;
-import android.view.Display;
import androidx.test.filters.FlakyTest;
import androidx.test.filters.SmallTest;
@@ -71,18 +70,21 @@
public void setUp() {
TaskPositioner.setFactory(null);
- final Display display = mDisplayContent.getDisplay();
- final DisplayMetrics dm = new DisplayMetrics();
- display.getMetrics(dm);
+ final DisplayMetrics dm = mDisplayContent.getDisplayMetrics();
// This should be the same calculation as the TaskPositioner uses.
mMinVisibleWidth = dipToPixel(MINIMUM_VISIBLE_WIDTH_IN_DP, dm);
mMinVisibleHeight = dipToPixel(MINIMUM_VISIBLE_HEIGHT_IN_DP, dm);
removeGlobalMinSizeRestriction();
- WindowState win = createWindow(null, TYPE_BASE_APPLICATION, "window");
- mPositioner = new TaskPositioner(mWm, mWm.mAtmService);
-
+ final ActivityStack stack = createTaskStackOnDisplay(mDisplayContent);
+ final ActivityRecord activity = new ActivityTestsBase.ActivityBuilder(stack.mAtmService)
+ .setStack(stack)
+ // In real case, there is no additional level for freeform mode.
+ .setCreateTask(false)
+ .build();
+ final WindowState win = createWindow(null, TYPE_BASE_APPLICATION, activity, "window");
+ mPositioner = new TaskPositioner(mWm);
mPositioner.register(mDisplayContent, win);
win.getRootTask().setWindowingMode(WINDOWING_MODE_FREEFORM);
@@ -109,6 +111,28 @@
assertTrue(created[0]);
}
+ /** This tests that the window can move in all directions. */
+ @Test
+ public void testMoveWindow() {
+ final Rect displayBounds = mDisplayContent.getBounds();
+ final int windowSize = Math.min(displayBounds.width(), displayBounds.height()) / 2;
+ final int left = displayBounds.centerX() - windowSize / 2;
+ final int top = displayBounds.centerY() - windowSize / 2;
+ final Rect r = new Rect(left, top, left + windowSize, top + windowSize);
+ mPositioner.mTask.setBounds(r);
+ mPositioner.startDrag(false /* resizing */, false /* preserveOrientation */, left, top);
+
+ // Move upper left.
+ mPositioner.notifyMoveLocked(left - MOUSE_DELTA_X, top - MOUSE_DELTA_Y);
+ r.offset(-MOUSE_DELTA_X, -MOUSE_DELTA_Y);
+ assertBoundsEquals(r, mPositioner.getWindowDragBounds());
+
+ // Move bottom right.
+ mPositioner.notifyMoveLocked(left, top);
+ r.offset(MOUSE_DELTA_X, MOUSE_DELTA_Y);
+ assertBoundsEquals(r, mPositioner.getWindowDragBounds());
+ }
+
/**
* This tests that free resizing will allow to change the orientation as well
* as does some basic tests (e.g. dragging in Y only will keep X stable).
diff --git a/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java b/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java
index e1475a4..91c3c27 100644
--- a/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TestIWindow.java
@@ -77,7 +77,8 @@
}
@Override
- public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, boolean sync)
+ public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep, float zoom,
+ boolean sync)
throws RemoteException {
}
@@ -85,7 +86,6 @@
public void dispatchWallpaperCommand(String action, int x, int y, int z, Bundle extras,
boolean sync) throws RemoteException {
}
-
@Override
public void dispatchDragEvent(DragEvent event) throws RemoteException {
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
index aa66524..900f014 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WallpaperControllerTests.java
@@ -17,19 +17,29 @@
package com.android.server.wm;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
+import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
+import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
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 org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyFloat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.IBinder;
+import android.os.RemoteException;
import android.platform.test.annotations.Presubmit;
import android.view.DisplayInfo;
import android.view.Gravity;
@@ -139,4 +149,124 @@
assertEquals(Configuration.ORIENTATION_LANDSCAPE, dc.getConfiguration().orientation);
assertEquals(portraitFrame, wallpaperWindow.getFrameLw());
}
+
+ @Test
+ public void testWallpaperZoom() throws RemoteException {
+ final DisplayContent dc = mWm.mRoot.getDefaultDisplay();
+ final WallpaperWindowToken wallpaperWindowToken = new WallpaperWindowToken(mWm,
+ mock(IBinder.class), true, dc, true /* ownerCanManageAppTokens */);
+ final WindowState wallpaperWindow = createWindow(null, TYPE_WALLPAPER, wallpaperWindowToken,
+ "wallpaperWindow");
+ wallpaperWindow.getAttrs().privateFlags |=
+ WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS;
+
+ final WindowState homeWindow = createWallpaperTargetWindow(dc);
+
+ spyOn(dc.mWallpaperController);
+ doReturn(true).when(dc.mWallpaperController).isWallpaperVisible();
+
+ dc.mWallpaperController.adjustWallpaperWindows();
+
+ spyOn(wallpaperWindow.mClient);
+
+ float zoom = .5f;
+ dc.mWallpaperController.setWallpaperZoomOut(homeWindow, zoom);
+ assertEquals(zoom, wallpaperWindow.mWallpaperZoomOut, .01f);
+ verify(wallpaperWindow.mClient).dispatchWallpaperOffsets(anyFloat(), anyFloat(), anyFloat(),
+ anyFloat(), eq(zoom), anyBoolean());
+ }
+
+ @Test
+ public void testWallpaperZoom_shouldNotScaleWallpaper() throws RemoteException {
+ final DisplayContent dc = mWm.mRoot.getDefaultDisplay();
+ final WallpaperWindowToken wallpaperWindowToken = new WallpaperWindowToken(mWm,
+ mock(IBinder.class), true, dc, true /* ownerCanManageAppTokens */);
+ final WindowState wallpaperWindow = createWindow(null, TYPE_WALLPAPER, wallpaperWindowToken,
+ "wallpaperWindow");
+ wallpaperWindow.getAttrs().privateFlags |=
+ WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS;
+
+ final WindowState homeWindow = createWallpaperTargetWindow(dc);
+
+ spyOn(dc.mWallpaperController);
+ doReturn(true).when(dc.mWallpaperController).isWallpaperVisible();
+
+ dc.mWallpaperController.adjustWallpaperWindows();
+
+ spyOn(wallpaperWindow.mClient);
+
+ float newZoom = .5f;
+ wallpaperWindow.mShouldScaleWallpaper = false;
+ // Set zoom, and make sure the window animator scale didn't actually change, but the zoom
+ // value did, and we do dispatch the zoom to the wallpaper service
+ dc.mWallpaperController.setWallpaperZoomOut(homeWindow, newZoom);
+ assertEquals(newZoom, wallpaperWindow.mWallpaperZoomOut, .01f);
+ assertEquals(1f, wallpaperWindow.mWinAnimator.mWallpaperScale, .01f);
+ verify(wallpaperWindow.mClient).dispatchWallpaperOffsets(anyFloat(), anyFloat(), anyFloat(),
+ anyFloat(), eq(newZoom), anyBoolean());
+ }
+
+ @Test
+ public void testWallpaperZoom_multipleCallers() {
+ final DisplayContent dc = mWm.mRoot.getDefaultDisplay();
+ final WallpaperWindowToken wallpaperWindowToken = new WallpaperWindowToken(mWm,
+ mock(IBinder.class), true, dc,
+ true /* ownerCanManageAppTokens */);
+ final WindowState wallpaperWindow = createWindow(null, TYPE_WALLPAPER, wallpaperWindowToken,
+ "wallpaperWindow");
+ wallpaperWindow.getAttrs().privateFlags |=
+ WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS;
+
+
+ spyOn(dc.mWallpaperController);
+ doReturn(true).when(dc.mWallpaperController).isWallpaperVisible();
+
+ final WindowState homeWindow = createWallpaperTargetWindow(dc);
+
+ WindowState otherWindow = createWindow(null /* parent */, TYPE_APPLICATION, dc,
+ "otherWindow");
+
+ dc.mWallpaperController.adjustWallpaperWindows();
+
+ spyOn(wallpaperWindow.mClient);
+
+ // Set zoom from 2 windows
+ float homeWindowInitialZoom = .5f;
+ float otherWindowInitialZoom = .7f;
+ dc.mWallpaperController.setWallpaperZoomOut(homeWindow, homeWindowInitialZoom);
+ dc.mWallpaperController.setWallpaperZoomOut(otherWindow, otherWindowInitialZoom);
+ // Make sure the largest one wins
+ assertEquals(otherWindowInitialZoom, wallpaperWindow.mWallpaperZoomOut, .01f);
+
+ // Change zoom to a larger zoom from homeWindow
+ float homeWindowZoom2 = .8f;
+ dc.mWallpaperController.setWallpaperZoomOut(homeWindow, homeWindowZoom2);
+ // New zoom should be current
+ assertEquals(homeWindowZoom2, wallpaperWindow.mWallpaperZoomOut, .01f);
+
+ // Set homeWindow zoom to a lower zoom, but keep the one from otherWindow
+ dc.mWallpaperController.setWallpaperZoomOut(homeWindow, homeWindowInitialZoom);
+
+ // Zoom from otherWindow should be the current.
+ assertEquals(otherWindowInitialZoom, wallpaperWindow.mWallpaperZoomOut, .01f);
+ }
+
+
+ private WindowState createWallpaperTargetWindow(DisplayContent dc) {
+ final ActivityRecord homeActivity = new ActivityTestsBase.ActivityBuilder(mWm.mAtmService)
+ .setStack(dc.getRootHomeTask())
+ .setCreateTask(true)
+ .build();
+ homeActivity.setVisibility(true);
+
+ WindowState appWindow = createWindow(null /* parent */, TYPE_BASE_APPLICATION,
+ homeActivity, "wallpaperTargetWindow");
+ appWindow.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
+ appWindow.mHasSurface = true;
+ spyOn(appWindow);
+ doReturn(true).when(appWindow).isDrawFinishedLw();
+
+ homeActivity.addWindow(appWindow);
+ return appWindow;
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java
index 35723ab..da4bde5 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowManagerServiceTests.java
@@ -16,9 +16,16 @@
package com.android.server.wm;
+import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
+
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+
import android.content.pm.PackageManager;
+import android.os.IBinder;
import android.platform.test.annotations.Presubmit;
import androidx.test.filters.SmallTest;
@@ -57,4 +64,25 @@
return getInstrumentation().getTargetContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_AUTOMOTIVE);
}
+
+ @Test
+ public void testAddWindowToken() {
+ IBinder token = mock(IBinder.class);
+ mWm.addWindowToken(token, TYPE_TOAST, mDisplayContent.getDisplayId());
+
+ WindowToken windowToken = mWm.mRoot.getWindowToken(token);
+ assertFalse(windowToken.mRoundedCornerOverlay);
+ assertFalse(windowToken.mFromClientToken);
+ }
+
+ @Test
+ public void testAddWindowTokenWithOptions() {
+ IBinder token = mock(IBinder.class);
+ mWm.addWindowTokenWithOptions(token, TYPE_TOAST, mDisplayContent.getDisplayId(),
+ null /* options */, null /* options */);
+
+ WindowToken windowToken = mWm.mRoot.getWindowToken(token);
+ assertFalse(windowToken.mRoundedCornerOverlay);
+ assertTrue(windowToken.mFromClientToken);
+ }
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
index 34e487b..07a6179 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowProcessControllerTests.java
@@ -29,6 +29,7 @@
import static org.mockito.Mockito.when;
import android.app.IApplicationThread;
+import android.content.ComponentName;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.platform.test.annotations.Presubmit;
@@ -55,8 +56,11 @@
@Before
public void setUp() {
mMockListener = mock(WindowProcessListener.class);
+
+ ApplicationInfo info = mock(ApplicationInfo.class);
+ info.packageName = "test.package.name";
mWpc = new WindowProcessController(
- mService, mock(ApplicationInfo.class), null, 0, -1, null, mMockListener);
+ mService, info, null, 0, -1, null, mMockListener);
mWpc.setThread(mock(IApplicationThread.class));
}
@@ -176,6 +180,26 @@
assertEquals(mWpc.getLastReportedConfiguration(), newConfig);
}
+ @Test
+ public void testActivityNotOverridingSystemUiProcessConfig() {
+ final ComponentName systemUiServiceComponent = mService.getSysUiServiceComponentLocked();
+ ApplicationInfo applicationInfo = mock(ApplicationInfo.class);
+ applicationInfo.packageName = systemUiServiceComponent.getPackageName();
+
+ WindowProcessController wpc = new WindowProcessController(
+ mService, applicationInfo, null, 0, -1, null, mMockListener);
+ wpc.setThread(mock(IApplicationThread.class));
+
+ final ActivityRecord activity = new ActivityBuilder(mService)
+ .setCreateTask(true)
+ .setUseProcess(wpc)
+ .build();
+
+ wpc.addActivityIfNeeded(activity);
+ // System UI owned processes should not be registered for activity config changes.
+ assertFalse(wpc.registeredForActivityConfigChanges());
+ }
+
private TestDisplayContent createTestDisplayContentInContainer() {
return new TestDisplayContent.Builder(mService, 1000, 1500).build();
}
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java
index e6aed49..38f643d 100644
--- a/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTokenTests.java
@@ -25,7 +25,9 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import android.os.IBinder;
import android.platform.test.annotations.Presubmit;
import androidx.test.filters.SmallTest;
@@ -129,4 +131,28 @@
// Verify that the token windows are no longer attached to it.
assertEquals(0, token.getWindowsCount());
}
+
+ /**
+ * Test that {@link WindowToken} constructor parameters is set with expectation.
+ */
+ @Test
+ public void testWindowTokenConstructorSanity() {
+ WindowToken token = new WindowToken(mDisplayContent.mWmService, mock(IBinder.class),
+ TYPE_TOAST, true /* persistOnEmpty */, mDisplayContent,
+ true /* ownerCanManageAppTokens */);
+ assertFalse(token.mRoundedCornerOverlay);
+ assertFalse(token.mFromClientToken);
+
+ token = new WindowToken(mDisplayContent.mWmService, mock(IBinder.class), TYPE_TOAST,
+ true /* persistOnEmpty */, mDisplayContent, true /* ownerCanManageAppTokens */,
+ true /* roundedCornerOverlay */);
+ assertTrue(token.mRoundedCornerOverlay);
+ assertFalse(token.mFromClientToken);
+
+ token = new WindowToken(mDisplayContent.mWmService, mock(IBinder.class), TYPE_TOAST,
+ true /* persistOnEmpty */, mDisplayContent, true /* ownerCanManageAppTokens */,
+ true /* roundedCornerOverlay */, true /* fromClientToken */);
+ assertTrue(token.mRoundedCornerOverlay);
+ assertTrue(token.mFromClientToken);
+ }
}
diff --git a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
index ef9a73b..9d48955 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
@@ -98,8 +98,7 @@
// Persist versioned backup files.
// Should be false, except when testing new versions
- // STOPSHIP: b/139937606 this should be false on launch
- static final boolean KEEP_BACKUP_DIR = true;
+ static final boolean KEEP_BACKUP_DIR = false;
private static final String TAG = "UsageStatsDatabase";
private static final boolean DEBUG = UsageStatsService.DEBUG;
@@ -412,6 +411,7 @@
}
if (mBackupsDir.exists() && !KEEP_BACKUP_DIR) {
+ mUpgradePerformed = true; // updated here to ensure that data is cleaned up
deleteDirectory(mBackupsDir);
}
}
diff --git a/services/usage/java/com/android/server/usage/UsageStatsService.java b/services/usage/java/com/android/server/usage/UsageStatsService.java
index 0d1b352..bbe9851 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsService.java
@@ -137,8 +137,7 @@
private static final File USAGE_STATS_LEGACY_DIR = new File(
Environment.getDataSystemDirectory(), "usagestats");
// For migration purposes, indicates whether to keep the legacy usage stats directory or not
- // STOPSHIP: b/138323140 this should be false on launch
- private static final boolean KEEP_LEGACY_DIR = true;
+ private static final boolean KEEP_LEGACY_DIR = false;
private static final char TOKEN_DELIMITER = '/';
@@ -648,7 +647,7 @@
private void deleteLegacyDir(int userId) {
final File legacyUserDir = new File(USAGE_STATS_LEGACY_DIR, Integer.toString(userId));
- if (!KEEP_LEGACY_DIR) {
+ if (!KEEP_LEGACY_DIR && legacyUserDir.exists()) {
deleteRecursively(legacyUserDir);
if (legacyUserDir.exists()) {
Slog.w(TAG, "Error occurred while attempting to delete legacy usage stats "
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/DatabaseHelper.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/DatabaseHelper.java
index af81ab6..be0987d 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/DatabaseHelper.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/DatabaseHelper.java
@@ -257,6 +257,9 @@
int userHandle) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
+ if (DBG) {
+ Slog.w(TAG, "querying database: " + selectQuery);
+ }
try {
if (c.moveToFirst()) {
@@ -334,7 +337,10 @@
return model;
} while (c.moveToNext());
}
- Slog.w(TAG, "No SoundModel available for the given keyphrase");
+
+ if (DBG) {
+ Slog.w(TAG, "No SoundModel available for the given keyphrase");
+ }
} finally {
c.close();
db.close();
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index 0b24dd2..0eba07b 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -41,6 +41,7 @@
import android.content.res.Resources;
import android.database.ContentObserver;
import android.hardware.soundtrigger.IRecognitionStatusCallback;
+import android.hardware.soundtrigger.KeyphraseEnrollmentInfo;
import android.hardware.soundtrigger.KeyphraseMetadata;
import android.hardware.soundtrigger.ModelParams;
import android.hardware.soundtrigger.SoundTrigger;
@@ -223,6 +224,7 @@
class VoiceInteractionManagerServiceStub extends IVoiceInteractionManagerService.Stub {
VoiceInteractionManagerServiceImpl mImpl;
+ KeyphraseEnrollmentInfo mEnrollmentApplicationInfo;
private boolean mSafeMode;
private int mCurUser;
@@ -447,6 +449,15 @@
}
}
+ private void getOrCreateEnrollmentApplicationInfo() {
+ synchronized (this) {
+ if (mEnrollmentApplicationInfo == null) {
+ mEnrollmentApplicationInfo = new KeyphraseEnrollmentInfo(
+ mContext.getPackageManager());
+ }
+ }
+ }
+
private void setCurrentUserLocked(@UserIdInt int userHandle) {
mCurUser = userHandle;
final UserInfo userInfo = mUserManagerInternal.getUserInfo(mCurUser);
@@ -1380,12 +1391,17 @@
pw.println(" mCurUserUnlocked: " + mCurUserUnlocked);
pw.println(" mCurUserSupported: " + mCurUserSupported);
dumpSupportedUsers(pw, " ");
+ if (mEnrollmentApplicationInfo == null) {
+ pw.println(" (No enrollment application info)");
+ } else {
+ pw.println(" " + mEnrollmentApplicationInfo.toString());
+ }
mDbHelper.dump(pw);
if (mImpl == null) {
pw.println(" (No active implementation)");
- return;
+ } else {
+ mImpl.dumpLocked(fd, pw, args);
}
- mImpl.dumpLocked(fd, pw, args);
}
mSoundTriggerInternal.dump(fd, pw, args);
}
@@ -1438,8 +1454,9 @@
}
private boolean isCallerTrustedEnrollmentApplication() {
- return mImpl.mEnrollmentApplicationInfo.isUidSupportedEnrollmentApplication(
- Binder.getCallingUid());
+ getOrCreateEnrollmentApplicationInfo();
+ return mEnrollmentApplicationInfo.isUidSupportedEnrollmentApplication(
+ Binder.getCallingUid());
}
private void setImplLocked(VoiceInteractionManagerServiceImpl impl) {
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
index b813f87..a62b03c 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
@@ -36,7 +36,6 @@
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
-import android.hardware.soundtrigger.KeyphraseEnrollmentInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
@@ -79,7 +78,6 @@
final IActivityManager mAm;
final IActivityTaskManager mAtm;
final VoiceInteractionServiceInfo mInfo;
- final KeyphraseEnrollmentInfo mEnrollmentApplicationInfo;
final ComponentName mSessionComponentName;
final IWindowManager mIWindowManager;
boolean mBound = false;
@@ -135,7 +133,6 @@
mComponent = service;
mAm = ActivityManager.getService();
mAtm = ActivityTaskManager.getService();
- mEnrollmentApplicationInfo = new KeyphraseEnrollmentInfo(context.getPackageManager());
VoiceInteractionServiceInfo info;
try {
info = new VoiceInteractionServiceInfo(context.getPackageManager(), service, mUser);
@@ -406,7 +403,6 @@
pw.println(" Active session:");
mActiveSession.dump(" ", pw);
}
- pw.println(" " + mEnrollmentApplicationInfo.toString());
}
void startLocked() {
diff --git a/telecomm/java/android/telecom/CallRedirectionService.java b/telecomm/java/android/telecom/CallRedirectionService.java
index 36c6377..c832f53 100644
--- a/telecomm/java/android/telecom/CallRedirectionService.java
+++ b/telecomm/java/android/telecom/CallRedirectionService.java
@@ -38,16 +38,14 @@
*
* <p>
* Below is an example manifest registration for a {@code CallRedirectionService}.
- * <pre>
* {@code
* <service android:name="your.package.YourCallRedirectionServiceImplementation"
- * android:permission="android.permission.BIND_REDIRECTION_SERVICE">
+ * android:permission="android.permission.BIND_CALL_REDIRECTION_SERVICE">
* <intent-filter>
* <action android:name="android.telecom.CallRedirectionService"/>
* </intent-filter>
* </service>
* }
- * </pre>
*/
public abstract class CallRedirectionService extends Service {
/**
diff --git a/telecomm/java/android/telecom/Connection.java b/telecomm/java/android/telecom/Connection.java
index 5f33a3d..9dfa3ac 100755
--- a/telecomm/java/android/telecom/Connection.java
+++ b/telecomm/java/android/telecom/Connection.java
@@ -2331,7 +2331,6 @@
* See {@link TelecomManager} for valid values.
*/
public final void setAddress(Uri address, int presentation) {
- checkImmutable();
Log.d(this, "setAddress %s", address);
mAddress = address;
mAddressPresentation = presentation;
@@ -3358,6 +3357,7 @@
private boolean mImmutable = false;
public FailureSignalingConnection(DisconnectCause disconnectCause) {
setDisconnected(disconnectCause);
+ mImmutable = true;
}
public void checkImmutable() {
diff --git a/telecomm/java/android/telecom/DisconnectCause.java b/telecomm/java/android/telecom/DisconnectCause.java
index 0093843..bebbbd0 100644
--- a/telecomm/java/android/telecom/DisconnectCause.java
+++ b/telecomm/java/android/telecom/DisconnectCause.java
@@ -80,17 +80,20 @@
* Reason code (returned via {@link #getReason()}) which indicates that a call could not be
* completed because the cellular radio is off or out of service, the device is connected to
* a wifi network, but the user has not enabled wifi calling.
+ * @hide
*/
public static final String REASON_WIFI_ON_BUT_WFC_OFF = "REASON_WIFI_ON_BUT_WFC_OFF";
/**
* Reason code (returned via {@link #getReason()}), which indicates that the video telephony
* call was disconnected because IMS access is blocked.
+ * @hide
*/
public static final String REASON_IMS_ACCESS_BLOCKED = "REASON_IMS_ACCESS_BLOCKED";
/**
* Reason code, which indicates that the conference call is simulating single party conference.
+ * @hide
*/
public static final String REASON_EMULATING_SINGLE_CALL = "EMULATING_SINGLE_CALL";
diff --git a/telecomm/java/android/telecom/PhoneAccount.java b/telecomm/java/android/telecom/PhoneAccount.java
index 4e6e1a5..768c8ee 100644
--- a/telecomm/java/android/telecom/PhoneAccount.java
+++ b/telecomm/java/android/telecom/PhoneAccount.java
@@ -53,7 +53,6 @@
* {@link android.telecom.ConnectionService}.
* @hide
*/
- @SystemApi
public static final String EXTRA_SORT_ORDER =
"android.telecom.extra.SORT_ORDER";
@@ -89,7 +88,6 @@
* rather than cellular calls.
* @hide
*/
- @SystemApi
public static final String EXTRA_ALWAYS_USE_VOIP_AUDIO_MODE =
"android.telecom.extra.ALWAYS_USE_VOIP_AUDIO_MODE";
@@ -114,7 +112,6 @@
*
* @hide
*/
- @SystemApi
public static final String EXTRA_SUPPORTS_VIDEO_CALLING_FALLBACK =
"android.telecom.extra.SUPPORTS_VIDEO_CALLING_FALLBACK";
@@ -163,7 +160,6 @@
* in progress.
* @hide
*/
- @SystemApi
public static final String EXTRA_PLAY_CALL_RECORDING_TONE =
"android.telecom.extra.PLAY_CALL_RECORDING_TONE";
@@ -258,7 +254,6 @@
* See {@link #getCapabilities}
* @hide
*/
- @SystemApi
public static final int CAPABILITY_EMERGENCY_CALLS_ONLY = 0x80;
/**
@@ -282,7 +277,6 @@
* convert all outgoing video calls to emergency numbers to audio-only.
* @hide
*/
- @SystemApi
public static final int CAPABILITY_EMERGENCY_VIDEO_CALLING = 0x200;
/**
@@ -340,7 +334,6 @@
*
* @hide
*/
- @SystemApi
public static final int CAPABILITY_EMERGENCY_PREFERRED = 0x2000;
/**
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 7f4fcc0..1792256 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -318,13 +318,13 @@
* the remote handle of the new call.
* @hide
*/
- @SystemApi
public static final String EXTRA_UNKNOWN_CALL_HANDLE =
"android.telecom.extra.UNKNOWN_CALL_HANDLE";
/**
* Optional extra for incoming and outgoing calls containing a long which specifies the time the
* call was created. This value is in milliseconds since boot.
+ * @hide
*/
public static final String EXTRA_CALL_CREATED_TIME_MILLIS =
"android.telecom.extra.CALL_CREATED_TIME_MILLIS";
@@ -388,7 +388,6 @@
* </ul>
* @hide
*/
- @SystemApi
public static final String EXTRA_CALL_TECHNOLOGY_TYPE =
"android.telecom.extra.CALL_TECHNOLOGY_TYPE";
@@ -731,7 +730,6 @@
* @see #EXTRA_CURRENT_TTY_MODE
* @hide
*/
- @SystemApi
public static final String ACTION_CURRENT_TTY_MODE_CHANGED =
"android.telecom.action.CURRENT_TTY_MODE_CHANGED";
@@ -746,7 +744,6 @@
* </ul>
* @hide
*/
- @SystemApi
public static final String EXTRA_CURRENT_TTY_MODE =
"android.telecom.extra.CURRENT_TTY_MODE";
@@ -757,7 +754,6 @@
* @see #EXTRA_TTY_PREFERRED_MODE
* @hide
*/
- @SystemApi
public static final String ACTION_TTY_PREFERRED_MODE_CHANGED =
"android.telecom.action.TTY_PREFERRED_MODE_CHANGED";
@@ -768,7 +764,6 @@
*
* @hide
*/
- @SystemApi
public static final String EXTRA_TTY_PREFERRED_MODE =
"android.telecom.extra.TTY_PREFERRED_MODE";
@@ -846,7 +841,6 @@
*
* @hide
*/
- @SystemApi
public static final String EXTRA_CALL_SOURCE = "android.telecom.extra.CALL_SOURCE";
/**
@@ -943,8 +937,8 @@
*/
public TelecomManager(Context context, ITelecomService telecomServiceImpl) {
Context appContext = context.getApplicationContext();
- if (appContext != null && Objects.equals(context.getFeatureId(),
- appContext.getFeatureId())) {
+ if (appContext != null && Objects.equals(context.getAttributionTag(),
+ appContext.getAttributionTag())) {
mContext = appContext;
} else {
mContext = context;
@@ -978,7 +972,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().getDefaultOutgoingPhoneAccount(uriScheme,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getDefaultOutgoingPhoneAccount", e);
@@ -1176,7 +1170,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().getSelfManagedPhoneAccounts(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getSelfManagedPhoneAccounts()", e);
@@ -1202,7 +1196,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().getCallCapablePhoneAccounts(includeDisabledAccounts,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getCallCapablePhoneAccounts(" +
@@ -1506,7 +1500,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().isVoiceMailNumber(accountHandle, number,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException calling ITelecomService#isVoiceMailNumber.", e);
@@ -1528,7 +1522,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().getVoiceMailNumber(accountHandle,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException calling ITelecomService#hasVoiceMailNumber.", e);
@@ -1549,7 +1543,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().getLine1Number(accountHandle,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException calling ITelecomService#getLine1Number.", e);
@@ -1571,7 +1565,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().isInCall(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException calling isInCall().", e);
@@ -1597,7 +1591,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().isInManagedCall(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException calling isInManagedCall().", e);
@@ -1778,7 +1772,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().isTtySupported(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException attempting to get TTY supported state.", e);
@@ -1803,7 +1797,7 @@
try {
if (isServiceConnected()) {
return getTelecomService().getCurrentTtyMode(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "RemoteException attempting to get the current TTY mode.", e);
@@ -2033,7 +2027,7 @@
if (service != null) {
try {
service.showInCallScreen(showDialpad, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#showCallScreen", e);
}
@@ -2096,7 +2090,7 @@
}
try {
service.placeCall(address, extras == null ? new Bundle() : extras,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#placeCall", e);
}
diff --git a/telephony/common/com/android/internal/telephony/CarrierAppUtils.java b/telephony/common/com/android/internal/telephony/CarrierAppUtils.java
index d9ae48f..b3d7c0d 100644
--- a/telephony/common/com/android/internal/telephony/CarrierAppUtils.java
+++ b/telephony/common/com/android/internal/telephony/CarrierAppUtils.java
@@ -30,6 +30,7 @@
import android.util.ArrayMap;
import android.util.Log;
+import com.android.internal.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.telephony.util.ArrayUtils;
@@ -162,7 +163,7 @@
for (ApplicationInfo ai : candidates) {
String packageName = ai.packageName;
String[] restrictedCarrierApps = Resources.getSystem().getStringArray(
- android.R.array.config_restrictedPreinstalledCarrierApps);
+ R.array.config_restrictedPreinstalledCarrierApps);
boolean hasPrivileges = telephonyManager != null
&& telephonyManager.checkCarrierPrivilegesForPackageAnyPhone(packageName)
== TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS
diff --git a/telephony/common/com/android/internal/telephony/GsmAlphabet.java b/telephony/common/com/android/internal/telephony/GsmAlphabet.java
index c62cec2..5c53f7e 100644
--- a/telephony/common/com/android/internal/telephony/GsmAlphabet.java
+++ b/telephony/common/com/android/internal/telephony/GsmAlphabet.java
@@ -19,10 +19,12 @@
import android.compat.annotation.UnsupportedAppUsage;
import android.content.res.Resources;
import android.os.Build;
-import android.text.TextUtils;
import android.util.Log;
+import android.text.TextUtils;
import android.util.SparseIntArray;
+import com.android.internal.R;
+
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
@@ -1087,10 +1089,8 @@
private static void enableCountrySpecificEncodings() {
Resources r = Resources.getSystem();
// See comments in frameworks/base/core/res/res/values/config.xml for allowed values
- sEnabledSingleShiftTables = r.getIntArray(
- android.R.array.config_sms_enabled_single_shift_tables);
- sEnabledLockingShiftTables = r.getIntArray(
- android.R.array.config_sms_enabled_locking_shift_tables);
+ sEnabledSingleShiftTables = r.getIntArray(R.array.config_sms_enabled_single_shift_tables);
+ sEnabledLockingShiftTables = r.getIntArray(R.array.config_sms_enabled_locking_shift_tables);
if (sEnabledSingleShiftTables.length > 0) {
sHighestEnabledSingleShiftCode =
diff --git a/telephony/common/com/google/android/mms/util/SqliteWrapper.java b/telephony/common/com/google/android/mms/util/SqliteWrapper.java
index 4871434..31fe4d7 100644
--- a/telephony/common/com/google/android/mms/util/SqliteWrapper.java
+++ b/telephony/common/com/google/android/mms/util/SqliteWrapper.java
@@ -60,7 +60,8 @@
@UnsupportedAppUsage
public static void checkSQLiteException(Context context, SQLiteException e) {
if (isLowMemory(e)) {
- Toast.makeText(context, android.R.string.low_memory, Toast.LENGTH_SHORT).show();
+ Toast.makeText(context, com.android.internal.R.string.low_memory,
+ Toast.LENGTH_SHORT).show();
} else {
throw e;
}
diff --git a/telephony/java/android/telephony/AccessNetworkConstants.java b/telephony/java/android/telephony/AccessNetworkConstants.java
index 01abb26..558f4cd 100644
--- a/telephony/java/android/telephony/AccessNetworkConstants.java
+++ b/telephony/java/android/telephony/AccessNetworkConstants.java
@@ -19,6 +19,10 @@
import android.annotation.IntDef;
import android.annotation.SystemApi;
import android.annotation.TestApi;
+import android.hardware.radio.V1_1.EutranBands;
+import android.hardware.radio.V1_1.GeranBands;
+import android.hardware.radio.V1_5.AccessNetwork;
+import android.hardware.radio.V1_5.UtranBands;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -84,13 +88,13 @@
public @interface RadioAccessNetworkType {}
public static final class AccessNetworkType {
- public static final int UNKNOWN = 0;
- public static final int GERAN = 1;
- public static final int UTRAN = 2;
- public static final int EUTRAN = 3;
- public static final int CDMA2000 = 4;
- public static final int IWLAN = 5;
- public static final int NGRAN = 6;
+ public static final int UNKNOWN = AccessNetwork.UNKNOWN;
+ public static final int GERAN = AccessNetwork.GERAN;
+ public static final int UTRAN = AccessNetwork.UTRAN;
+ public static final int EUTRAN = AccessNetwork.EUTRAN;
+ public static final int CDMA2000 = AccessNetwork.CDMA2000;
+ public static final int IWLAN = AccessNetwork.IWLAN;
+ public static final int NGRAN = AccessNetwork.NGRAN;
/** @hide */
private AccessNetworkType() {}
@@ -115,20 +119,20 @@
* http://www.etsi.org/deliver/etsi_ts/145000_145099/145005/14.00.00_60/ts_145005v140000p.pdf
*/
public static final class GeranBand {
- public static final int BAND_T380 = 1;
- public static final int BAND_T410 = 2;
- public static final int BAND_450 = 3;
- public static final int BAND_480 = 4;
- public static final int BAND_710 = 5;
- public static final int BAND_750 = 6;
- public static final int BAND_T810 = 7;
- public static final int BAND_850 = 8;
- public static final int BAND_P900 = 9;
- public static final int BAND_E900 = 10;
- public static final int BAND_R900 = 11;
- public static final int BAND_DCS1800 = 12;
- public static final int BAND_PCS1900 = 13;
- public static final int BAND_ER900 = 14;
+ public static final int BAND_T380 = GeranBands.BAND_T380;
+ public static final int BAND_T410 = GeranBands.BAND_T410;
+ public static final int BAND_450 = GeranBands.BAND_450;
+ public static final int BAND_480 = GeranBands.BAND_480;
+ public static final int BAND_710 = GeranBands.BAND_710;
+ public static final int BAND_750 = GeranBands.BAND_750;
+ public static final int BAND_T810 = GeranBands.BAND_T810;
+ public static final int BAND_850 = GeranBands.BAND_850;
+ public static final int BAND_P900 = GeranBands.BAND_P900;
+ public static final int BAND_E900 = GeranBands.BAND_E900;
+ public static final int BAND_R900 = GeranBands.BAND_R900;
+ public static final int BAND_DCS1800 = GeranBands.BAND_DCS1800;
+ public static final int BAND_PCS1900 = GeranBands.BAND_PCS1900;
+ public static final int BAND_ER900 = GeranBands.BAND_ER900;
/** @hide */
private GeranBand() {}
@@ -139,28 +143,28 @@
* http://www.etsi.org/deliver/etsi_ts/125100_125199/125104/13.03.00_60/ts_125104v130p.pdf
*/
public static final class UtranBand {
- public static final int BAND_1 = 1;
- public static final int BAND_2 = 2;
- public static final int BAND_3 = 3;
- public static final int BAND_4 = 4;
- public static final int BAND_5 = 5;
- public static final int BAND_6 = 6;
- public static final int BAND_7 = 7;
- public static final int BAND_8 = 8;
- public static final int BAND_9 = 9;
- public static final int BAND_10 = 10;
- public static final int BAND_11 = 11;
- public static final int BAND_12 = 12;
- public static final int BAND_13 = 13;
- public static final int BAND_14 = 14;
+ public static final int BAND_1 = UtranBands.BAND_1;
+ public static final int BAND_2 = UtranBands.BAND_2;
+ public static final int BAND_3 = UtranBands.BAND_3;
+ public static final int BAND_4 = UtranBands.BAND_4;
+ public static final int BAND_5 = UtranBands.BAND_5;
+ public static final int BAND_6 = UtranBands.BAND_6;
+ public static final int BAND_7 = UtranBands.BAND_7;
+ public static final int BAND_8 = UtranBands.BAND_8;
+ public static final int BAND_9 = UtranBands.BAND_9;
+ public static final int BAND_10 = UtranBands.BAND_10;
+ public static final int BAND_11 = UtranBands.BAND_11;
+ public static final int BAND_12 = UtranBands.BAND_12;
+ public static final int BAND_13 = UtranBands.BAND_13;
+ public static final int BAND_14 = UtranBands.BAND_14;
// band 15, 16, 17, 18 are reserved
- public static final int BAND_19 = 19;
- public static final int BAND_20 = 20;
- public static final int BAND_21 = 21;
- public static final int BAND_22 = 22;
+ public static final int BAND_19 = UtranBands.BAND_19;
+ public static final int BAND_20 = UtranBands.BAND_20;
+ public static final int BAND_21 = UtranBands.BAND_21;
+ public static final int BAND_22 = UtranBands.BAND_22;
// band 23, 24 are reserved
- public static final int BAND_25 = 25;
- public static final int BAND_26 = 26;
+ public static final int BAND_25 = UtranBands.BAND_25;
+ public static final int BAND_26 = UtranBands.BAND_26;
// Frequency bands for TD-SCDMA. Defined in 3GPP TS 25.102, Table 5.2.
@@ -169,38 +173,38 @@
* 1900 - 1920 MHz: Uplink and downlink transmission
* 2010 - 2025 MHz: Uplink and downlink transmission
*/
- public static final int BAND_A = 101;
+ public static final int BAND_A = UtranBands.BAND_A;
/**
* Band B
* 1850 - 1910 MHz: Uplink and downlink transmission
* 1930 - 1990 MHz: Uplink and downlink transmission
*/
- public static final int BAND_B = 102;
+ public static final int BAND_B = UtranBands.BAND_B;
/**
* Band C
* 1910 - 1930 MHz: Uplink and downlink transmission
*/
- public static final int BAND_C = 103;
+ public static final int BAND_C = UtranBands.BAND_C;
/**
* Band D
* 2570 - 2620 MHz: Uplink and downlink transmission
*/
- public static final int BAND_D = 104;
+ public static final int BAND_D = UtranBands.BAND_D;
/**
* Band E
* 2300—2400 MHz: Uplink and downlink transmission
*/
- public static final int BAND_E = 105;
+ public static final int BAND_E = UtranBands.BAND_E;
/**
* Band F
* 1880 - 1920 MHz: Uplink and downlink transmission
*/
- public static final int BAND_F = 106;
+ public static final int BAND_F = UtranBands.BAND_F;
/** @hide */
private UtranBand() {}
@@ -211,54 +215,54 @@
* http://www.etsi.org/deliver/etsi_ts/136100_136199/136101/14.03.00_60/ts_136101v140p.pdf
*/
public static final class EutranBand {
- public static final int BAND_1 = 1;
- public static final int BAND_2 = 2;
- public static final int BAND_3 = 3;
- public static final int BAND_4 = 4;
- public static final int BAND_5 = 5;
- public static final int BAND_6 = 6;
- public static final int BAND_7 = 7;
- public static final int BAND_8 = 8;
- public static final int BAND_9 = 9;
- public static final int BAND_10 = 10;
- public static final int BAND_11 = 11;
- public static final int BAND_12 = 12;
- public static final int BAND_13 = 13;
- public static final int BAND_14 = 14;
- public static final int BAND_17 = 17;
- public static final int BAND_18 = 18;
- public static final int BAND_19 = 19;
- public static final int BAND_20 = 20;
- public static final int BAND_21 = 21;
- public static final int BAND_22 = 22;
- public static final int BAND_23 = 23;
- public static final int BAND_24 = 24;
- public static final int BAND_25 = 25;
- public static final int BAND_26 = 26;
- public static final int BAND_27 = 27;
- public static final int BAND_28 = 28;
- public static final int BAND_30 = 30;
- public static final int BAND_31 = 31;
- public static final int BAND_33 = 33;
- public static final int BAND_34 = 34;
- public static final int BAND_35 = 35;
- public static final int BAND_36 = 36;
- public static final int BAND_37 = 37;
- public static final int BAND_38 = 38;
- public static final int BAND_39 = 39;
- public static final int BAND_40 = 40;
- public static final int BAND_41 = 41;
- public static final int BAND_42 = 42;
- public static final int BAND_43 = 43;
- public static final int BAND_44 = 44;
- public static final int BAND_45 = 45;
- public static final int BAND_46 = 46;
- public static final int BAND_47 = 47;
- public static final int BAND_48 = 48;
- public static final int BAND_65 = 65;
- public static final int BAND_66 = 66;
- public static final int BAND_68 = 68;
- public static final int BAND_70 = 70;
+ public static final int BAND_1 = EutranBands.BAND_1;
+ public static final int BAND_2 = EutranBands.BAND_2;
+ public static final int BAND_3 = EutranBands.BAND_3;
+ public static final int BAND_4 = EutranBands.BAND_4;
+ public static final int BAND_5 = EutranBands.BAND_5;
+ public static final int BAND_6 = EutranBands.BAND_6;
+ public static final int BAND_7 = EutranBands.BAND_7;
+ public static final int BAND_8 = EutranBands.BAND_8;
+ public static final int BAND_9 = EutranBands.BAND_9;
+ public static final int BAND_10 = EutranBands.BAND_10;
+ public static final int BAND_11 = EutranBands.BAND_11;
+ public static final int BAND_12 = EutranBands.BAND_12;
+ public static final int BAND_13 = EutranBands.BAND_13;
+ public static final int BAND_14 = EutranBands.BAND_14;
+ public static final int BAND_17 = EutranBands.BAND_17;
+ public static final int BAND_18 = EutranBands.BAND_18;
+ public static final int BAND_19 = EutranBands.BAND_19;
+ public static final int BAND_20 = EutranBands.BAND_20;
+ public static final int BAND_21 = EutranBands.BAND_21;
+ public static final int BAND_22 = EutranBands.BAND_22;
+ public static final int BAND_23 = EutranBands.BAND_23;
+ public static final int BAND_24 = EutranBands.BAND_24;
+ public static final int BAND_25 = EutranBands.BAND_25;
+ public static final int BAND_26 = EutranBands.BAND_26;
+ public static final int BAND_27 = EutranBands.BAND_27;
+ public static final int BAND_28 = EutranBands.BAND_28;
+ public static final int BAND_30 = EutranBands.BAND_30;
+ public static final int BAND_31 = EutranBands.BAND_31;
+ public static final int BAND_33 = EutranBands.BAND_33;
+ public static final int BAND_34 = EutranBands.BAND_34;
+ public static final int BAND_35 = EutranBands.BAND_35;
+ public static final int BAND_36 = EutranBands.BAND_36;
+ public static final int BAND_37 = EutranBands.BAND_37;
+ public static final int BAND_38 = EutranBands.BAND_38;
+ public static final int BAND_39 = EutranBands.BAND_39;
+ public static final int BAND_40 = EutranBands.BAND_40;
+ public static final int BAND_41 = EutranBands.BAND_41;
+ public static final int BAND_42 = EutranBands.BAND_42;
+ public static final int BAND_43 = EutranBands.BAND_43;
+ public static final int BAND_44 = EutranBands.BAND_44;
+ public static final int BAND_45 = EutranBands.BAND_45;
+ public static final int BAND_46 = EutranBands.BAND_46;
+ public static final int BAND_47 = EutranBands.BAND_47;
+ public static final int BAND_48 = EutranBands.BAND_48;
+ public static final int BAND_65 = EutranBands.BAND_65;
+ public static final int BAND_66 = EutranBands.BAND_66;
+ public static final int BAND_68 = EutranBands.BAND_68;
+ public static final int BAND_70 = EutranBands.BAND_70;
/** @hide */
private EutranBand() {};
@@ -304,51 +308,51 @@
*/
public static final class NgranBands {
/** FR1 bands */
- public static final int BAND_1 = 1;
- public static final int BAND_2 = 2;
- public static final int BAND_3 = 3;
- public static final int BAND_5 = 5;
- public static final int BAND_7 = 7;
- public static final int BAND_8 = 8;
- public static final int BAND_12 = 12;
- public static final int BAND_14 = 14;
- public static final int BAND_18 = 18;
- public static final int BAND_20 = 20;
- public static final int BAND_25 = 25;
- public static final int BAND_28 = 28;
- public static final int BAND_29 = 29;
- public static final int BAND_30 = 30;
- public static final int BAND_34 = 34;
- public static final int BAND_38 = 38;
- public static final int BAND_39 = 39;
- public static final int BAND_40 = 40;
- public static final int BAND_41 = 41;
- public static final int BAND_48 = 48;
- public static final int BAND_50 = 50;
- public static final int BAND_51 = 51;
- public static final int BAND_65 = 65;
- public static final int BAND_66 = 66;
- public static final int BAND_70 = 70;
- public static final int BAND_71 = 71;
- public static final int BAND_74 = 74;
- public static final int BAND_75 = 75;
- public static final int BAND_76 = 76;
- public static final int BAND_77 = 77;
- public static final int BAND_78 = 78;
- public static final int BAND_79 = 79;
- public static final int BAND_80 = 80;
- public static final int BAND_81 = 81;
- public static final int BAND_82 = 82;
- public static final int BAND_83 = 83;
- public static final int BAND_84 = 84;
- public static final int BAND_86 = 86;
- public static final int BAND_90 = 90;
+ public static final int BAND_1 = android.hardware.radio.V1_5.NgranBands.BAND_1;
+ public static final int BAND_2 = android.hardware.radio.V1_5.NgranBands.BAND_2;
+ public static final int BAND_3 = android.hardware.radio.V1_5.NgranBands.BAND_3;
+ public static final int BAND_5 = android.hardware.radio.V1_5.NgranBands.BAND_5;
+ public static final int BAND_7 = android.hardware.radio.V1_5.NgranBands.BAND_7;
+ public static final int BAND_8 = android.hardware.radio.V1_5.NgranBands.BAND_8;
+ public static final int BAND_12 = android.hardware.radio.V1_5.NgranBands.BAND_12;
+ public static final int BAND_14 = android.hardware.radio.V1_5.NgranBands.BAND_14;
+ public static final int BAND_18 = android.hardware.radio.V1_5.NgranBands.BAND_18;
+ public static final int BAND_20 = android.hardware.radio.V1_5.NgranBands.BAND_20;
+ public static final int BAND_25 = android.hardware.radio.V1_5.NgranBands.BAND_25;
+ public static final int BAND_28 = android.hardware.radio.V1_5.NgranBands.BAND_28;
+ public static final int BAND_29 = android.hardware.radio.V1_5.NgranBands.BAND_29;
+ public static final int BAND_30 = android.hardware.radio.V1_5.NgranBands.BAND_30;
+ public static final int BAND_34 = android.hardware.radio.V1_5.NgranBands.BAND_34;
+ public static final int BAND_38 = android.hardware.radio.V1_5.NgranBands.BAND_38;
+ public static final int BAND_39 = android.hardware.radio.V1_5.NgranBands.BAND_39;
+ public static final int BAND_40 = android.hardware.radio.V1_5.NgranBands.BAND_40;
+ public static final int BAND_41 = android.hardware.radio.V1_5.NgranBands.BAND_41;
+ public static final int BAND_48 = android.hardware.radio.V1_5.NgranBands.BAND_48;
+ public static final int BAND_50 = android.hardware.radio.V1_5.NgranBands.BAND_50;
+ public static final int BAND_51 = android.hardware.radio.V1_5.NgranBands.BAND_51;
+ public static final int BAND_65 = android.hardware.radio.V1_5.NgranBands.BAND_65;
+ public static final int BAND_66 = android.hardware.radio.V1_5.NgranBands.BAND_66;
+ public static final int BAND_70 = android.hardware.radio.V1_5.NgranBands.BAND_70;
+ public static final int BAND_71 = android.hardware.radio.V1_5.NgranBands.BAND_71;
+ public static final int BAND_74 = android.hardware.radio.V1_5.NgranBands.BAND_74;
+ public static final int BAND_75 = android.hardware.radio.V1_5.NgranBands.BAND_75;
+ public static final int BAND_76 = android.hardware.radio.V1_5.NgranBands.BAND_76;
+ public static final int BAND_77 = android.hardware.radio.V1_5.NgranBands.BAND_77;
+ public static final int BAND_78 = android.hardware.radio.V1_5.NgranBands.BAND_78;
+ public static final int BAND_79 = android.hardware.radio.V1_5.NgranBands.BAND_79;
+ public static final int BAND_80 = android.hardware.radio.V1_5.NgranBands.BAND_80;
+ public static final int BAND_81 = android.hardware.radio.V1_5.NgranBands.BAND_81;
+ public static final int BAND_82 = android.hardware.radio.V1_5.NgranBands.BAND_82;
+ public static final int BAND_83 = android.hardware.radio.V1_5.NgranBands.BAND_83;
+ public static final int BAND_84 = android.hardware.radio.V1_5.NgranBands.BAND_84;
+ public static final int BAND_86 = android.hardware.radio.V1_5.NgranBands.BAND_86;
+ public static final int BAND_90 = android.hardware.radio.V1_5.NgranBands.BAND_90;
/** FR2 bands */
- public static final int BAND_257 = 257;
- public static final int BAND_258 = 258;
- public static final int BAND_260 = 260;
- public static final int BAND_261 = 261;
+ public static final int BAND_257 = android.hardware.radio.V1_5.NgranBands.BAND_257;
+ public static final int BAND_258 = android.hardware.radio.V1_5.NgranBands.BAND_258;
+ public static final int BAND_260 = android.hardware.radio.V1_5.NgranBands.BAND_260;
+ public static final int BAND_261 = android.hardware.radio.V1_5.NgranBands.BAND_261;
/**
* NR Bands
diff --git a/telephony/java/android/telephony/Annotation.java b/telephony/java/android/telephony/Annotation.java
index 9ae86c8..dcd4eb5 100644
--- a/telephony/java/android/telephony/Annotation.java
+++ b/telephony/java/android/telephony/Annotation.java
@@ -1,7 +1,6 @@
package android.telephony;
import android.annotation.IntDef;
-import android.provider.Telephony;
import android.telecom.Connection;
import android.telephony.data.ApnSetting;
@@ -653,15 +652,6 @@
@Retention(RetentionPolicy.SOURCE)
public @interface UiccAppType{}
- /** @hide */
- @IntDef({
- Telephony.Carriers.SKIP_464XLAT_DEFAULT,
- Telephony.Carriers.SKIP_464XLAT_DISABLE,
- Telephony.Carriers.SKIP_464XLAT_ENABLE,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Skip464XlatStatus {}
-
/**
* Override network type
*/
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index c5c08c2..e2112a5 100755
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -1568,6 +1568,7 @@
/**
* The string is used to compare with operator name.
* If it matches the pattern then show specific data icon.
+ * @hide
*/
public static final String KEY_SHOW_CARRIER_DATA_ICON_PATTERN_STRING =
"show_carrier_data_icon_pattern_string";
@@ -2381,17 +2382,16 @@
* <p> If a measure is not set, signal criteria reporting from modem will not be triggered and
* not be used for calculating signal level. If multiple measures are set bit, the parameter
* whose value is smallest is used to indicate the signal level.
+ * <UL>
+ * <LI>RSRP = 1 << 0</LI>
+ * <LI>RSRQ = 1 << 1</LI>
+ * <LI>RSSNR = 1 << 2</LI>
+ * </UL>
+ * <p> The value of this key must be bitwise OR of {@link CellSignalStrengthLte#USE_RSRP},
+ * {@link CellSignalStrengthLte#USE_RSRQ}, {@link CellSignalStrengthLte#USE_RSSNR}.
*
- * RSRP = 1 << 0,
- * RSRQ = 1 << 1,
- * RSSNR = 1 << 2,
- *
- * The value of this key must be bitwise OR of {@link CellSignalStrengthLte#USE_RSRP},
- * {@link CellSignalStrengthLte#USE_RSRQ}, {@link CellSignalStrengthLte#USE_RSSNR}.
- *
- * For example, if both RSRP and RSRQ are used, the value of key is 3 (1 << 0 | 1 << 1).
- * If the key is invalid or not configured, a default value (RSRP = 1 << 0)
- * will apply.
+ * <p> For example, if both RSRP and RSRQ are used, the value of key is 3 (1 << 0 | 1 << 1).
+ * If the key is invalid or not configured, a default value (RSRP = 1 << 0) will apply.
*
* @hide
*/
@@ -2400,16 +2400,18 @@
/**
* List of 4 customized 5G SS reference signal received power (SSRSRP) thresholds.
- *
+ * <p>
* Reference: 3GPP TS 38.215
- *
+ * <p>
* 4 threshold integers must be within the boundaries [-140 dB, -44 dB], and the levels are:
- * "NONE: [-140, threshold1]"
- * "POOR: (threshold1, threshold2]"
- * "MODERATE: (threshold2, threshold3]"
- * "GOOD: (threshold3, threshold4]"
- * "EXCELLENT: (threshold4, -44]"
- *
+ * <UL>
+ * <LI>"NONE: [-140, threshold1]"</LI>
+ * <LI>"POOR: (threshold1, threshold2]"</LI>
+ * <LI>"MODERATE: (threshold2, threshold3]"</LI>
+ * <LI>"GOOD: (threshold3, threshold4]"</LI>
+ * <LI>"EXCELLENT: (threshold4, -44]"</LI>
+ * </UL>
+ * <p>
* This key is considered invalid if the format is violated. If the key is invalid or
* not configured, a default value set will apply.
*/
@@ -2418,16 +2420,18 @@
/**
* List of 4 customized 5G SS reference signal received quality (SSRSRQ) thresholds.
- *
+ * <p>
* Reference: 3GPP TS 38.215
- *
+ * <p>
* 4 threshold integers must be within the boundaries [-20 dB, -3 dB], and the levels are:
- * "NONE: [-20, threshold1]"
- * "POOR: (threshold1, threshold2]"
- * "MODERATE: (threshold2, threshold3]"
- * "GOOD: (threshold3, threshold4]"
- * "EXCELLENT: (threshold4, -3]"
- *
+ * <UL>
+ * <LI>"NONE: [-20, threshold1]"</LI>
+ * <LI>"POOR: (threshold1, threshold2]"</LI>
+ * <LI>"MODERATE: (threshold2, threshold3]"</LI>
+ * <LI>"GOOD: (threshold3, threshold4]"</LI>
+ * <LI>"EXCELLENT: (threshold4, -3]"</LI>
+ * </UL>
+ * <p>
* This key is considered invalid if the format is violated. If the key is invalid or
* not configured, a default value set will apply.
*/
@@ -2436,17 +2440,19 @@
/**
* List of 4 customized 5G SS signal-to-noise and interference ratio (SSSINR) thresholds.
- *
+ * <p>
* Reference: 3GPP TS 38.215,
* 3GPP TS 38.133 10.1.16.1
- *
+ * <p>
* 4 threshold integers must be within the boundaries [-23 dB, 40 dB], and the levels are:
- * "NONE: [-23, threshold1]"
- * "POOR: (threshold1, threshold2]"
- * "MODERATE: (threshold2, threshold3]"
- * "GOOD: (threshold3, threshold4]"
- * "EXCELLENT: (threshold4, 40]"
- *
+ * <UL>
+ * <LI>"NONE: [-23, threshold1]"</LI>
+ * <LI>"POOR: (threshold1, threshold2]"</LI>
+ * <LI>"MODERATE: (threshold2, threshold3]"</LI>
+ * <LI>"GOOD: (threshold3, threshold4]"</LI>
+ * <LI>"EXCELLENT: (threshold4, 40]"</LI>
+ * </UL>
+ * <p>
* This key is considered invalid if the format is violated. If the key is invalid or
* not configured, a default value set will apply.
*/
@@ -2461,19 +2467,19 @@
* <p> If a measure is not set, signal criteria reporting from modem will not be triggered and
* not be used for calculating signal level. If multiple measures are set bit, the parameter
* whose value is smallest is used to indicate the signal level.
- *
- * SSRSRP = 1 << 0,
- * SSRSRQ = 1 << 1,
- * SSSINR = 1 << 2,
- *
+ * <UL>
+ * <LI>SSRSRP = 1 << 0</LI>
+ * <LI>SSRSRQ = 1 << 1</LI>
+ * <LI>SSSINR = 1 << 2</LI>
+ * </UL>
* The value of this key must be bitwise OR of {@link CellSignalStrengthNr#USE_SSRSRP},
* {@link CellSignalStrengthNr#USE_SSRSRQ}, {@link CellSignalStrengthNr#USE_SSSINR}.
*
- * For example, if both SSRSRP and SSSINR are used, the value of key is 5 (1 << 0 | 1 << 2).
+ * <p> For example, if both SSRSRP and SSSINR are used, the value of key is 5 (1 << 0 | 1 << 2).
* If the key is invalid or not configured, a default value (SSRSRP = 1 << 0) will apply.
*
- * Reference: 3GPP TS 38.215,
- * 3GPP TS 38.133 10.1.16.1
+ * <p> Reference: 3GPP TS 38.215,
+ * 3GPP TS 38.133 10.1.16.1
*
* @hide
*/
@@ -2978,9 +2984,9 @@
* UE wants to display 5G_Plus icon for scenario#1, and 5G icon for scenario#2; otherwise not
* define.
* The configuration is: "connected_mmwave:5G_Plus,connected:5G"
+ * @hide
*/
- public static final String KEY_5G_ICON_CONFIGURATION_STRING =
- "5g_icon_configuration_string";
+ public static final String KEY_5G_ICON_CONFIGURATION_STRING = "5g_icon_configuration_string";
/**
* Timeout in seconds for displaying 5G icon, default value is 0 which means the timer is
@@ -2992,12 +2998,14 @@
*
* If 5G is reacquired during this timer, the timer is canceled and restarted when 5G is next
* lost. Allows us to momentarily lose 5G without blinking the icon.
+ * @hide
*/
public static final String KEY_5G_ICON_DISPLAY_GRACE_PERIOD_SEC_INT =
"5g_icon_display_grace_period_sec_int";
/**
* Controls time in milliseconds until DcTracker reevaluates 5G connection state.
+ * @hide
*/
public static final String KEY_5G_WATCHDOG_TIME_MS_LONG = "5g_watchdog_time_long";
@@ -3527,6 +3535,15 @@
"support_wps_over_ims_bool";
/**
+ * The two digital number pattern of MMI code which is defined by carrier.
+ * If the dial number matches this pattern, it will be dialed out normally not USSD.
+ *
+ * @hide
+ */
+ public static final String KEY_MMI_TWO_DIGIT_NUMBER_PATTERN_STRING_ARRAY =
+ "mmi_two_digit_number_pattern_string_array";
+
+ /**
* Holds the list of carrier certificate hashes.
* Note that each carrier has its own certificates.
*/
@@ -4021,7 +4038,8 @@
sDefaults.putBoolean(KEY_USE_CALLER_ID_USSD_BOOL, false);
sDefaults.putInt(KEY_CALL_WAITING_SERVICE_CLASS_INT, 1 /* SERVICE_CLASS_VOICE */);
sDefaults.putString(KEY_5G_ICON_CONFIGURATION_STRING,
- "connected_mmwave:5G,connected:5G");
+ "connected_mmwave:5G,connected:5G,not_restricted_rrc_idle:5G,"
+ + "not_restricted_rrc_con:5G");
sDefaults.putInt(KEY_5G_ICON_DISPLAY_GRACE_PERIOD_SEC_INT, 0);
/* Default value is 1 hour. */
sDefaults.putLong(KEY_5G_WATCHDOG_TIME_MS_LONG, 3600000);
@@ -4082,6 +4100,7 @@
new int[] {4 /* BUSY */});
sDefaults.putBoolean(KEY_PREVENT_CLIR_ACTIVATION_AND_DEACTIVATION_CODE_BOOL, false);
sDefaults.putLong(KEY_DATA_SWITCH_VALIDATION_TIMEOUT_LONG, 2000);
+ sDefaults.putStringArray(KEY_MMI_TWO_DIGIT_NUMBER_PATTERN_STRING_ARRAY, new String[0]);
sDefaults.putInt(KEY_PARAMETERS_USED_FOR_LTE_SIGNAL_BAR_INT,
CellSignalStrengthLte.USE_RSRP);
// Default wifi configurations.
@@ -4143,7 +4162,7 @@
return null;
}
return loader.getConfigForSubIdWithFeature(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
Rlog.e(TAG, "Error getting config for subId " + subId + ": "
+ ex.toString());
diff --git a/telephony/java/android/telephony/CdmaEriInformation.java b/telephony/java/android/telephony/CdmaEriInformation.java
index 1cd9d30..fd0b905 100644
--- a/telephony/java/android/telephony/CdmaEriInformation.java
+++ b/telephony/java/android/telephony/CdmaEriInformation.java
@@ -40,7 +40,6 @@
*
* @hide
*/
-@SystemApi
public final class CdmaEriInformation implements Parcelable {
/** @hide */
@Retention(RetentionPolicy.SOURCE)
diff --git a/telephony/java/android/telephony/DataSpecificRegistrationInfo.java b/telephony/java/android/telephony/DataSpecificRegistrationInfo.java
index 270eafe..c667165 100644
--- a/telephony/java/android/telephony/DataSpecificRegistrationInfo.java
+++ b/telephony/java/android/telephony/DataSpecificRegistrationInfo.java
@@ -208,7 +208,6 @@
* @return {@code true} if using carrier aggregation.
* @hide
*/
- @SystemApi
public boolean isUsingCarrierAggregation() {
return mIsUsingCarrierAggregation;
}
diff --git a/telephony/java/android/telephony/ImsManager.java b/telephony/java/android/telephony/ImsManager.java
index fe75266..3984bd7 100644
--- a/telephony/java/android/telephony/ImsManager.java
+++ b/telephony/java/android/telephony/ImsManager.java
@@ -19,9 +19,7 @@
import android.annotation.NonNull;
import android.annotation.SdkConstant;
import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
import android.annotation.SystemService;
-import android.annotation.TestApi;
import android.content.Context;
import android.telephony.SubscriptionManager;
@@ -34,8 +32,9 @@
private Context mContext;
/**
- * <p>Broadcast Action: Indicates that an IMS operation was rejected by the network due to it
- * not being authorized on the network.
+ * <p>Broadcast Action: Indicates that a previously allowed IMS operation was rejected by the
+ * network due to the network returning a "forbidden" response. This may be due to a
+ * provisioning change from the network.
* May include the {@link SubscriptionManager#EXTRA_SUBSCRIPTION_INDEX} extra to also specify
* which subscription the operation was rejected for.
* <p class="note">
@@ -43,8 +42,6 @@
* issues.
* @hide
*/
- @SystemApi
- @TestApi
// Moved from TelephonyIntents, need to keep backwards compatibility with OEM apps that have
// this value hard-coded in BroadcastReceiver.
@SuppressLint("ActionValue")
diff --git a/telephony/java/android/telephony/NetworkRegistrationInfo.java b/telephony/java/android/telephony/NetworkRegistrationInfo.java
index c74e17f..4940cb2 100644
--- a/telephony/java/android/telephony/NetworkRegistrationInfo.java
+++ b/telephony/java/android/telephony/NetworkRegistrationInfo.java
@@ -297,7 +297,7 @@
mDataSpecificInfo = new DataSpecificRegistrationInfo(
maxDataCalls, isDcNrRestricted, isNrAvailable, isEndcAvailable, lteVopsSupportInfo,
isUsingCarrierAggregation);
- updateNrState(mDataSpecificInfo);
+ updateNrState();
}
private NetworkRegistrationInfo(Parcel source) {
@@ -367,6 +367,7 @@
* Get the 5G NR connection state.
*
* @return the 5G NR connection state.
+ * @hide
*/
public @NRState int getNrState() {
return mNrState;
@@ -685,12 +686,12 @@
* DCNR is not restricted and NR is supported by the selected PLMN. Otherwise the use of 5G
* NR is restricted.
*
- * @param state data specific registration state contains the 5G NR indicators.
+ * @hide
*/
- private void updateNrState(DataSpecificRegistrationInfo state) {
+ public void updateNrState() {
mNrState = NR_STATE_NONE;
- if (state.isEnDcAvailable) {
- if (!state.isDcNrRestricted && state.isNrAvailable) {
+ if (mDataSpecificInfo.isEnDcAvailable) {
+ if (!mDataSpecificInfo.isDcNrRestricted && mDataSpecificInfo.isNrAvailable) {
mNrState = NR_STATE_NOT_RESTRICTED;
} else {
mNrState = NR_STATE_RESTRICTED;
diff --git a/telephony/java/android/telephony/NetworkService.java b/telephony/java/android/telephony/NetworkService.java
index 87d94bfd..c75de42 100644
--- a/telephony/java/android/telephony/NetworkService.java
+++ b/telephony/java/android/telephony/NetworkService.java
@@ -234,6 +234,9 @@
* this method to facilitate the creation of {@link NetworkServiceProvider} instances. The system
* will call this method after binding the network service for each active SIM slot id.
*
+ * This methead is guaranteed to be invoked in {@link NetworkService}'s internal handler thread
+ * whose looper can be retrieved with {@link Looper.myLooper()} when override this method.
+ *
* @param slotIndex SIM slot id the network service associated with.
* @return Network service object. Null if failed to create the provider (e.g. invalid slot
* index)
diff --git a/telephony/java/android/telephony/PinResult.java b/telephony/java/android/telephony/PinResult.java
index c14bd91..98d6448 100644
--- a/telephony/java/android/telephony/PinResult.java
+++ b/telephony/java/android/telephony/PinResult.java
@@ -19,7 +19,6 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.SystemApi;
import android.os.Parcel;
import android.os.Parcelable;
@@ -32,7 +31,6 @@
*
* @hide
*/
-@SystemApi
public final class PinResult implements Parcelable {
/** @hide */
@IntDef({
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index 9b1baef..deba551 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -580,7 +580,6 @@
*
* @hide
*/
- @SystemApi
public @RegState int getDataRegistrationState() {
return getDataRegState();
}
@@ -689,8 +688,9 @@
* @return true if registration indicates roaming, false otherwise
* @hide
*/
- @SystemApi
public boolean getDataRoamingFromRegistration() {
+ // TODO: all callers should refactor to get roaming state directly from modem
+ // this should not be exposed as a public API
return mIsDataRoamingFromRegistration;
}
@@ -1422,7 +1422,6 @@
* @return the frequency range of 5G NR.
* @hide
*/
- @SystemApi
public @FrequencyRange int getNrFrequencyRange() {
return mNrFrequencyRange;
}
@@ -1651,7 +1650,6 @@
* @return Current data network type
* @hide
*/
- @SystemApi
@TestApi
public @NetworkType int getDataNetworkType() {
final NetworkRegistrationInfo iwlanRegInfo = getNetworkRegistrationInfo(
@@ -2026,6 +2024,7 @@
* The long format can be up to 16 characters long.
*
* @return long raw name of operator, null if unregistered or unknown
+ * @hide
*/
@Nullable
public String getOperatorAlphaLongRaw() {
@@ -2045,6 +2044,7 @@
* The short format can be up to 8 characters long.
*
* @return short raw name of operator, null if unregistered or unknown
+ * @hide
*/
@Nullable
public String getOperatorAlphaShortRaw() {
diff --git a/telephony/java/android/telephony/SmsManager.java b/telephony/java/android/telephony/SmsManager.java
index 8479db6..f6a305f 100644
--- a/telephony/java/android/telephony/SmsManager.java
+++ b/telephony/java/android/telephony/SmsManager.java
@@ -975,11 +975,7 @@
*
* @param packageName serves as the default package name if the package name that is
* associated with the user id is null.
- *
- * @hide
*/
- @SystemApi
- @TestApi
public void sendMultipartTextMessage(
@NonNull String destinationAddress, @Nullable String scAddress,
@NonNull List<String> parts, @Nullable List<PendingIntent> sentIntents,
@@ -2939,7 +2935,7 @@
/**
* Gets the premium SMS permission for the specified package. If the package has never
- * been seen before, the default {@link SmsManager#PREMIUM_SMS_PERMISSION_ASK_USER}
+ * been seen before, the default {@link SmsManager#PREMIUM_SMS_CONSENT_UNKNOWN}
* will be returned.
* @param packageName the name of the package to query permission
* @return one of {@link SmsManager#PREMIUM_SMS_CONSENT_UNKNOWN},
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 8ac9023b..01a40f5 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -1144,7 +1144,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
subInfo = iSub.getActiveSubscriptionInfo(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1178,7 +1178,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
result = iSub.getActiveSubscriptionInfoForIccId(iccId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1212,7 +1212,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
result = iSub.getActiveSubscriptionInfoForSimSlotIndex(slotIndex,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1236,7 +1236,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
result = iSub.getAllSubInfoList(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1300,8 +1300,13 @@
* both active and hidden SubscriptionInfos.
*
*/
- public @Nullable List<SubscriptionInfo> getActiveAndHiddenSubscriptionInfoList() {
- return getActiveSubscriptionInfoList(/* userVisibleonly */false);
+ public @NonNull List<SubscriptionInfo> getCompleteActiveSubscriptionInfoList() {
+ List<SubscriptionInfo> completeList = getActiveSubscriptionInfoList(
+ /* userVisibleonly */false);
+ if (completeList == null) {
+ completeList = new ArrayList<>();
+ }
+ return completeList;
}
/**
@@ -1317,7 +1322,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
activeList = iSub.getActiveSubscriptionInfoList(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1368,7 +1373,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
result = iSub.getAvailableSubscriptionInfoList(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1486,7 +1491,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
result = iSub.getAllSubInfoCount(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -1515,7 +1520,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
result = iSub.getActiveSubInfoCount(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -2270,7 +2275,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
resultValue = iSub.getSubscriptionProperty(subId, propKey,
- context.getOpPackageName(), context.getFeatureId());
+ context.getOpPackageName(), context.getAttributionTag());
}
} catch (RemoteException ex) {
// ignore it
@@ -2434,7 +2439,7 @@
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
return iSub.isActiveSubId(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
}
@@ -2697,13 +2702,14 @@
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public @NonNull List<SubscriptionInfo> getOpportunisticSubscriptions() {
String contextPkg = mContext != null ? mContext.getOpPackageName() : "<unknown>";
- String contextFeature = mContext != null ? mContext.getFeatureId() : null;
+ String contextAttributionTag = mContext != null ? mContext.getAttributionTag() : null;
List<SubscriptionInfo> subInfoList = null;
try {
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
- subInfoList = iSub.getOpportunisticSubscriptions(contextPkg, contextFeature);
+ subInfoList = iSub.getOpportunisticSubscriptions(contextPkg,
+ contextAttributionTag);
}
} catch (RemoteException ex) {
// ignore it
@@ -2942,7 +2948,7 @@
public @NonNull List<SubscriptionInfo> getSubscriptionsInGroup(@NonNull ParcelUuid groupUuid) {
Preconditions.checkNotNull(groupUuid, "groupUuid can't be null");
String contextPkg = mContext != null ? mContext.getOpPackageName() : "<unknown>";
- String contextFeature = mContext != null ? mContext.getFeatureId() : null;
+ String contextAttributionTag = mContext != null ? mContext.getAttributionTag() : null;
if (VDBG) {
logd("[getSubscriptionsInGroup]+ groupUuid:" + groupUuid);
}
@@ -2951,7 +2957,8 @@
try {
ISub iSub = TelephonyManager.getSubscriptionService();
if (iSub != null) {
- result = iSub.getSubscriptionsInGroup(groupUuid, contextPkg, contextFeature);
+ result = iSub.getSubscriptionsInGroup(groupUuid, contextPkg,
+ contextAttributionTag);
} else {
if (!isSystemProcess()) {
throw new IllegalStateException("telephony service is null.");
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index 40def40..e559c2a 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -54,6 +54,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
import android.os.PersistableBundle;
import android.os.Process;
import android.os.RemoteException;
@@ -344,10 +345,10 @@
mSubId = subId;
Context appContext = context.getApplicationContext();
if (appContext != null) {
- if (Objects.equals(context.getFeatureId(), appContext.getFeatureId())) {
+ if (Objects.equals(context.getAttributionTag(), appContext.getAttributionTag())) {
mContext = appContext;
} else {
- mContext = appContext.createFeatureContext(context.getFeatureId());
+ mContext = appContext.createAttributionContext(context.getAttributionTag());
}
} else {
mContext = context;
@@ -392,12 +393,12 @@
}
}
- private String getFeatureId() {
+ private String getAttributionTag() {
// For legacy reasons the TelephonyManager has API for getting
// a static instance with no context set preventing us from
- // getting the feature Id.
+ // getting the attribution tag.
if (mContext != null) {
- return mContext.getFeatureId();
+ return mContext.getAttributionTag();
}
return null;
}
@@ -1564,6 +1565,7 @@
* @hide
*/
@SystemApi
+ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
@SuppressLint("ActionValue")
public static final String ACTION_EMERGENCY_CALLBACK_MODE_CHANGED =
"android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED";
@@ -1785,6 +1787,7 @@
* @hide
*/
@SystemApi
+ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
@SuppressLint("ActionValue")
public static final String ACTION_EMERGENCY_CALL_STATE_CHANGED =
"android.intent.action.EMERGENCY_CALL_STATE_CHANGED";
@@ -1895,7 +1898,7 @@
try {
return telephony.getDeviceSoftwareVersionForSlot(slotIndex, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -1937,7 +1940,7 @@
if (telephony == null)
return null;
return telephony.getDeviceIdWithFeature(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -1982,7 +1985,7 @@
if (info == null)
return null;
return info.getDeviceIdForPhone(slotIndex, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -2040,7 +2043,7 @@
if (telephony == null) return null;
try {
- return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getFeatureId());
+ return telephony.getImeiForSlot(slotIndex, getOpPackageName(), getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -2134,7 +2137,8 @@
if (telephony == null) return null;
try {
- String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(), getFeatureId());
+ String meid = telephony.getMeidForSlot(slotIndex, getOpPackageName(),
+ getAttributionTag());
if (TextUtils.isEmpty(meid)) {
Log.d(TAG, "getMeid: return null because MEID is not available");
return null;
@@ -2236,7 +2240,7 @@
if (info == null)
return null;
String nai = info.getNaiForSubscriber(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Rlog.v(TAG, "Nai = " + nai);
}
@@ -2270,7 +2274,7 @@
}
CellIdentity cellIdentity = telephony.getCellLocation(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
CellLocation cl = cellIdentity.asCellLocation();
if (cl == null || cl.isEmpty()) {
Rlog.d(TAG, "getCellLocation returning null because CellLocation is empty or"
@@ -2354,7 +2358,7 @@
if (telephony == null)
return null;
return telephony.getNeighboringCellInfo(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -2370,7 +2374,12 @@
public static final int PHONE_TYPE_CDMA = PhoneConstants.PHONE_TYPE_CDMA;
/** Phone is via SIP. */
public static final int PHONE_TYPE_SIP = PhoneConstants.PHONE_TYPE_SIP;
- /** Phone is via IMS. */
+
+ /**
+ * Phone is via IMS.
+ *
+ * @hide
+ */
public static final int PHONE_TYPE_IMS = PhoneConstants.PHONE_TYPE_IMS;
/**
@@ -2378,7 +2387,6 @@
*
* @hide
*/
- @SystemApi
public static final int PHONE_TYPE_THIRD_PARTY = PhoneConstants.PHONE_TYPE_THIRD_PARTY;
/**
@@ -2956,7 +2964,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getNetworkTypeForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} else {
// This can happen when the ITelephony interface is not up yet.
return NETWORK_TYPE_UNKNOWN;
@@ -3021,7 +3029,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getDataNetworkTypeForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} else {
// This can happen when the ITelephony interface is not up yet.
return NETWORK_TYPE_UNKNOWN;
@@ -3058,7 +3066,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getVoiceNetworkTypeForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} else {
// This can happen when the ITelephony interface is not up yet.
return NETWORK_TYPE_UNKNOWN;
@@ -3762,29 +3770,6 @@
}
/**
- * Returns the ISO-3166 country code equivalent for the SIM provider's country code
- * of the default subscription
- * <p>
- * The ISO-3166 country code is provided in lowercase 2 character format.
- * @return the lowercase 2 character ISO-3166 country code, or empty string is not available.
- * <p>
- * Note: This API is introduced to unblock mainlining work as the following APIs in
- * Linkify.java invokes getSimCountryIso() without a context. TODO(Bug 144576376): remove
- * this API once the following APIs are redesigned to access telephonymanager with a context.
- *
- * {@link Linkify#addLinks(@NonNull Spannable text, @LinkifyMask int mask)}
- * {@link Linkify#addLinks(@NonNull Spannable text, @LinkifyMask int mask,
- @Nullable Function<String, URLSpan> urlSpanFactory)}
- *
- * @hide
- */
- @SystemApi
- @NonNull
- public static String getDefaultSimCountryIso() {
- return getSimCountryIso(SubscriptionManager.getDefaultSubscriptionId());
- }
-
- /**
* Returns the ISO country code equivalent for the SIM provider's country code.
*
* @param subId for which SimCountryIso is returned
@@ -3867,7 +3852,7 @@
if (info == null)
return null;
return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -3911,7 +3896,7 @@
if (telephony == null)
return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
return telephony.getLteOnCdmaModeForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
// Assume no ICC card if remote exception which shouldn't happen
return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
@@ -4140,7 +4125,7 @@
if (info == null)
return null;
return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4308,7 +4293,7 @@
if (info == null)
return null;
return info.getGroupIdLevel1ForSubscriber(getSubId(), mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4332,7 +4317,7 @@
if (info == null)
return null;
return info.getGroupIdLevel1ForSubscriber(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4383,7 +4368,7 @@
ITelephony telephony = getITelephony();
if (telephony != null)
number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
} catch (NullPointerException ex) {
}
@@ -4395,7 +4380,7 @@
if (info == null)
return null;
return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4474,7 +4459,7 @@
ITelephony telephony = getITelephony();
if (telephony != null)
alphaTag = telephony.getLine1AlphaTagForDisplay(subId,
- getOpPackageName(), getFeatureId());
+ getOpPackageName(), getAttributionTag());
} catch (RemoteException ex) {
} catch (NullPointerException ex) {
}
@@ -4486,7 +4471,7 @@
if (info == null)
return null;
return info.getLine1AlphaTagForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4516,7 +4501,7 @@
ITelephony telephony = getITelephony();
if (telephony != null)
return telephony.getMergedSubscriberIds(getSubId(), getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
} catch (NullPointerException ex) {
}
@@ -4573,7 +4558,7 @@
IPhoneSubInfo info = getSubscriberInfoService();
if (info == null)
return null;
- return info.getMsisdnForSubscriber(subId, getOpPackageName(), getFeatureId());
+ return info.getMsisdnForSubscriber(subId, getOpPackageName(), getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4608,7 +4593,7 @@
if (info == null)
return null;
return info.getVoiceMailNumberForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -4733,7 +4718,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getVisualVoicemailPackageName(mContext.getOpPackageName(),
- getFeatureId(), getSubId());
+ getAttributionTag(), getSubId());
}
} catch (RemoteException ex) {
} catch (NullPointerException ex) {
@@ -5170,7 +5155,7 @@
if (telephony == null)
return 0;
return telephony.getVoiceMessageCountForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
return 0;
} catch (NullPointerException ex) {
@@ -5207,7 +5192,7 @@
if (info == null)
return null;
return info.getVoiceMailAlphaTagForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -5297,8 +5282,8 @@
* not present or not loaded
* @hide
*/
+ @UnsupportedAppUsage
@Nullable
- @SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public String[] getIsimImpu() {
try {
@@ -5590,7 +5575,7 @@
(TelephonyRegistryManager)
mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE);
if (telephonyRegistry != null) {
- telephonyRegistry.listenForSubscriber(mSubId, getOpPackageName(), getFeatureId(),
+ telephonyRegistry.listenForSubscriber(mSubId, getOpPackageName(), getAttributionTag(),
listener, events, notifyNow);
} else {
Rlog.w(TAG, "telephony registry not ready.");
@@ -5605,7 +5590,6 @@
* @hide
*/
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
- @SystemApi
@NonNull
public CdmaEriInformation getCdmaEriInformation() {
return new CdmaEriInformation(
@@ -5624,7 +5608,7 @@
if (telephony == null)
return -1;
return telephony.getCdmaEriIconIndexForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
// the phone process is restarting.
return -1;
@@ -5648,7 +5632,7 @@
if (telephony == null)
return -1;
return telephony.getCdmaEriIconModeForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
// the phone process is restarting.
return -1;
@@ -5680,7 +5664,7 @@
if (telephony == null)
return null;
return telephony.getCdmaEriTextForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
// the phone process is restarting.
return null;
@@ -5772,7 +5756,7 @@
ITelephony telephony = getITelephony();
if (telephony == null)
return null;
- return telephony.getAllCellInfo(getOpPackageName(), getFeatureId());
+ return telephony.getAllCellInfo(getOpPackageName(), getAttributionTag());
} catch (RemoteException ex) {
} catch (NullPointerException ex) {
}
@@ -5872,7 +5856,7 @@
Binder.restoreCallingIdentity(identity);
}
}
- }, getOpPackageName(), getFeatureId());
+ }, getOpPackageName(), getAttributionTag());
} catch (RemoteException ex) {
}
}
@@ -5923,7 +5907,7 @@
Binder.restoreCallingIdentity(identity);
}
}
- }, getOpPackageName(), getFeatureId(), workSource);
+ }, getOpPackageName(), getAttributionTag(), workSource);
} catch (RemoteException ex) {
}
}
@@ -7209,7 +7193,7 @@
if (telephony == null)
return null;
return telephony.getForbiddenPlmns(subId, appType, mContext.getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
@@ -7243,7 +7227,7 @@
ITelephony telephony = getITelephony();
if (telephony == null) return -1;
return telephony.setForbiddenPlmns(
- getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getFeatureId());
+ getSubId(), APPTYPE_USIM, fplmns, getOpPackageName(), getAttributionTag());
} catch (RemoteException ex) {
Rlog.e(TAG, "setForbiddenPlmns RemoteException: " + ex.getMessage());
} catch (NullPointerException ex) {
@@ -7264,7 +7248,7 @@
ITelephony telephony = getITelephony();
if (telephony == null)
return new String[0];
- return telephony.getPcscfAddress(apnType, getOpPackageName(), getFeatureId());
+ return telephony.getPcscfAddress(apnType, getOpPackageName(), getAttributionTag());
} catch (RemoteException e) {
return new String[0];
}
@@ -7837,7 +7821,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getCellNetworkScanResults(getSubId(), getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
}
} catch (RemoteException ex) {
Rlog.e(TAG, "getAvailableNetworks RemoteException", ex);
@@ -7892,7 +7876,7 @@
}
}
return mTelephonyScanManager.requestNetworkScan(getSubId(), request, executor, callback,
- getOpPackageName(), getFeatureId());
+ getOpPackageName(), getAttributionTag());
}
/**
@@ -8646,7 +8630,7 @@
try {
ITelephony telephony = getITelephony();
if (telephony != null)
- return telephony.isRadioOnWithFeature(getOpPackageName(), getFeatureId());
+ return telephony.isRadioOnWithFeature(getOpPackageName(), getAttributionTag());
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#isRadioOn", e);
}
@@ -8725,7 +8709,6 @@
*
* @hide
*/
- @SystemApi
@Nullable
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public PinResult supplyPinReportPinResult(@NonNull String pin) {
@@ -8750,7 +8733,6 @@
*
* @hide
*/
- @SystemApi
@Nullable
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public PinResult supplyPukReportPinResult(@NonNull String puk, @NonNull String pin) {
@@ -8942,7 +8924,10 @@
}
/**
- * Shut down all the live radios over all the slot index.
+ * Shut down all the live radios over all the slot indexes.
+ *
+ * <p>To know when the radio has completed powering off, use
+ * {@link PhoneStateListener#LISTEN_SERVICE_STATE LISTEN_SERVICE_STATE}.
*
* @hide
*/
@@ -8955,7 +8940,8 @@
telephony.shutdownMobileRadios();
}
} catch (RemoteException e) {
- Log.e(TAG, "Error calling ITelephony#shutdownMobileRadios", e);
+ Log.e(TAG, "Error calling ITelephony#shutdownAllRadios", e);
+ e.rethrowAsRuntimeException();
}
}
@@ -8974,7 +8960,8 @@
return telephony.needMobileRadioShutdown();
}
} catch (RemoteException e) {
- Log.e(TAG, "Error calling ITelephony#needMobileRadioShutdown", e);
+ Log.e(TAG, "Error calling ITelephony#isAnyRadioPoweredOn", e);
+ e.rethrowAsRuntimeException();
}
return false;
}
@@ -9017,7 +9004,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getRadioPowerState(getSlotIndex(), mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
// This could happen if binder process crashes.
@@ -9204,7 +9191,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public @CdmaRoamingMode int getCdmaRoamingMode() {
int mode = CDMA_ROAMING_MODE_RADIO_DEFAULT;
@@ -9233,7 +9219,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public boolean setCdmaRoamingMode(@CdmaRoamingMode int mode) {
try {
@@ -9259,19 +9244,16 @@
/** Used for CDMA subscription mode, it'll be UNKNOWN if there is no Subscription source.
* @hide
*/
- @SystemApi
public static final int CDMA_SUBSCRIPTION_UNKNOWN = -1;
/** Used for CDMA subscription mode: RUIM/SIM (default)
* @hide
*/
- @SystemApi
public static final int CDMA_SUBSCRIPTION_RUIM_SIM = 0;
/** Used for CDMA subscription mode: NV -> non-volatile memory
* @hide
*/
- @SystemApi
public static final int CDMA_SUBSCRIPTION_NV = 1;
/** @hide */
@@ -9290,7 +9272,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public boolean setCdmaSubscriptionMode(@CdmaSubscription int mode) {
try {
@@ -9408,7 +9389,7 @@
try {
ITelephony telephony = getITelephony();
if (telephony != null)
- return telephony.isVideoCallingEnabled(getOpPackageName(), getFeatureId());
+ return telephony.isVideoCallingEnabled(getOpPackageName(), getAttributionTag());
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#isVideoCallingEnabled", e);
}
@@ -9425,7 +9406,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.canChangeDtmfToneLength(mSubId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#canChangeDtmfToneLength", e);
@@ -9444,7 +9425,7 @@
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
- return telephony.isWorldPhone(mSubId, getOpPackageName(), getFeatureId());
+ return telephony.isWorldPhone(mSubId, getOpPackageName(), getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#isWorldPhone", e);
@@ -9998,18 +9979,30 @@
}
/**
- * Gets the default Respond Via Message application
- * @param context context from the calling app
- * @param updateIfNeeded update the default app if there is no valid default app configured.
+ * Gets the default Respond Via Message application, updating the cache if there is no
+ * respond-via-message application currently configured.
* @return component name of the app and class to direct Respond Via Message intent to, or
* {@code null} if the functionality is not supported.
* @hide
*/
@SystemApi
@TestApi
- public static @Nullable ComponentName getDefaultRespondViaMessageApplication(
- @NonNull Context context, boolean updateIfNeeded) {
- return SmsApplication.getDefaultRespondViaMessageApplication(context, updateIfNeeded);
+ @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
+ public @Nullable ComponentName getAndUpdateDefaultRespondViaMessageApplication() {
+ return SmsApplication.getDefaultRespondViaMessageApplication(mContext, true);
+ }
+
+ /**
+ * Gets the default Respond Via Message application.
+ * @return component name of the app and class to direct Respond Via Message intent to, or
+ * {@code null} if the functionality is not supported.
+ * @hide
+ */
+ @SystemApi
+ @TestApi
+ @RequiresPermission(Manifest.permission.INTERACT_ACROSS_USERS)
+ public @Nullable ComponentName getDefaultRespondViaMessageApplication() {
+ return SmsApplication.getDefaultRespondViaMessageApplication(mContext, false);
}
/**
@@ -10172,7 +10165,8 @@
ITelephony service = getITelephony();
if (service != null) {
retval = service.getSubIdForPhoneAccountHandle(
- phoneAccountHandle, mContext.getOpPackageName(), mContext.getFeatureId());
+ phoneAccountHandle, mContext.getOpPackageName(),
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
Log.e(TAG, "getSubscriptionId RemoteException", ex);
@@ -10313,7 +10307,7 @@
ITelephony service = getITelephony();
if (service != null) {
return service.getServiceStateForSubscriber(subId, getOpPackageName(),
- getFeatureId());
+ getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#getServiceStateForSubscriber", e);
@@ -11034,7 +11028,8 @@
try {
ITelephony service = getITelephony();
if (service != null) {
- return service.getClientRequestStats(getOpPackageName(), getFeatureId(), subId);
+ return service.getClientRequestStats(getOpPackageName(), getAttributionTag(),
+ subId);
}
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelephony#getClientRequestStats", e);
@@ -11145,21 +11140,21 @@
}
/**
- * Checks whether cellular data connection is enabled in the device.
+ * Checks whether cellular data connection is allowed in the device.
*
- * Whether cellular data connection is enabled, meaning upon request whether will try to setup
- * metered data connection considering all factors below:
- * 1) User turned on data setting {@link #isDataEnabled}.
- * 2) Carrier allows data to be on.
- * 3) Network policy.
- * And possibly others.
- *
- * @return {@code true} if the overall data connection is capable; {@code false} if not.
+ * <p>Whether cellular data connection is allowed considers all factors below:
+ * <UL>
+ * <LI>User turned on data setting {@link #isDataEnabled}.</LI>
+ * <LI>Carrier allows data to be on.</LI>
+ * <LI>Network policy.</LI>
+ * <LI>And possibly others.</LI>
+ * </UL>
+ * @return {@code true} if the overall data connection is allowed; {@code false} if not.
* @hide
*/
@SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
- public boolean isDataConnectionEnabled() {
+ public boolean isDataConnectionAllowed() {
boolean retVal = false;
try {
int subId = getSubId(SubscriptionManager.getDefaultDataSubscriptionId());
@@ -11167,8 +11162,9 @@
if (telephony != null)
retVal = telephony.isDataEnabled(subId);
} catch (RemoteException e) {
- Log.e(TAG, "Error isDataConnectionEnabled", e);
+ Log.e(TAG, "Error isDataConnectionAllowed", e);
} catch (NullPointerException e) {
+ return false;
}
return retVal;
}
@@ -11319,7 +11315,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getNumberOfModemsWithSimultaneousDataConnections(
- getSubId(), getOpPackageName(), getFeatureId());
+ getSubId(), getOpPackageName(), getAttributionTag());
}
} catch (RemoteException ex) {
// This could happen if binder process crashes.
@@ -11648,11 +11644,9 @@
}
/**
- * Override the file path for testing OTA emergency number database in a file partition.
+ * Override the file path for OTA emergency number database in a file partition.
*
- * @param otaFilePath The test OTA emergency number database file path;
- * if "RESET", recover the original database file partition.
- * Format: <root file folder>@<file path>
+ * @param otaParcelFileDescriptor parcelable file descriptor for OTA emergency number database.
*
* <p> Requires permission:
* {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
@@ -11662,16 +11656,42 @@
@RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
@SystemApi
@TestApi
- public void updateTestOtaEmergencyNumberDbFilePath(@NonNull String otaFilePath) {
+ public void updateOtaEmergencyNumberDbFilePath(
+ @NonNull ParcelFileDescriptor otaParcelFileDescriptor) {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
- telephony.updateTestOtaEmergencyNumberDbFilePath(otaFilePath);
+ telephony.updateOtaEmergencyNumberDbFilePath(otaParcelFileDescriptor);
} else {
throw new IllegalStateException("telephony service is null.");
}
} catch (RemoteException ex) {
- Log.e(TAG, "notifyOtaEmergencyNumberDatabaseInstalled RemoteException", ex);
+ Log.e(TAG, "updateOtaEmergencyNumberDbFilePath RemoteException", ex);
+ ex.rethrowAsRuntimeException();
+ }
+ }
+
+ /**
+ * Reset the file path to default for OTA emergency number database in a file partition.
+ *
+ * <p> Requires permission:
+ * {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
+ *
+ * @hide
+ */
+ @RequiresPermission(android.Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
+ @SystemApi
+ @TestApi
+ public void resetOtaEmergencyNumberDbFilePath() {
+ try {
+ ITelephony telephony = getITelephony();
+ if (telephony != null) {
+ telephony.resetOtaEmergencyNumberDbFilePath();
+ } else {
+ throw new IllegalStateException("telephony service is null.");
+ }
+ } catch (RemoteException ex) {
+ Log.e(TAG, "resetOtaEmergencyNumberDbFilePath RemoteException", ex);
ex.rethrowAsRuntimeException();
}
}
@@ -11725,7 +11745,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.getEmergencyNumberList(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} else {
throw new IllegalStateException("telephony service is null.");
}
@@ -11780,7 +11800,7 @@
ITelephony telephony = getITelephony();
if (telephony != null) {
emergencyNumberList = telephony.getEmergencyNumberList(
- mContext.getOpPackageName(), mContext.getFeatureId());
+ mContext.getOpPackageName(), mContext.getAttributionTag());
if (emergencyNumberList != null) {
for (Integer subscriptionId : emergencyNumberList.keySet()) {
List<EmergencyNumber> numberList = emergencyNumberList.get(subscriptionId);
@@ -11873,7 +11893,7 @@
}
/**
- * A test API to return the emergency number db version.
+ * Returns the emergency number database version.
*
* <p>Requires Permission:
* {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE READ_PRIVILEGED_PHONE_STATE}
@@ -11882,6 +11902,7 @@
*/
@TestApi
@SystemApi
+ @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public int getEmergencyNumberDbVersion() {
try {
ITelephony telephony = getITelephony();
@@ -12088,13 +12109,13 @@
})
public int getPreferredOpportunisticDataSubscription() {
String packageName = mContext != null ? mContext.getOpPackageName() : "<unknown>";
- String featureId = mContext != null ? mContext.getFeatureId() : null;
+ String attributionTag = mContext != null ? mContext.getAttributionTag() : null;
int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
try {
IOns iOpportunisticNetworkService = getIOns();
if (iOpportunisticNetworkService != null) {
subId = iOpportunisticNetworkService.getPreferredDataSubscriptionId(
- packageName, featureId);
+ packageName, attributionTag);
}
} catch (RemoteException ex) {
Rlog.e(TAG, "getPreferredDataSubscriptionId RemoteException", ex);
@@ -12211,18 +12232,20 @@
/**
* It indicates whether modem is enabled or not per slot.
- * It's the corresponding status of {@link #enableModemForSlot}.
+ * It's the corresponding status of TelephonyManager.enableModemForSlot.
*
+ * <p>Requires Permission:
+ * READ_PRIVILEGED_PHONE_STATE or
+ * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
* @param slotIndex which slot it's checking.
- * @hide
*/
- @SystemApi
+ @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public boolean isModemEnabledForSlot(int slotIndex) {
try {
ITelephony telephony = getITelephony();
if (telephony != null) {
return telephony.isModemEnabledForSlot(slotIndex, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
}
} catch (RemoteException ex) {
Log.e(TAG, "enableModem RemoteException", ex);
@@ -12327,7 +12350,7 @@
try {
ITelephony service = getITelephony();
if (service != null) {
- return service.isMultiSimSupported(getOpPackageName(), getFeatureId());
+ return service.isMultiSimSupported(getOpPackageName(), getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "isMultiSimSupported RemoteException", e);
@@ -12379,7 +12402,7 @@
ITelephony service = getITelephony();
if (service != null) {
return service.doesSwitchMultiSimConfigTriggerReboot(getSubId(),
- getOpPackageName(), getFeatureId());
+ getOpPackageName(), getAttributionTag());
}
} catch (RemoteException e) {
Log.e(TAG, "doesSwitchMultiSimConfigTriggerReboot RemoteException", e);
@@ -12448,7 +12471,6 @@
* @throws {@link SecurityException} if the caller is not the system or phone process.
* @hide
*/
- @SystemApi
@TestApi
// TODO: add new permission tag indicating that this is system-only.
public @NonNull List<ApnSetting> getDevicePolicyOverrideApns(@NonNull Context context) {
@@ -12479,7 +12501,6 @@
* @throws {@link SecurityException} if the caller is not the system or phone process.
* @hide
*/
- @SystemApi
@TestApi
// TODO: add new permission tag indicating that this is system-only.
public int addDevicePolicyOverrideApn(@NonNull Context context,
@@ -12510,7 +12531,6 @@
* @throws {@link SecurityException} if the caller is not the system or phone process.
* @hide
*/
- @SystemApi
@TestApi
// TODO: add new permission tag indicating that this is system-only.
public boolean modifyDevicePolicyOverrideApn(@NonNull Context context, int apnId,
@@ -12874,7 +12894,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public boolean setDataAllowedDuringVoiceCall(boolean allow) {
try {
@@ -12903,7 +12922,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public boolean isDataAllowedInVoiceCall() {
try {
@@ -12950,7 +12968,6 @@
* The IccLock state or password was changed successfully.
* @hide
*/
- @SystemApi
public static final int CHANGE_ICC_LOCK_SUCCESS = Integer.MAX_VALUE;
/**
@@ -12963,7 +12980,6 @@
*
* @hide
*/
- @SystemApi
@WorkerThread
@RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public boolean isIccLockEnabled() {
@@ -13000,7 +13016,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public int setIccLockEnabled(boolean enabled, @NonNull String password) {
checkNotNull(password, "setIccLockEnabled password can't be null.");
@@ -13034,7 +13049,6 @@
*
* @hide
*/
- @SystemApi
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
public int changeIccLockPassword(@NonNull String oldPassword, @NonNull String newPassword) {
checkNotNull(oldPassword, "changeIccLockPassword oldPassword can't be null.");
diff --git a/telephony/java/android/telephony/data/ApnSetting.java b/telephony/java/android/telephony/data/ApnSetting.java
index f5dfacc6..bfb54b0 100644
--- a/telephony/java/android/telephony/data/ApnSetting.java
+++ b/telephony/java/android/telephony/data/ApnSetting.java
@@ -18,7 +18,6 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.SystemApi;
import android.content.ContentValues;
import android.database.Cursor;
import android.hardware.radio.V1_5.ApnTypes;
@@ -27,7 +26,6 @@
import android.os.Parcelable;
import android.provider.Telephony;
import android.provider.Telephony.Carriers;
-import android.telephony.Annotation;
import android.telephony.Annotation.ApnType;
import android.telephony.Annotation.NetworkType;
import android.telephony.ServiceState;
@@ -126,6 +124,15 @@
/** Authentication type for PAP or CHAP. */
public static final int AUTH_TYPE_PAP_OR_CHAP = 3;
+ /** @hide */
+ @IntDef({
+ Telephony.Carriers.SKIP_464XLAT_DEFAULT,
+ Telephony.Carriers.SKIP_464XLAT_DISABLE,
+ Telephony.Carriers.SKIP_464XLAT_ENABLE,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface Skip464XlatStatus {}
+
/**
* APN types for data connections. These are usage categories for an APN
* entry. One APN entry may support multiple APN types, eg, a single APN
@@ -139,7 +146,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_ALL_STRING = "*";
/**
@@ -147,7 +153,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_DEFAULT_STRING = "default";
@@ -156,7 +161,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_MMS_STRING = "mms";
@@ -165,7 +169,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_SUPL_STRING = "supl";
/**
@@ -173,7 +176,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_DUN_STRING = "dun";
/**
@@ -181,7 +183,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_HIPRI_STRING = "hipri";
/**
@@ -189,7 +190,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_FOTA_STRING = "fota";
/**
@@ -197,7 +197,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_IMS_STRING = "ims";
/**
@@ -205,7 +204,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_CBS_STRING = "cbs";
/**
@@ -213,7 +211,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_IA_STRING = "ia";
/**
@@ -222,7 +219,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_EMERGENCY_STRING = "emergency";
/**
@@ -230,7 +226,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_MCX_STRING = "mcx";
/**
@@ -238,7 +233,6 @@
*
* @hide
*/
- @SystemApi
public static final String TYPE_XCAP_STRING = "xcap";
@@ -745,7 +739,7 @@
* @return SKIP_464XLAT_DEFAULT, SKIP_464XLAT_DISABLE or SKIP_464XLAT_ENABLE
* @hide
*/
- @Annotation.Skip464XlatStatus
+ @Skip464XlatStatus
public int getSkip464Xlat() {
return mSkip464Xlat;
}
@@ -1416,7 +1410,6 @@
* @return comma delimited list of APN types.
* @hide
*/
- @SystemApi
@NonNull
public static String getApnTypesStringFromBitmask(int apnTypeBitmask) {
List<String> types = new ArrayList<>();
@@ -2065,7 +2058,7 @@
* @param skip464xlat skip464xlat for this APN.
* @hide
*/
- public Builder setSkip464Xlat(@Annotation.Skip464XlatStatus int skip464xlat) {
+ public Builder setSkip464Xlat(@Skip464XlatStatus int skip464xlat) {
this.mSkip464Xlat = skip464xlat;
return this;
}
diff --git a/telephony/java/android/telephony/data/DataService.java b/telephony/java/android/telephony/data/DataService.java
index 6c4e7ce..f56bbe1 100644
--- a/telephony/java/android/telephony/data/DataService.java
+++ b/telephony/java/android/telephony/data/DataService.java
@@ -458,6 +458,9 @@
* this method to facilitate the creation of {@link DataServiceProvider} instances. The system
* will call this method after binding the data service for each active SIM slot id.
*
+ * This methead is guaranteed to be invoked in {@link DataService}'s internal handler thread
+ * whose looper can be retrieved with {@link Looper.myLooper()} when override this method.
+ *
* @param slotIndex SIM slot id the data service associated with.
* @return Data service object. Null if failed to create the provider (e.g. invalid slot index)
*/
diff --git a/telephony/java/android/telephony/ims/ImsCallProfile.java b/telephony/java/android/telephony/ims/ImsCallProfile.java
index 9c1be48..1597cd5 100644
--- a/telephony/java/android/telephony/ims/ImsCallProfile.java
+++ b/telephony/java/android/telephony/ims/ImsCallProfile.java
@@ -18,7 +18,6 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.compat.annotation.UnsupportedAppUsage;
@@ -718,11 +717,16 @@
* @return A {@link Bundle} containing proprietary call extras that were not set by the
* platform.
*/
- public @Nullable Bundle getProprietaryCallExtras() {
+ public @NonNull Bundle getProprietaryCallExtras() {
if (mCallExtras == null) {
- return null;
+ return new Bundle();
}
- return mCallExtras.getBundle(EXTRA_OEM_EXTRAS);
+ Bundle proprietaryExtras = mCallExtras.getBundle(EXTRA_OEM_EXTRAS);
+ if (proprietaryExtras == null) {
+ return new Bundle();
+ }
+ // Make a copy so users do not accidentally change this copy of the extras.
+ return new Bundle(proprietaryExtras);
}
public ImsStreamMediaProfile getMediaProfile() {
diff --git a/telephony/java/android/telephony/ims/ImsCallSessionListener.java b/telephony/java/android/telephony/ims/ImsCallSessionListener.java
index 025721c..81af99f 100644
--- a/telephony/java/android/telephony/ims/ImsCallSessionListener.java
+++ b/telephony/java/android/telephony/ims/ImsCallSessionListener.java
@@ -58,7 +58,7 @@
try {
mListener.callSessionProgressing(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -71,7 +71,7 @@
try {
mListener.callSessionInitiated(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -85,7 +85,7 @@
try {
mListener.callSessionInitiatedFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -98,7 +98,7 @@
try {
mListener.callSessionTerminated(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -115,7 +115,7 @@
try {
mListener.callSessionHeld(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -128,7 +128,7 @@
try {
mListener.callSessionHoldFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -141,7 +141,7 @@
try {
mListener.callSessionHoldReceived(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -155,7 +155,7 @@
try {
mListener.callSessionResumed(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -169,7 +169,7 @@
try {
mListener.callSessionResumeFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -182,7 +182,7 @@
try {
mListener.callSessionResumeReceived(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -201,7 +201,7 @@
mListener.callSessionMergeStarted(newSession != null ?
newSession.getServiceImpl() : null, profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -216,7 +216,7 @@
try {
mListener.callSessionMergeStarted(newSession, profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -232,7 +232,7 @@
mListener.callSessionMergeComplete(newSession != null ?
newSession.getServiceImpl() : null);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -247,7 +247,7 @@
try {
mListener.callSessionMergeComplete(newSession);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -260,7 +260,7 @@
try {
mListener.callSessionMergeFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -273,7 +273,7 @@
try {
mListener.callSessionUpdated(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -286,7 +286,7 @@
try {
mListener.callSessionUpdateFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -299,7 +299,7 @@
try {
mListener.callSessionUpdateReceived(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -319,7 +319,7 @@
mListener.callSessionConferenceExtended(
newSession != null ? newSession.getServiceImpl() : null, profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -333,7 +333,7 @@
try {
mListener.callSessionConferenceExtended(newSession, profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -347,7 +347,7 @@
try {
mListener.callSessionConferenceExtendFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -364,7 +364,7 @@
mListener.callSessionConferenceExtendReceived(newSession != null
? newSession.getServiceImpl() : null, profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -379,7 +379,7 @@
try {
mListener.callSessionConferenceExtendReceived(newSession, profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -391,7 +391,7 @@
try {
mListener.callSessionInviteParticipantsRequestDelivered();
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -407,7 +407,7 @@
try {
mListener.callSessionInviteParticipantsRequestFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -419,7 +419,7 @@
try {
mListener.callSessionRemoveParticipantsRequestDelivered();
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -435,7 +435,7 @@
try {
mListener.callSessionInviteParticipantsRequestFailed(reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -448,7 +448,7 @@
try {
mListener.callSessionConferenceStateUpdated(state);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -465,7 +465,7 @@
try {
mListener.callSessionUssdMessageReceived(mode, ussdMessage);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -501,7 +501,7 @@
try {
mListener.callSessionMayHandover(srcNetworkType, targetNetworkType);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -537,7 +537,7 @@
try {
mListener.callSessionHandover(srcNetworkType, targetNetworkType, reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -570,7 +570,7 @@
try {
mListener.callSessionHandoverFailed(srcNetworkType, targetNetworkType, reasonInfo);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -587,7 +587,7 @@
try {
mListener.callSessionTtyModeReceived(mode);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -600,7 +600,7 @@
try {
mListener.callSessionMultipartyStateChanged(isMultiParty);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -614,7 +614,7 @@
try {
mListener.callSessionSuppServiceReceived(suppSrvNotification);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -628,7 +628,7 @@
try {
mListener.callSessionRttModifyRequestReceived(callProfile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -641,7 +641,7 @@
try {
mListener.callSessionRttModifyResponseReceived(status);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -654,7 +654,7 @@
try {
mListener.callSessionRttMessageReceived(rttMessage);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -667,7 +667,7 @@
try {
mListener.callSessionRttAudioIndicatorChanged(profile);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
@@ -680,7 +680,7 @@
try {
mListener.callQualityChanged(callQuality);
} catch (RemoteException e) {
- throw new RuntimeException(e);
+ e.rethrowFromSystemServer();
}
}
}
diff --git a/telephony/java/android/telephony/ims/ImsMmTelManager.java b/telephony/java/android/telephony/ims/ImsMmTelManager.java
index 3341fa7..bd531da 100644
--- a/telephony/java/android/telephony/ims/ImsMmTelManager.java
+++ b/telephony/java/android/telephony/ims/ImsMmTelManager.java
@@ -21,7 +21,6 @@
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SuppressAutoDoc;
import android.annotation.SuppressLint;
@@ -124,7 +123,7 @@
* @param info the {@link ImsReasonInfo} associated with why registration was disconnected.
*/
@Override
- public void onUnregistered(@Nullable ImsReasonInfo info) {
+ public void onUnregistered(@NonNull ImsReasonInfo info) {
}
/**
@@ -136,7 +135,7 @@
@Override
public void onTechnologyChangeFailed(
@AccessNetworkConstants.TransportType int imsTransportType,
- @Nullable ImsReasonInfo info) {
+ @NonNull ImsReasonInfo info) {
}
}
@@ -294,8 +293,15 @@
throw new IllegalArgumentException("Must include a non-null Executor.");
}
c.setExecutor(executor);
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new ImsException("Could not find Telephony Service.",
+ ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
+ }
+
try {
- getITelephony().registerImsRegistrationCallback(mSubId, c.getBinder());
+ iTelephony.registerImsRegistrationCallback(mSubId, c.getBinder());
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -331,8 +337,15 @@
throw new IllegalArgumentException("Must include a non-null Executor.");
}
c.setExecutor(executor);
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new ImsException("Could not find Telephony Service.",
+ ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
+ }
+
try {
- getITelephony().registerImsRegistrationCallback(mSubId, c.getBinder());
+ iTelephony.registerImsRegistrationCallback(mSubId, c.getBinder());
} catch (ServiceSpecificException e) {
throw new ImsException(e.getMessage(), e.errorCode);
} catch (RemoteException | IllegalStateException e) {
@@ -361,8 +374,14 @@
if (c == null) {
throw new IllegalArgumentException("Must include a non-null RegistrationCallback.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().unregisterImsRegistrationCallback(mSubId, c.getBinder());
+ iTelephony.unregisterImsRegistrationCallback(mSubId, c.getBinder());
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -387,8 +406,14 @@
if (c == null) {
throw new IllegalArgumentException("Must include a non-null RegistrationCallback.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().unregisterImsRegistrationCallback(mSubId, c.getBinder());
+ iTelephony.unregisterImsRegistrationCallback(mSubId, c.getBinder());
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -409,8 +434,14 @@
if (executor == null) {
throw new IllegalArgumentException("Must include a non-null Executor.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().getImsMmTelRegistrationState(mSubId, new IIntegerConsumer.Stub() {
+ iTelephony.getImsMmTelRegistrationState(mSubId, new IIntegerConsumer.Stub() {
@Override
public void accept(int result) {
executor.execute(() -> stateCallback.accept(result));
@@ -443,8 +474,14 @@
if (executor == null) {
throw new IllegalArgumentException("Must include a non-null Executor.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().getImsMmTelRegistrationTransportType(mSubId,
+ iTelephony.getImsMmTelRegistrationTransportType(mSubId,
new IIntegerConsumer.Stub() {
@Override
public void accept(int result) {
@@ -506,8 +543,15 @@
throw new IllegalArgumentException("Must include a non-null Executor.");
}
c.setExecutor(executor);
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new ImsException("Could not find Telephony Service.",
+ ImsException.CODE_ERROR_INVALID_SUBSCRIPTION);
+ }
+
try {
- getITelephony().registerMmTelCapabilityCallback(mSubId, c.getBinder());
+ iTelephony.registerMmTelCapabilityCallback(mSubId, c.getBinder());
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -553,8 +597,14 @@
if (c == null) {
throw new IllegalArgumentException("Must include a non-null RegistrationCallback.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().unregisterMmTelCapabilityCallback(mSubId, c.getBinder());
+ iTelephony.unregisterMmTelCapabilityCallback(mSubId, c.getBinder());
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -599,8 +649,13 @@
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
android.Manifest.permission.READ_PRECISE_PHONE_STATE})
public boolean isAdvancedCallingSettingEnabled() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isAdvancedCallingSettingEnabled(mSubId);
+ return iTelephony.isAdvancedCallingSettingEnabled(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -640,8 +695,13 @@
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
@SystemApi @TestApi
public void setAdvancedCallingSettingEnabled(boolean isEnabled) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setAdvancedCallingSettingEnabled(mSubId, isEnabled);
+ iTelephony.setAdvancedCallingSettingEnabled(mSubId, isEnabled);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -680,8 +740,13 @@
@SystemApi @TestApi
public boolean isCapable(@MmTelFeature.MmTelCapabilities.MmTelCapability int capability,
@ImsRegistrationImplBase.ImsRegistrationTech int imsRegTech) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isCapable(mSubId, capability, imsRegTech);
+ return iTelephony.isCapable(mSubId, capability, imsRegTech);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -709,8 +774,13 @@
@RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public boolean isAvailable(@MmTelFeature.MmTelCapabilities.MmTelCapability int capability,
@ImsRegistrationImplBase.ImsRegistrationTech int imsRegTech) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isAvailable(mSubId, capability, imsRegTech);
+ return iTelephony.isAvailable(mSubId, capability, imsRegTech);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -744,6 +814,13 @@
if (executor == null) {
throw new IllegalArgumentException("Must include a non-null Executor.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new ImsException("Could not find Telephony Service.",
+ ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
+ }
+
try {
getITelephony().isMmTelCapabilitySupported(mSubId, new IIntegerConsumer.Stub() {
@Override
@@ -788,8 +865,13 @@
android.Manifest.permission.READ_PRECISE_PHONE_STATE})
@SuppressAutoDoc // No support for device / profile owner or carrier privileges (b/72967236).
public boolean isVtSettingEnabled() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isVtSettingEnabled(mSubId);
+ return iTelephony.isVtSettingEnabled(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -813,8 +895,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setVtSettingEnabled(boolean isEnabled) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setVtSettingEnabled(mSubId, isEnabled);
+ iTelephony.setVtSettingEnabled(mSubId, isEnabled);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -853,8 +940,13 @@
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
android.Manifest.permission.READ_PRECISE_PHONE_STATE})
public boolean isVoWiFiSettingEnabled() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isVoWiFiSettingEnabled(mSubId);
+ return iTelephony.isVoWiFiSettingEnabled(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -879,8 +971,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setVoWiFiSettingEnabled(boolean isEnabled) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setVoWiFiSettingEnabled(mSubId, isEnabled);
+ iTelephony.setVoWiFiSettingEnabled(mSubId, isEnabled);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -921,8 +1018,13 @@
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
android.Manifest.permission.READ_PRECISE_PHONE_STATE})
public boolean isVoWiFiRoamingSettingEnabled() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isVoWiFiRoamingSettingEnabled(mSubId);
+ return iTelephony.isVoWiFiRoamingSettingEnabled(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -948,8 +1050,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setVoWiFiRoamingSettingEnabled(boolean isEnabled) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setVoWiFiRoamingSettingEnabled(mSubId, isEnabled);
+ iTelephony.setVoWiFiRoamingSettingEnabled(mSubId, isEnabled);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -980,8 +1087,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setVoWiFiNonPersistent(boolean isCapable, int mode) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setVoWiFiNonPersistent(mSubId, isCapable, mode);
+ iTelephony.setVoWiFiNonPersistent(mSubId, isCapable, mode);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1025,8 +1137,13 @@
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
android.Manifest.permission.READ_PRECISE_PHONE_STATE})
public @WiFiCallingMode int getVoWiFiModeSetting() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().getVoWiFiModeSetting(mSubId);
+ return iTelephony.getVoWiFiModeSetting(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1054,8 +1171,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setVoWiFiModeSetting(@WiFiCallingMode int mode) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setVoWiFiModeSetting(mSubId, mode);
+ iTelephony.setVoWiFiModeSetting(mSubId, mode);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1085,8 +1207,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
public @WiFiCallingMode int getVoWiFiRoamingModeSetting() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().getVoWiFiRoamingModeSetting(mSubId);
+ return iTelephony.getVoWiFiRoamingModeSetting(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1116,8 +1243,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setVoWiFiRoamingModeSetting(@WiFiCallingMode int mode) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setVoWiFiRoamingModeSetting(mSubId, mode);
+ iTelephony.setVoWiFiRoamingModeSetting(mSubId, mode);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1145,8 +1277,13 @@
@SystemApi @TestApi
@RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
public void setRttCapabilitySetting(boolean isEnabled) {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- getITelephony().setRttCapabilitySetting(mSubId, isEnabled);
+ iTelephony.setRttCapabilitySetting(mSubId, isEnabled);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1186,8 +1323,13 @@
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
android.Manifest.permission.READ_PRECISE_PHONE_STATE})
public boolean isTtyOverVolteEnabled() {
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new RuntimeException("Could not find Telephony Service.");
+ }
+
try {
- return getITelephony().isTtyOverVolteEnabled(mSubId);
+ return iTelephony.isTtyOverVolteEnabled(mSubId);
} catch (ServiceSpecificException e) {
if (e.errorCode == ImsException.CODE_ERROR_INVALID_SUBSCRIPTION) {
// Rethrow as runtime error to keep API compatible.
@@ -1223,8 +1365,15 @@
if (callback == null) {
throw new IllegalArgumentException("Must include a non-null Consumer.");
}
+
+ ITelephony iTelephony = getITelephony();
+ if (iTelephony == null) {
+ throw new ImsException("Could not find Telephony Service.",
+ ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
+ }
+
try {
- getITelephony().getImsMmTelFeatureState(mSubId, new IIntegerConsumer.Stub() {
+ iTelephony.getImsMmTelFeatureState(mSubId, new IIntegerConsumer.Stub() {
@Override
public void accept(int result) {
executor.execute(() -> callback.accept(result));
@@ -1243,9 +1392,6 @@
.getTelephonyServiceManager()
.getTelephonyServiceRegisterer()
.get());
- if (binder == null) {
- throw new RuntimeException("Could not find Telephony Service.");
- }
return binder;
}
}
diff --git a/telephony/java/android/telephony/ims/ImsUtListener.java b/telephony/java/android/telephony/ims/ImsUtListener.java
index bc124044..460a032 100644
--- a/telephony/java/android/telephony/ims/ImsUtListener.java
+++ b/telephony/java/android/telephony/ims/ImsUtListener.java
@@ -49,7 +49,8 @@
* {@link ImsSsInfo#CLIR_STATUS_TEMPORARILY_RESTRICTED}, and
* {@link ImsSsInfo#CLIR_STATUS_TEMPORARILY_ALLOWED}.
* @deprecated Use {@link #onLineIdentificationSupplementaryServiceResponse(int, ImsSsInfo)}
- * instead.
+ * instead, this key has been added for backwards compatibility with older proprietary
+ * implementations only and is being phased out.
*/
@Deprecated
public static final String BUNDLE_KEY_CLIR = "queryClir";
@@ -60,7 +61,8 @@
* response. The value will be an instance of {@link ImsSsInfo}, which contains the response to
* the query.
* @deprecated Use {@link #onLineIdentificationSupplementaryServiceResponse(int, ImsSsInfo)}
- * instead.
+ * instead, this key has been added for backwards compatibility with older proprietary
+ * implementations only and is being phased out.
*/
@Deprecated
public static final String BUNDLE_KEY_SSINFO = "imsSsInfo";
@@ -123,7 +125,7 @@
try {
mServiceInterface.lineIdentificationSupplementaryServiceResponse(id, configuration);
} catch (RemoteException e) {
- Log.w(LOG_TAG, "onLineIdentificationSupplementaryServicesResponse: remote exception");
+ e.rethrowFromSystemServer();
}
}
diff --git a/telephony/java/android/telephony/ims/ProvisioningManager.java b/telephony/java/android/telephony/ims/ProvisioningManager.java
index 0370846..1a606b7 100644
--- a/telephony/java/android/telephony/ims/ProvisioningManager.java
+++ b/telephony/java/android/telephony/ims/ProvisioningManager.java
@@ -85,6 +85,7 @@
/**
* There is no existing configuration for the queried provisioning key.
+ * @hide
*/
public static final int PROVISIONING_RESULT_UNKNOWN = -1;
@@ -120,6 +121,7 @@
* Value is in String format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_AMR_CODEC_MODE_SET_VALUES = 0;
@@ -143,6 +145,7 @@
* Value is in String format.
* @see #setProvisioningStringValue(int, String)
* @see #getProvisioningStringValue(int)
+ * @hide
*/
public static final int KEY_AMR_WB_CODEC_MODE_SET_VALUES = 1;
@@ -154,6 +157,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_SESSION_TIMER_SEC = 2;
@@ -165,6 +169,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_MINIMUM_SIP_SESSION_EXPIRATION_TIMER_SEC = 3;
@@ -176,6 +181,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_INVITE_CANCELLATION_TIMER_MS = 4;
@@ -184,6 +190,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_TRANSITION_TO_LTE_DELAY_MS = 5;
@@ -192,6 +199,7 @@
* Value is in boolean format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_ENABLE_SILENT_REDIAL = 6;
@@ -207,6 +215,7 @@
* The value is an integer.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_T1_TIMER_VALUE_MS = 7;
@@ -218,6 +227,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_T2_TIMER_VALUE_MS = 8;
@@ -229,6 +239,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_TF_TIMER_VALUE_MS = 9;
@@ -241,6 +252,7 @@
* {@link #PROVISIONING_VALUE_DISABLED} to disable VoLTE provisioning.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_VOLTE_PROVISIONING_STATUS = 10;
@@ -253,6 +265,7 @@
* {@link #PROVISIONING_VALUE_DISABLED} to disable VT provisioning.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_VT_PROVISIONING_STATUS = 11;
@@ -261,6 +274,7 @@
* Value is in String format.
* @see #setProvisioningStringValue(int, String)
* @see #getProvisioningStringValue(int)
+ * @hide
*/
public static final int KEY_REGISTRATION_DOMAIN_NAME = 12;
@@ -270,18 +284,21 @@
* Valid values are {@link #SMS_FORMAT_3GPP} and {@link #SMS_FORMAT_3GPP2}.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SMS_FORMAT = 13;
/**
* Value used with {@link #KEY_SMS_FORMAT} to indicate 3GPP2 SMS format is used.
* See {@link android.telephony.SmsMessage#FORMAT_3GPP2} for more information.
+ * @hide
*/
public static final int SMS_FORMAT_3GPP2 = 0;
/**
* Value used with {@link #KEY_SMS_FORMAT} to indicate 3GPP SMS format is used.
* See {@link android.telephony.SmsMessage#FORMAT_3GPP} for more information.
+ * @hide
*/
public static final int SMS_FORMAT_3GPP = 1;
@@ -290,6 +307,7 @@
* Value is in Integer format. ON (1), OFF(0).
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SMS_OVER_IP_ENABLED = 14;
@@ -300,18 +318,20 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_PUBLISH_TIMER_SEC = 15;
/**
* An integer key associated with the carrier configured expiration time in seconds for
- * RCS presence published offline availability in RCS presence.
+ * published offline availability in RCS presence provided, which is provided to the network.
* <p>
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
- public static final int KEY_RCS_PUBLISH_TIMER_EXTENDED_SEC = 16;
+ public static final int KEY_RCS_PUBLISH_OFFLINE_AVAILABILITY_TIMER_SEC = 16;
/**
* An integer key associated with whether or not capability discovery is provisioned for this
@@ -322,46 +342,55 @@
* enabled.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_CAPABILITY_DISCOVERY_ENABLED = 17;
/**
- * An integer key associated with the period of time the capability information of each contact
- * is cached on the device.
+ * An integer key associated with the period of time in seconds the capability information of
+ * each contact is cached on the device.
+ * <p>
+ * Seconds are used because this is usually measured in the span of days.
* <p>
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_CAPABILITIES_CACHE_EXPIRATION_SEC = 18;
/**
* An integer key associated with the period of time in seconds that the availability
- * information of a contact is cached on the device.
+ * information of a contact is cached on the device, which is based on the carrier provisioning
+ * configuration from the network.
* <p>
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_AVAILABILITY_CACHE_EXPIRATION_SEC = 19;
/**
* An integer key associated with the carrier configured interval in seconds expected between
- * successive capability polling attempts.
+ * successive capability polling attempts, which is based on the carrier provisioning
+ * configuration from the network.
* <p>
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_CAPABILITIES_POLL_INTERVAL_SEC = 20;
/**
* An integer key representing the minimum time allowed between two consecutive presence publish
- * messages from the device.
+ * messages from the device in milliseconds.
* <p>
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_PUBLISH_SOURCE_THROTTLE_MS = 21;
@@ -372,17 +401,19 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_MAX_NUM_ENTRIES_IN_RCL = 22;
/**
* An integer associated with the expiration timer used during the SIP subscription of a
* Request Contained List (RCL), which is used to retrieve the RCS capabilities of the contact
- * book.
+ * book. This timer value is sent in seconds to the network.
* <p>
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RCS_CAPABILITY_POLL_LIST_SUB_EXP_SEC = 23;
@@ -391,6 +422,7 @@
* Value is in Integer format. Enable (1), Disable(0).
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_USE_GZIP_FOR_LIST_SUBSCRIPTION = 24;
@@ -403,6 +435,7 @@
* {@link #PROVISIONING_VALUE_DISABLED} to disable EAB provisioning.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_EAB_PROVISIONING_STATUS = 25;
@@ -436,6 +469,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_VOICE_OVER_WIFI_ENABLED_OVERRIDE = 28;
@@ -444,6 +478,7 @@
* Value is in Integer format. On (1), OFF(0).
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_MOBILE_DATA_ENABLED = 29;
@@ -452,12 +487,14 @@
* Value is in Integer format. Opted-in (1) Opted-out (0).
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_VOLTE_USER_OPT_IN_STATUS = 30;
/**
* Proxy for Call Session Control Function(P-CSCF) address for Local-BreakOut(LBO).
* Value is in String format.
+ * @hide
*/
public static final int KEY_LOCAL_BREAKOUT_PCSCF_ADDRESS = 31;
@@ -466,22 +503,27 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_KEEP_ALIVE_ENABLED = 32;
/**
- * Registration retry Base Time value in seconds.
+ * Registration retry Base Time value in seconds, which is based off of the carrier
+ * configuration.
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_REGISTRATION_RETRY_BASE_TIME_SEC = 33;
/**
- * Registration retry Max Time value in seconds.
+ * Registration retry Max Time value in seconds, which is based off of the carrier
+ * configuration.
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_REGISTRATION_RETRY_MAX_TIME_SEC = 34;
@@ -490,6 +532,7 @@
* Value is in integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RTP_SPEECH_START_PORT = 35;
@@ -499,6 +542,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RTP_SPEECH_END_PORT = 36;
@@ -508,6 +552,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_INVITE_REQUEST_TRANSMIT_INTERVAL_MS = 37;
@@ -517,6 +562,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_INVITE_ACK_WAIT_TIME_MS = 38;
@@ -526,6 +572,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_INVITE_RESPONSE_RETRANSMIT_WAIT_TIME_MS = 39;
@@ -535,6 +582,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_NON_INVITE_REQUEST_RETRANSMIT_INTERVAL_MS = 40;
@@ -544,6 +592,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_NON_INVITE_TRANSACTION_TIMEOUT_TIMER_MS = 41;
@@ -553,6 +602,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_INVITE_RESPONSE_RETRANSMIT_INTERVAL_MS = 42;
@@ -562,6 +612,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_ACK_RECEIPT_WAIT_TIME_MS = 43;
@@ -571,6 +622,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_ACK_RETRANSMIT_WAIT_TIME_MS = 44;
@@ -580,6 +632,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_NON_INVITE_REQUEST_RETRANSMISSION_WAIT_TIME_MS = 45;
@@ -589,6 +642,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_SIP_NON_INVITE_RESPONSE_RETRANSMISSION_WAIT_TIME_MS = 46;
@@ -597,6 +651,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_AMR_WB_OCTET_ALIGNED_PAYLOAD_TYPE = 47;
@@ -605,6 +660,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_AMR_WB_BANDWIDTH_EFFICIENT_PAYLOAD_TYPE = 48;
@@ -613,6 +669,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_AMR_OCTET_ALIGNED_PAYLOAD_TYPE = 49;
@@ -621,6 +678,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_AMR_BANDWIDTH_EFFICIENT_PAYLOAD_TYPE = 50;
@@ -629,6 +687,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_DTMF_WB_PAYLOAD_TYPE = 51;
@@ -637,6 +696,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_DTMF_NB_PAYLOAD_TYPE = 52;
@@ -645,12 +705,14 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_AMR_DEFAULT_ENCODING_MODE = 53;
/**
* SMS Public Service Identity.
* Value is in String format.
+ * @hide
*/
public static final int KEY_SMS_PUBLIC_SERVICE_IDENTITY = 54;
@@ -660,16 +722,19 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_VIDEO_QUALITY = 55;
/**
* Used with {@link #KEY_VIDEO_QUALITY} to indicate low video quality.
+ * @hide
*/
public static final int VIDEO_QUALITY_LOW = 0;
/**
* Used with {@link #KEY_VIDEO_QUALITY} to indicate high video quality.
+ * @hide
*/
public static final int VIDEO_QUALITY_HIGH = 1;
@@ -679,6 +744,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_LTE_THRESHOLD_1 = 56;
@@ -690,6 +756,7 @@
*
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_LTE_THRESHOLD_2 = 57;
@@ -701,6 +768,7 @@
*
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_LTE_THRESHOLD_3 = 58;
@@ -710,6 +778,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_1X_THRESHOLD = 59;
@@ -721,6 +790,7 @@
*
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_WIFI_THRESHOLD_A = 60;
@@ -731,6 +801,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_WIFI_THRESHOLD_B = 61;
@@ -740,6 +811,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_LTE_EPDG_TIMER_SEC = 62;
@@ -749,12 +821,14 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_WIFI_EPDG_TIMER_SEC = 63;
/**
* 1x ePDG timer (in seconds).
* Device shall not re-register on 1x until the T_ePDG_1x timer expires.
+ * @hide
*/
public static final int KEY_1X_EPDG_TIMER_SEC = 64;
@@ -763,6 +837,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_MULTIENDPOINT_ENABLED = 65;
@@ -771,6 +846,7 @@
* Value is in Integer format.
* @see #setProvisioningIntValue(int, int)
* @see #getProvisioningIntValue(int)
+ * @hide
*/
public static final int KEY_RTT_ENABLED = 66;
@@ -922,7 +998,7 @@
*
* @param key An integer that represents the provisioning key, which is defined by the OEM.
* @return an integer value for the provided key, or
- * {@link #PROVISIONING_RESULT_UNKNOWN} if the key doesn't exist.
+ * {@link ImsConfigImplBase#CONFIG_RESULT_UNKNOWN} if the key doesn't exist.
* @throws IllegalArgumentException if the key provided was invalid.
*/
@WorkerThread
diff --git a/telephony/java/android/telephony/ims/RcsContactUceCapability.java b/telephony/java/android/telephony/ims/RcsContactUceCapability.java
index 57b9b7a..dc36edf 100644
--- a/telephony/java/android/telephony/ims/RcsContactUceCapability.java
+++ b/telephony/java/android/telephony/ims/RcsContactUceCapability.java
@@ -19,8 +19,6 @@
import android.annotation.LongDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.annotation.TestApi;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
@@ -37,8 +35,6 @@
* Contains the User Capability Exchange capabilities corresponding to a contact's URI.
* @hide
*/
-@SystemApi
-@TestApi
public final class RcsContactUceCapability implements Parcelable {
/** Supports 1-to-1 chat */
diff --git a/telephony/java/android/telephony/ims/RcsUceAdapter.java b/telephony/java/android/telephony/ims/RcsUceAdapter.java
index 58e9b70..05ab6bd 100644
--- a/telephony/java/android/telephony/ims/RcsUceAdapter.java
+++ b/telephony/java/android/telephony/ims/RcsUceAdapter.java
@@ -24,12 +24,10 @@
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.content.Context;
-import android.database.ContentObserver;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
-import android.provider.Telephony;
import android.telephony.TelephonyFrameworkInitializer;
import android.telephony.ims.aidl.IImsRcsController;
import android.telephony.ims.aidl.IRcsUceControllerCallback;
@@ -138,7 +136,7 @@
* UCE.
* @hide
*/
- public static final int PUBLISH_STATE_200_OK = 1;
+ public static final int PUBLISH_STATE_OK = 1;
/**
* The hasn't published its capabilities since boot or hasn't gotten any publish response yet.
@@ -178,7 +176,7 @@
/**@hide*/
@Retention(RetentionPolicy.SOURCE)
@IntDef(prefix = "PUBLISH_STATE_", value = {
- PUBLISH_STATE_200_OK,
+ PUBLISH_STATE_OK,
PUBLISH_STATE_NOT_PUBLISHED,
PUBLISH_STATE_VOLTE_PROVISION_ERROR,
PUBLISH_STATE_RCS_PROVISION_ERROR,
@@ -293,7 +291,7 @@
try {
imsRcsController.requestCapabilities(mSubId, mContext.getOpPackageName(),
- mContext.getFeatureId(), contactNumbers, internalCallback);
+ mContext.getAttributionTag(), contactNumbers, internalCallback);
} catch (RemoteException e) {
Log.e(TAG, "Error calling IImsRcsController#requestCapabilities", e);
throw new ImsException("Remote IMS Service is not available",
@@ -305,7 +303,7 @@
* Gets the last publish result from the UCE service if the device is using an RCS presence
* server.
* @return The last publish result from the UCE service. If the device is using SIP OPTIONS,
- * this method will return {@link #PUBLISH_STATE_200_OK} as well.
+ * this method will return {@link #PUBLISH_STATE_OK} as well.
* @throws ImsException if the subscription associated with this instance of
* {@link RcsUceAdapter} is valid, but the ImsService associated with the subscription is not
* available. This can happen if the ImsService has crashed, for example, or if the subscription
@@ -354,7 +352,7 @@
try {
// Telephony.SimInfo#IMS_RCS_UCE_ENABLED can also be used to listen to changes to this.
return imsRcsController.isUceSettingEnabled(mSubId, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException e) {
Log.e(TAG, "Error calling IImsRcsController#isUceSettingEnabled", e);
throw new ImsException("Remote IMS Service is not available",
diff --git a/telephony/java/android/telephony/ims/RegistrationManager.java b/telephony/java/android/telephony/ims/RegistrationManager.java
index 5c86ba7..1dbaff5 100644
--- a/telephony/java/android/telephony/ims/RegistrationManager.java
+++ b/telephony/java/android/telephony/ims/RegistrationManager.java
@@ -196,11 +196,11 @@
}
/**
- * Notifies the framework when the IMS Provider is deregistered from the IMS network.
+ * Notifies the framework when the IMS Provider is unregistered from the IMS network.
*
* @param info the {@link ImsReasonInfo} associated with why registration was disconnected.
*/
- public void onUnregistered(@Nullable ImsReasonInfo info) {
+ public void onUnregistered(@NonNull ImsReasonInfo info) {
}
/**
@@ -211,7 +211,7 @@
*/
public void onTechnologyChangeFailed(
@AccessNetworkConstants.TransportType int imsTransportType,
- @Nullable ImsReasonInfo info) {
+ @NonNull ImsReasonInfo info) {
}
/**
diff --git a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java
index 14a64d2..7069e0a 100644
--- a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java
+++ b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java
@@ -175,9 +175,11 @@
*/
public final void onDeregistered(ImsReasonInfo info) {
updateToDisconnectedState(info);
+ // ImsReasonInfo should never be null.
+ final ImsReasonInfo reasonInfo = (info != null) ? info : new ImsReasonInfo();
mCallbacks.broadcastAction((c) -> {
try {
- c.onDeregistered(info);
+ c.onDeregistered(reasonInfo);
} catch (RemoteException e) {
Log.w(LOG_TAG, e + " " + "onRegistrationDisconnected() - Skipping " +
"callback.");
@@ -194,9 +196,10 @@
*/
public final void onTechnologyChangeFailed(@ImsRegistrationTech int imsRadioTech,
ImsReasonInfo info) {
+ final ImsReasonInfo reasonInfo = (info != null) ? info : new ImsReasonInfo();
mCallbacks.broadcastAction((c) -> {
try {
- c.onTechnologyChangeFailed(imsRadioTech, info);
+ c.onTechnologyChangeFailed(imsRadioTech, reasonInfo);
} catch (RemoteException e) {
Log.w(LOG_TAG, e + " " + "onRegistrationChangeFailed() - Skipping " +
"callback.");
diff --git a/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java b/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java
index f13371c..8564f7a 100644
--- a/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java
+++ b/telephony/java/android/telephony/ims/stub/ImsUtImplBase.java
@@ -44,52 +44,62 @@
public class ImsUtImplBase {
/**
* Bar all incoming calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_ALL_INCOMING = 1;
/**
* Bar all outgoing calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_ALL_OUTGOING = 2;
/**
* Bar all outgoing international calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_OUTGOING_INTL = 3;
/**
* Bar all outgoing international calls, excluding those to the home PLMN country
* (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_OUTGOING_INTL_EXCL_HOME = 4;
/**
* Bar all incoming calls when roaming (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BLOCKING_INCOMING_WHEN_ROAMING = 5;
/**
* Enable Anonymous Communication Rejection (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_ANONYMOUS_INCOMING = 6;
/**
* Bar all incoming and outgoing calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_ALL = 7;
/**
* Bar all outgoing service requests, including calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_OUTGOING_ALL_SERVICES = 8;
/**
* Bar all incoming service requests, including calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_INCOMING_ALL_SERVICES = 9;
/**
* Bar specific incoming calls. (See 3GPP TS 24.611)
+ * @hide
*/
public static final int CALL_BARRING_SPECIFIC_INCOMING_CALLS = 10;
@@ -104,6 +114,7 @@
/**
* Constant used to denote an invalid return value.
+ * @hide
*/
public static final int INVALID_RESULT = -1;
@@ -338,6 +349,7 @@
/**
* Updates the configuration of the call barring for specified service class with password.
+ * @hide
*/
public int updateCallBarringWithPassword(int cbType, int action, @Nullable String[] barrList,
int serviceClass, @NonNull String password) {
diff --git a/telephony/java/com/android/ims/ImsConfig.java b/telephony/java/com/android/ims/ImsConfig.java
index 96f77d8..d0cec52d 100644
--- a/telephony/java/com/android/ims/ImsConfig.java
+++ b/telephony/java/com/android/ims/ImsConfig.java
@@ -270,11 +270,12 @@
/**
* Requested expiration for Published Offline availability.
* Value is in Integer format.
- * @deprecated use {@link ProvisioningManager#KEY_RCS_PUBLISH_TIMER_EXTENDED_SEC}.
+ * @deprecated use
+ * {@link ProvisioningManager#KEY_RCS_PUBLISH_OFFLINE_AVAILABILITY_TIMER_SEC}.
*/
@Deprecated
public static final int PUBLISH_TIMER_EXTENDED =
- ProvisioningManager.KEY_RCS_PUBLISH_TIMER_EXTENDED_SEC;
+ ProvisioningManager.KEY_RCS_PUBLISH_OFFLINE_AVAILABILITY_TIMER_SEC;
/**
*
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index af5089f..dcf339c 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -22,6 +22,7 @@
import android.os.Bundle;
import android.os.IBinder;
import android.os.Messenger;
+import android.os.ParcelFileDescriptor;
import android.os.ResultReceiver;
import android.os.WorkSource;
import android.net.NetworkStats;
@@ -2121,9 +2122,14 @@
void notifyOtaEmergencyNumberDbInstalled();
/**
- * Override the file partition name for testing OTA emergency number database.
+ * Override a customized file partition name for OTA emergency number database.
*/
- void updateTestOtaEmergencyNumberDbFilePath(String otaFilePath);
+ void updateOtaEmergencyNumberDbFilePath(in ParcelFileDescriptor otaParcelFileDescriptor);
+
+ /**
+ * Reset file partition to default for OTA emergency number database.
+ */
+ void resetOtaEmergencyNumberDbFilePath();
/**
* Enable or disable a logical modem stack associated with the slotIndex.
diff --git a/test-mock/src/android/test/mock/MockContentResolver.java b/test-mock/src/android/test/mock/MockContentResolver.java
index 8283019..8f4bccc 100644
--- a/test-mock/src/android/test/mock/MockContentResolver.java
+++ b/test-mock/src/android/test/mock/MockContentResolver.java
@@ -25,6 +25,7 @@
import android.database.ContentObserver;
import android.net.Uri;
+import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@@ -172,7 +173,7 @@
* from observers elsewhere in the system.
*/
@Override
- public void notifyChange(@NonNull Iterable<Uri> uris, @Nullable ContentObserver observer,
+ public void notifyChange(@NonNull Collection<Uri> uris, @Nullable ContentObserver observer,
@NotifyFlags int flags) {
}
}
diff --git a/tests/BlobStoreTestUtils/src/com/android/utils/blob/DummyBlobData.java b/tests/BlobStoreTestUtils/src/com/android/utils/blob/DummyBlobData.java
index 504bd17..b805744 100644
--- a/tests/BlobStoreTestUtils/src/com/android/utils/blob/DummyBlobData.java
+++ b/tests/BlobStoreTestUtils/src/com/android/utils/blob/DummyBlobData.java
@@ -38,38 +38,75 @@
public class DummyBlobData {
private static final long DEFAULT_SIZE_BYTES = 10 * 1024L * 1024L;
- private final Context mContext;
private final Random mRandom;
private final File mFile;
private final long mFileSize;
- private final String mLabel;
+ private final CharSequence mLabel;
byte[] mFileDigest;
long mExpiryTimeMs;
- public DummyBlobData(Context context) {
- this(context, new Random(0), "blob_" + System.nanoTime());
+ public DummyBlobData(Builder builder) {
+ mRandom = new Random(builder.getRandomSeed());
+ mFile = new File(builder.getContext().getFilesDir(), builder.getFileName());
+ mFileSize = builder.getFileSize();
+ mLabel = builder.getLabel();
}
- public DummyBlobData(Context context, long fileSize) {
- this(context, fileSize, new Random(0), "blob_" + System.nanoTime(), "Test label");
- }
+ public static class Builder {
+ private final Context mContext;
+ private int mRandomSeed = 0;
+ private long mFileSize = DEFAULT_SIZE_BYTES;
+ private CharSequence mLabel = "Test label";
+ private String mFileName = "blob_" + System.nanoTime();
- public DummyBlobData(Context context, Random random, String fileName) {
- this(context, DEFAULT_SIZE_BYTES, random, fileName, "Test label");
- }
+ public Builder(Context context) {
+ mContext = context;
+ }
- public DummyBlobData(Context context, Random random, String fileName, String label) {
- this(context, DEFAULT_SIZE_BYTES, random, fileName, label);
- }
+ public Context getContext() {
+ return mContext;
+ }
- public DummyBlobData(Context context, long fileSize, Random random, String fileName,
- String label) {
- mContext = context;
- mRandom = random;
- mFile = new File(mContext.getFilesDir(), fileName);
- mFileSize = fileSize;
- mLabel = label;
+ public Builder setRandomSeed(int randomSeed) {
+ mRandomSeed = randomSeed;
+ return this;
+ }
+
+ public int getRandomSeed() {
+ return mRandomSeed;
+ }
+
+ public Builder setFileSize(int fileSize) {
+ mFileSize = fileSize;
+ return this;
+ }
+
+ public long getFileSize() {
+ return mFileSize;
+ }
+
+ public Builder setLabel(CharSequence label) {
+ mLabel = label;
+ return this;
+ }
+
+ public CharSequence getLabel() {
+ return mLabel;
+ }
+
+ public Builder setFileName(String fileName) {
+ mFileName = fileName;
+ return this;
+ }
+
+ public String getFileName() {
+ return mFileName;
+ }
+
+ public DummyBlobData build() {
+ return new DummyBlobData(this);
+ }
}
public void prepare() throws Exception {
diff --git a/tests/BlobStoreTestUtils/src/com/android/utils/blob/Utils.java b/tests/BlobStoreTestUtils/src/com/android/utils/blob/Utils.java
index c35385c..654c1e2 100644
--- a/tests/BlobStoreTestUtils/src/com/android/utils/blob/Utils.java
+++ b/tests/BlobStoreTestUtils/src/com/android/utils/blob/Utils.java
@@ -16,7 +16,13 @@
package com.android.utils.blob;
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.blob.BlobHandle;
import android.app.blob.BlobStoreManager;
+import android.app.blob.LeaseInfo;
+import android.content.Context;
+import android.content.res.Resources;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
@@ -56,4 +62,76 @@
copy(in, out, lengthBytes);
}
}
+
+ public static void assertLeasedBlobs(BlobStoreManager blobStoreManager,
+ BlobHandle... expectedBlobHandles) throws IOException {
+ assertThat(blobStoreManager.getLeasedBlobs()).containsExactly(expectedBlobHandles);
+ }
+
+ public static void assertNoLeasedBlobs(BlobStoreManager blobStoreManager)
+ throws IOException {
+ assertThat(blobStoreManager.getLeasedBlobs()).isEmpty();
+ }
+
+ public static void acquireLease(Context context,
+ BlobHandle blobHandle, CharSequence description) throws IOException {
+ final BlobStoreManager blobStoreManager = (BlobStoreManager) context.getSystemService(
+ Context.BLOB_STORE_SERVICE);
+ blobStoreManager.acquireLease(blobHandle, description);
+
+ final LeaseInfo leaseInfo = blobStoreManager.getLeaseInfo(blobHandle);
+ assertLeaseInfo(leaseInfo, context.getPackageName(), 0,
+ Resources.ID_NULL, description);
+ }
+
+ public static void acquireLease(Context context,
+ BlobHandle blobHandle, int descriptionResId) throws IOException {
+ final BlobStoreManager blobStoreManager = (BlobStoreManager) context.getSystemService(
+ Context.BLOB_STORE_SERVICE);
+ blobStoreManager.acquireLease(blobHandle, descriptionResId);
+
+ final LeaseInfo leaseInfo = blobStoreManager.getLeaseInfo(blobHandle);
+ assertLeaseInfo(leaseInfo, context.getPackageName(), 0,
+ descriptionResId, context.getString(descriptionResId));
+ }
+
+ public static void acquireLease(Context context,
+ BlobHandle blobHandle, CharSequence description,
+ long expiryTimeMs) throws IOException {
+ final BlobStoreManager blobStoreManager = (BlobStoreManager) context.getSystemService(
+ Context.BLOB_STORE_SERVICE);
+ blobStoreManager.acquireLease(blobHandle, description, expiryTimeMs);
+
+ final LeaseInfo leaseInfo = blobStoreManager.getLeaseInfo(blobHandle);
+ assertLeaseInfo(leaseInfo, context.getPackageName(), expiryTimeMs,
+ Resources.ID_NULL, description);
+ }
+
+ public static void acquireLease(Context context,
+ BlobHandle blobHandle, int descriptionResId,
+ long expiryTimeMs) throws IOException {
+ final BlobStoreManager blobStoreManager = (BlobStoreManager) context.getSystemService(
+ Context.BLOB_STORE_SERVICE);
+ blobStoreManager.acquireLease(blobHandle, descriptionResId, expiryTimeMs);
+
+ final LeaseInfo leaseInfo = blobStoreManager.getLeaseInfo(blobHandle);
+ assertLeaseInfo(leaseInfo, context.getPackageName(), expiryTimeMs,
+ descriptionResId, context.getString(descriptionResId));
+ }
+
+ public static void releaseLease(Context context,
+ BlobHandle blobHandle) throws IOException {
+ final BlobStoreManager blobStoreManager = (BlobStoreManager) context.getSystemService(
+ Context.BLOB_STORE_SERVICE);
+ blobStoreManager.releaseLease(blobHandle);
+ assertThat(blobStoreManager.getLeaseInfo(blobHandle)).isNull();
+ }
+
+ private static void assertLeaseInfo(LeaseInfo leaseInfo, String packageName,
+ long expiryTimeMs, int descriptionResId, CharSequence description) {
+ assertThat(leaseInfo.getPackageName()).isEqualTo(packageName);
+ assertThat(leaseInfo.getExpiryTimeMillis()).isEqualTo(expiryTimeMs);
+ assertThat(leaseInfo.getDescriptionResId()).isEqualTo(descriptionResId);
+ assertThat(leaseInfo.getDescription()).isEqualTo(description);
+ }
}
diff --git a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
index 61f3dba..4ecca2d 100644
--- a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
+++ b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java
@@ -78,13 +78,12 @@
return false;
}
String res = mTestDevice.executeShellCommand("kill -s SIGUSR1 " + pid).trim();
- assertTrue("kill SIGUSR1: " + res, res.length() == 0);
- return true;
+ return res.length() == 0;
}
@Test
public void testSystemServerProfile() throws Exception {
- final int numIterations = 20;
+ final int numIterations = 30;
String res;
// Set properties and wait for them to be readable.
for (int i = 1; i <= numIterations; ++i) {
diff --git a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java
index 339df93..475305e 100644
--- a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java
+++ b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java
@@ -32,7 +32,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -51,7 +51,7 @@
}
@DataClass.Generated.Member
- public HierrarchicalDataClassBase setBaseData(int value) {
+ public HierrarchicalDataClassBase setBaseData( int value) {
mBaseData = value;
return this;
}
@@ -98,8 +98,8 @@
};
@DataClass.Generated(
- time = 1574122837821L,
- codegenVersion = "1.0.14",
+ time = 1582685650576L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassBase.java",
inputSignatures = "private int mBaseData\nclass HierrarchicalDataClassBase extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genConstructor=false, genSetters=true)")
@Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java
index 69e06b2..150b324 100644
--- a/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java
+++ b/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java
@@ -46,7 +46,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -120,8 +120,8 @@
};
@DataClass.Generated(
- time = 1574122838768L,
- codegenVersion = "1.0.14",
+ time = 1582685651560L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/HierrarchicalDataClassChild.java",
inputSignatures = "private @android.annotation.NonNull java.lang.String mChildData\nclass HierrarchicalDataClassChild extends com.android.codegentest.HierrarchicalDataClassBase implements []\n@com.android.internal.util.DataClass(genParcelable=true, genConstructor=false, genSetters=true)")
@Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java b/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java
index ca128be..3087156 100644
--- a/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java
+++ b/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java
@@ -54,7 +54,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -355,7 +355,7 @@
}
@DataClass.Generated.Member
- public @NonNull Builder setNullableBoolean(@SuppressWarnings({ "WeakerAccess" }) @Nullable Boolean value) {
+ public @NonNull Builder setNullableBoolean(@SuppressWarnings({ "WeakerAccess" }) @NonNull Boolean value) {
checkNotUsed();
mBuilderFieldsSet |= 0x80;
mNullableBoolean = value;
@@ -412,8 +412,8 @@
}
@DataClass.Generated(
- time = 1574122836960L,
- codegenVersion = "1.0.14",
+ time = 1582685649678L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/ParcelAllTheThingsDataClass.java",
inputSignatures = " @android.annotation.NonNull java.lang.String[] mStringArray\n @android.annotation.NonNull int[] mIntArray\n @android.annotation.NonNull java.util.List<java.lang.String> mStringList\n @android.annotation.NonNull java.util.Map<java.lang.String,com.android.codegentest.SampleWithCustomBuilder> mMap\n @android.annotation.NonNull java.util.Map<java.lang.String,java.lang.String> mStringMap\n @android.annotation.NonNull android.util.SparseArray<com.android.codegentest.SampleWithCustomBuilder> mSparseArray\n @android.annotation.NonNull android.util.SparseIntArray mSparseIntArray\n @java.lang.SuppressWarnings({\"WeakerAccess\"}) @android.annotation.Nullable java.lang.Boolean mNullableBoolean\nclass ParcelAllTheThingsDataClass extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genAidl=false, genToString=true)")
@Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/SampleDataClass.java b/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
index c850bf8..8d421bf 100644
--- a/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
+++ b/tests/Codegen/src/com/android/codegentest/SampleDataClass.java
@@ -342,7 +342,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -512,7 +512,7 @@
@Nullable LinkAddress[] linkAddresses5,
@StringRes int stringRes,
@android.annotation.IntRange(from = 0, to = 6) int dayOfWeek,
- @Size(2) @NonNull @Each @FloatRange(from = 0f) float[] coords) {
+ @Size(2) @NonNull @FloatRange(from = 0f) float[] coords) {
this.mNum = num;
this.mNum2 = num2;
this.mNum4 = num4;
@@ -790,7 +790,7 @@
* @see AnnotationValidations#validate(Class, Size, int, String, int)
*/
@DataClass.Generated.Member
- public @Size(2) @NonNull @Each @FloatRange(from = 0f) float[] getCoords() {
+ public @Size(2) @NonNull @FloatRange(from = 0f) float[] getCoords() {
return mCoords;
}
@@ -820,7 +820,7 @@
* pieces in multiple places for each field.
*/
@DataClass.Generated.Member
- public SampleDataClass setNum(int value) {
+ public SampleDataClass setNum( int value) {
mNum = value;
return this;
}
@@ -832,7 +832,7 @@
* @see #mNum2 ..and so should blocks at the bottom, e.g. {@code @see} blocks.
*/
@DataClass.Generated.Member
- public SampleDataClass setNum2(int value) {
+ public SampleDataClass setNum2( int value) {
mNum2 = value;
return this;
}
@@ -846,7 +846,7 @@
* @hide
*/
@DataClass.Generated.Member
- public SampleDataClass setNum4(int value) {
+ public SampleDataClass setNum4( int value) {
mNum4 = value;
return this;
}
@@ -855,7 +855,7 @@
* {@link Nullable} or {@link NonNull} annotation is required on all non-primitive fields.
*/
@DataClass.Generated.Member
- public SampleDataClass setName(@Nullable String value) {
+ public SampleDataClass setName(@NonNull String value) {
mName = value;
return this;
}
@@ -892,7 +892,7 @@
* E.g. {@link Parcelable} subclasses, {@link String}, {@link int}, {@link boolean}, etc.
*/
@DataClass.Generated.Member
- public SampleDataClass setOtherParcelable(@Nullable AccessibilityNodeInfo value) {
+ public SampleDataClass setOtherParcelable(@NonNull AccessibilityNodeInfo value) {
mOtherParcelable = value;
return this;
}
@@ -957,7 +957,7 @@
* @see Builder#setLinkAddresses4(LinkAddress...)
*/
@DataClass.Generated.Member
- public SampleDataClass setLinkAddresses4(@Nullable LinkAddress... value) {
+ public SampleDataClass setLinkAddresses4(@NonNull LinkAddress... value) {
mLinkAddresses4 = value;
return this;
}
@@ -1070,7 +1070,7 @@
* @see AnnotationValidations#validate(Class, Size, int, String, int)
*/
@DataClass.Generated.Member
- public SampleDataClass setCoords(@Size(2) @NonNull @Each @FloatRange(from = 0f) float... value) {
+ public SampleDataClass setCoords(@Size(2) @NonNull @FloatRange(from = 0f) float... value) {
mCoords = value;
AnnotationValidations.validate(
Size.class, null, mCoords.length,
@@ -1451,7 +1451,7 @@
private @Nullable LinkAddress[] mLinkAddresses5;
private @StringRes int mStringRes;
private @android.annotation.IntRange(from = 0, to = 6) int mDayOfWeek;
- private @Size(2) @NonNull @Each @FloatRange(from = 0f) float[] mCoords;
+ private @Size(2) @NonNull @FloatRange(from = 0f) float[] mCoords;
private long mBuilderFieldsSet = 0L;
@@ -1549,7 +1549,7 @@
* {@link Nullable} or {@link NonNull} annotation is required on all non-primitive fields.
*/
@DataClass.Generated.Member
- public @NonNull Builder setName(@Nullable String value) {
+ public @NonNull Builder setName(@NonNull String value) {
checkNotUsed();
mBuilderFieldsSet |= 0x8;
mName = value;
@@ -1588,7 +1588,7 @@
* E.g. {@link Parcelable} subclasses, {@link String}, {@link int}, {@link boolean}, etc.
*/
@DataClass.Generated.Member
- public @NonNull Builder setOtherParcelable(@Nullable AccessibilityNodeInfo value) {
+ public @NonNull Builder setOtherParcelable(@NonNull AccessibilityNodeInfo value) {
checkNotUsed();
mBuilderFieldsSet |= 0x40;
mOtherParcelable = value;
@@ -1674,7 +1674,7 @@
* @see Builder#setLinkAddresses4(LinkAddress...)
*/
@DataClass.Generated.Member
- public @NonNull Builder setLinkAddresses4(@Nullable LinkAddress... value) {
+ public @NonNull Builder setLinkAddresses4(@NonNull LinkAddress... value) {
checkNotUsed();
mBuilderFieldsSet |= 0x800;
mLinkAddresses4 = value;
@@ -1733,7 +1733,7 @@
* Final fields suppress generating a setter (when setters are requested).
*/
@DataClass.Generated.Member
- public @NonNull Builder setLinkAddresses5(@Nullable LinkAddress... value) {
+ public @NonNull Builder setLinkAddresses5(@NonNull LinkAddress... value) {
checkNotUsed();
mBuilderFieldsSet |= 0x10000;
mLinkAddresses5 = value;
@@ -1785,7 +1785,7 @@
* @see AnnotationValidations#validate(Class, Size, int, String, int)
*/
@DataClass.Generated.Member
- public @NonNull Builder setCoords(@Size(2) @NonNull @Each @FloatRange(from = 0f) float... value) {
+ public @NonNull Builder setCoords(@Size(2) @NonNull @FloatRange(from = 0f) float... value) {
checkNotUsed();
mBuilderFieldsSet |= 0x80000;
mCoords = value;
@@ -1872,8 +1872,8 @@
}
@DataClass.Generated(
- time = 1574122835009L,
- codegenVersion = "1.0.14",
+ time = 1582685647656L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleDataClass.java",
inputSignatures = "public static final java.lang.String STATE_NAME_UNDEFINED\npublic static final java.lang.String STATE_NAME_ON\npublic static final java.lang.String STATE_NAME_OFF\npublic static final int STATE_UNDEFINED\npublic static final int STATE_ON\npublic static final int STATE_OFF\npublic static final @com.android.codegentest.SampleDataClass.RequestFlags int FLAG_MANUAL_REQUEST\npublic static final @com.android.codegentest.SampleDataClass.RequestFlags int FLAG_COMPATIBILITY_MODE_REQUEST\npublic static final @com.android.codegentest.SampleDataClass.RequestFlags int FLAG_AUGMENTED_REQUEST\nprivate int mNum\nprivate int mNum2\nprivate int mNum4\nprivate @android.annotation.Nullable java.lang.String mName\nprivate @android.annotation.NonNull java.lang.String mName2\nprivate @android.annotation.NonNull java.lang.String mName4\nprivate @android.annotation.Nullable android.view.accessibility.AccessibilityNodeInfo mOtherParcelable\nprivate @com.android.internal.util.DataClass.ParcelWith(com.android.codegentest.MyDateParcelling.class) @android.annotation.NonNull java.util.Date mDate\nprivate @com.android.internal.util.DataClass.ParcelWith(com.android.internal.util.Parcelling.BuiltIn.ForPattern.class) @android.annotation.NonNull java.util.regex.Pattern mPattern\nprivate @android.annotation.NonNull java.util.List<android.net.LinkAddress> mLinkAddresses2\nprivate @com.android.internal.util.DataClass.PluralOf(\"linkAddress\") @android.annotation.NonNull java.util.ArrayList<android.net.LinkAddress> mLinkAddresses\nprivate @android.annotation.Nullable android.net.LinkAddress[] mLinkAddresses4\nprivate @com.android.codegentest.SampleDataClass.StateName @android.annotation.NonNull java.lang.String mStateName\nprivate @com.android.codegentest.SampleDataClass.RequestFlags int mFlags\nprivate @com.android.codegentest.SampleDataClass.State int mState\npublic @android.annotation.NonNull java.lang.CharSequence charSeq\nprivate final @android.annotation.Nullable android.net.LinkAddress[] mLinkAddresses5\nprivate transient android.net.LinkAddress[] mLinkAddresses6\ntransient int[] mTmpStorage\nprivate @android.annotation.StringRes int mStringRes\nprivate @android.annotation.IntRange(from=0L, to=6L) int mDayOfWeek\nprivate @android.annotation.Size(2L) @android.annotation.NonNull @com.android.internal.util.DataClass.Each @android.annotation.FloatRange(from=0.0) float[] mCoords\nprivate static java.lang.String defaultName4()\nprivate int[] lazyInitTmpStorage()\npublic android.net.LinkAddress[] getLinkAddresses4()\nprivate boolean patternEquals(java.util.regex.Pattern)\nprivate int patternHashCode()\nprivate void onConstructed()\npublic void dump(java.io.PrintWriter)\nclass SampleDataClass extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genConstructor=true, genEqualsHashCode=true, genToString=true, genForEachField=true, genSetters=true)")
@Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java b/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
index 2de848c..d9fe1fd 100644
--- a/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
+++ b/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java
@@ -85,7 +85,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -253,8 +253,8 @@
}
@DataClass.Generated(
- time = 1574122835982L,
- codegenVersion = "1.0.14",
+ time = 1582685648622L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithCustomBuilder.java",
inputSignatures = " long delayAmount\n @android.annotation.NonNull java.util.concurrent.TimeUnit delayUnit\n long creationTimestamp\nprivate static java.util.concurrent.TimeUnit unparcelDelayUnit(android.os.Parcel)\nprivate void parcelDelayUnit(android.os.Parcel,int)\nclass SampleWithCustomBuilder extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genBuilder=true, genAidl=false, genToString=true)\nabstract com.android.codegentest.SampleWithCustomBuilder.Builder setDelayAmount(long)\npublic abstract com.android.codegentest.SampleWithCustomBuilder.Builder setDelayUnit(java.util.concurrent.TimeUnit)\npublic com.android.codegentest.SampleWithCustomBuilder.Builder setDelay(long,java.util.concurrent.TimeUnit)\nclass BaseBuilder extends java.lang.Object implements []")
@Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java b/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java
index 0deffe4..f98d7b0 100644
--- a/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java
+++ b/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java
@@ -36,7 +36,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -135,8 +135,8 @@
};
@DataClass.Generated(
- time = 1574122840588L,
- codegenVersion = "1.0.14",
+ time = 1582685653406L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java",
inputSignatures = " @android.annotation.NonNull java.lang.String mBar\nclass NestedDataClass extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true)")
@Deprecated
@@ -160,7 +160,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -259,8 +259,8 @@
};
@DataClass.Generated(
- time = 1574122840597L,
- codegenVersion = "1.0.14",
+ time = 1582685653415L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java",
inputSignatures = " @android.annotation.NonNull long mBaz2\nclass NestedDataClass3 extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true)")
@Deprecated
@@ -274,7 +274,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -373,8 +373,8 @@
};
@DataClass.Generated(
- time = 1574122840608L,
- codegenVersion = "1.0.14",
+ time = 1582685653420L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/SampleWithNestedDataClasses.java",
inputSignatures = " @android.annotation.NonNull java.lang.String mBaz\nclass NestedDataClass2 extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genEqualsHashCode=true)")
@Deprecated
diff --git a/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java b/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java
index 712722b..6b4fc2f 100644
--- a/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java
+++ b/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java
@@ -51,7 +51,7 @@
- // Code below generated by codegen v1.0.14.
+ // Code below generated by codegen v1.0.15.
//
// DO NOT MODIFY!
// CHECKSTYLE:OFF Generated code
@@ -65,8 +65,8 @@
@DataClass.Generated(
- time = 1574122839646L,
- codegenVersion = "1.0.14",
+ time = 1582685652436L,
+ codegenVersion = "1.0.15",
sourceFile = "frameworks/base/tests/Codegen/src/com/android/codegentest/StaleDataclassDetectorFalsePositivesTest.java",
inputSignatures = "public @android.annotation.NonNull java.lang.String someMethod(int)\nclass StaleDataclassDetectorFalsePositivesTest extends java.lang.Object implements []\n@com.android.internal.util.DataClass(genConstructor=false, genBuilder=false)")
@Deprecated
diff --git a/tests/MemoryUsage/src/com/android/tests/memoryusage/MemoryUsageTest.java b/tests/MemoryUsage/src/com/android/tests/memoryusage/MemoryUsageTest.java
index 5904916..c7e5a5e 100644
--- a/tests/MemoryUsage/src/com/android/tests/memoryusage/MemoryUsageTest.java
+++ b/tests/MemoryUsage/src/com/android/tests/memoryusage/MemoryUsageTest.java
@@ -322,7 +322,7 @@
mAtm.startActivityAndWait(null,
getInstrumentation().getContext().getBasePackageName(),
- getInstrumentation().getContext().getFeatureId(), mLaunchIntent,
+ getInstrumentation().getContext().getAttributionTag(), mLaunchIntent,
mimeType, null, null, 0, mLaunchIntent.getFlags(), null, null,
UserHandle.USER_CURRENT_OR_SELF);
} catch (RemoteException e) {
diff --git a/tests/PackageWatchdog/src/com/android/server/ExplicitHealthCheckServiceTest.java b/tests/PackageWatchdog/src/com/android/server/ExplicitHealthCheckServiceTest.java
new file mode 100644
index 0000000..2fbfeba
--- /dev/null
+++ b/tests/PackageWatchdog/src/com/android/server/ExplicitHealthCheckServiceTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2020 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;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.RemoteCallback;
+import android.service.watchdog.ExplicitHealthCheckService;
+import android.service.watchdog.IExplicitHealthCheckService;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.concurrent.CountDownLatch;
+
+public class ExplicitHealthCheckServiceTest {
+
+ private ExplicitHealthCheckService mExplicitHealthCheckService;
+ private static final String PACKAGE_NAME = "com.test.package";
+
+ @Before
+ public void setup() throws Exception {
+ mExplicitHealthCheckService = spy(ExplicitHealthCheckService.class);
+ }
+
+ /**
+ * Test to verify that the correct information is sent in the callback when a package has
+ * passed an explicit health check.
+ */
+ @Test
+ public void testNotifyHealthCheckPassed() throws Exception {
+ IBinder binder = mExplicitHealthCheckService.onBind(new Intent());
+ CountDownLatch countDownLatch = new CountDownLatch(1);
+ RemoteCallback callback = new RemoteCallback(result -> {
+ assertThat(result.get(ExplicitHealthCheckService.EXTRA_HEALTH_CHECK_PASSED_PACKAGE))
+ .isEqualTo(PACKAGE_NAME);
+ countDownLatch.countDown();
+ });
+ IExplicitHealthCheckService.Stub.asInterface(binder).setCallback(callback);
+ mExplicitHealthCheckService.notifyHealthCheckPassed(PACKAGE_NAME);
+ countDownLatch.await();
+ }
+}
diff --git a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
index 8cc8cf4..dfaac2c 100644
--- a/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
+++ b/tests/PackageWatchdog/src/com/android/server/PackageWatchdogTest.java
@@ -1063,6 +1063,20 @@
assertThat(bootObserver2.mitigatedBootLoop()).isFalse();
}
+ /**
+ * Ensure that passing a null list of failed packages does not cause any mitigation logic to
+ * execute.
+ */
+ @Test
+ public void testNullFailedPackagesList() {
+ PackageWatchdog watchdog = createWatchdog();
+ TestObserver observer1 = new TestObserver(OBSERVER_NAME_1);
+ watchdog.startObservingHealth(observer1, List.of(APP_A), LONG_DURATION);
+
+ raiseFatalFailureAndDispatch(watchdog, null, PackageWatchdog.FAILURE_REASON_APP_CRASH);
+ assertThat(observer1.mMitigatedPackages).isEmpty();
+ }
+
private void adoptShellPermissions(String... permissions) {
InstrumentationRegistry
.getInstrumentation()
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
index 70be83f..a616c61 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/StagedRollbackTest.java
@@ -127,18 +127,12 @@
/**
* Test rollbacks of staged installs involving only apks with bad update.
- * Trigger rollback phase. This is expected to fail due to watchdog
- * rebooting the test out from under it.
+ * Trigger rollback phase.
*/
@Test
public void testBadApkOnly_Phase3() throws Exception {
// One more crash to trigger rollback
RollbackUtils.sendCrashBroadcast(TestApp.A, 1);
-
- // We expect the device to be rebooted automatically. Wait for that to happen.
- // This device method will fail and the host will catch the assertion.
- // If reboot doesn't happen, the host will fail the assertion.
- Thread.sleep(TimeUnit.SECONDS.toMillis(120));
}
/**
diff --git a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
index 4afebb5..282f012 100644
--- a/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
+++ b/tests/RollbackTest/StagedRollbackTest/src/com/android/tests/rollback/host/StagedRollbackTest.java
@@ -22,7 +22,6 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
-import static org.testng.Assert.assertThrows;
import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
@@ -136,7 +135,10 @@
getDevice().reboot();
runPhase("testBadApkOnly_Phase2");
- assertThrows(AssertionError.class, () -> runPhase("testBadApkOnly_Phase3"));
+ // Trigger rollback and wait for reboot to happen
+ runPhase("testBadApkOnly_Phase3");
+ assertTrue(getDevice().waitForDeviceNotAvailable(TimeUnit.MINUTES.toMillis(2)));
+
getDevice().waitForDeviceAvailable();
runPhase("testBadApkOnly_Phase4");
diff --git a/tests/SurfaceControlViewHostTest/src/com/android/test/viewembed/SurfaceControlViewHostTest.java b/tests/SurfaceControlViewHostTest/src/com/android/test/viewembed/SurfaceControlViewHostTest.java
index 6169671..3bc5309 100644
--- a/tests/SurfaceControlViewHostTest/src/com/android/test/viewembed/SurfaceControlViewHostTest.java
+++ b/tests/SurfaceControlViewHostTest/src/com/android/test/viewembed/SurfaceControlViewHostTest.java
@@ -66,7 +66,7 @@
WindowManager.LayoutParams lp =
new WindowManager.LayoutParams(500, 500, WindowManager.LayoutParams.TYPE_APPLICATION,
0, PixelFormat.OPAQUE);
- mVr.addView(v, lp);
+ mVr.setView(v, lp);
}
@Override
diff --git a/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerMultiWindowTest.java b/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerMultiWindowTest.java
index 8f7bebb..6eb4587 100644
--- a/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerMultiWindowTest.java
+++ b/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerMultiWindowTest.java
@@ -139,7 +139,7 @@
mTaskView2.reparentTask(ti.token);
}
}
- public void taskVanished(IWindowContainer wc) {
+ public void taskVanished(ActivityManager.RunningTaskInfo ti) {
}
public void transactionReady(int id, SurfaceControl.Transaction t) {
mergedTransaction.merge(t);
diff --git a/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerPipTest.java b/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerPipTest.java
index bd17751..ade5c2e 100644
--- a/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerPipTest.java
+++ b/tests/TaskOrganizerTest/src/com/android/test/taskembed/TaskOrganizerPipTest.java
@@ -49,7 +49,7 @@
} catch (Exception e) {
}
}
- public void taskVanished(IWindowContainer wc) {
+ public void taskVanished(ActivityManager.RunningTaskInfo ti) {
}
public void transactionReady(int id, SurfaceControl.Transaction t) {
}
diff --git a/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/WindowInsetsActivity.java b/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/WindowInsetsActivity.java
index 8e6f198..f254e4d 100644
--- a/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/WindowInsetsActivity.java
+++ b/tests/WindowInsetsTests/src/com/google/android/test/windowinsetstests/WindowInsetsActivity.java
@@ -16,11 +16,15 @@
package com.google.android.test.windowinsetstests;
+import static android.view.WindowInsets.Type.ime;
import static android.view.WindowInsetsAnimation.Callback.DISPATCH_MODE_STOP;
import static java.lang.Math.max;
import static java.lang.Math.min;
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ValueAnimator;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
@@ -30,13 +34,13 @@
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
-import android.view.Window;
import android.view.WindowInsets;
-import android.view.WindowInsets.Type;
import android.view.WindowInsetsAnimation;
import android.view.WindowInsetsAnimation.Callback;
import android.view.WindowInsetsAnimationControlListener;
import android.view.WindowInsetsAnimationController;
+import android.view.WindowInsetsController;
+import android.view.WindowInsetsController.OnControllableInsetsChangedListener;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
@@ -82,8 +86,8 @@
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDown = event.getY();
- mDownInsets = v.getRootWindowInsets().getInsets(Type.ime());
- mShownAtDown = v.getRootWindowInsets().isVisible(Type.ime());
+ mDownInsets = v.getRootWindowInsets().getInsets(ime());
+ mShownAtDown = v.getRootWindowInsets().isVisible(ime());
mRequestedController = false;
mCurrentRequest = null;
break;
@@ -94,8 +98,8 @@
> mViewConfiguration.getScaledTouchSlop()
&& !mRequestedController) {
mRequestedController = true;
- v.getWindowInsetsController().controlWindowInsetsAnimation(Type.ime(),
- 1000, new LinearInterpolator(),
+ v.getWindowInsetsController().controlWindowInsetsAnimation(ime(),
+ 1000, new LinearInterpolator(), null /* cancellationSignal */,
mCurrentRequest = new WindowInsetsAnimationControlListener() {
@Override
public void onReady(
@@ -189,6 +193,51 @@
getWindow().getDecorView().post(() -> getWindow().setDecorFitsSystemWindows(false));
}
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ getWindow().getInsetsController().addOnControllableInsetsChangedListener(
+ new OnControllableInsetsChangedListener() {
+
+ boolean hasControl = false;
+ @Override
+ public void onControllableInsetsChanged(WindowInsetsController controller,
+ int types) {
+ if ((types & ime()) != 0 && !hasControl) {
+ hasControl = true;
+ controller.controlWindowInsetsAnimation(ime(), -1,
+ new LinearInterpolator(), null /* cancellationSignal */,
+ new WindowInsetsAnimationControlListener() {
+ @Override
+ public void onReady(
+ WindowInsetsAnimationController controller,
+ int types) {
+ ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
+ anim.setDuration(1500);
+ anim.addUpdateListener(animation
+ -> controller.setInsetsAndAlpha(
+ controller.getShownStateInsets(),
+ (float) animation.getAnimatedValue(),
+ anim.getAnimatedFraction()));
+ anim.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ super.onAnimationEnd(animation);
+ controller.finish(true);
+ }
+ });
+ anim.start();
+ }
+
+ @Override
+ public void onCancelled() {
+ }
+ });
+ }
+ }
+ });
+ }
+
static class Transition {
private int mEndBottom;
private int mStartBottom;
@@ -200,7 +249,7 @@
}
void onPrepare(WindowInsetsAnimation animation) {
- if ((animation.getTypeMask() & Type.ime()) != 0) {
+ if ((animation.getTypeMask() & ime()) != 0) {
mInsetsAnimation = animation;
}
mStartBottom = mView.getBottom();
diff --git a/tests/net/common/java/android/net/CaptivePortalTest.java b/tests/net/common/java/android/net/CaptivePortalTest.java
index ca4ba63..7a60cc1 100644
--- a/tests/net/common/java/android/net/CaptivePortalTest.java
+++ b/tests/net/common/java/android/net/CaptivePortalTest.java
@@ -18,19 +18,26 @@
import static org.junit.Assert.assertEquals;
+import android.os.Build;
import android.os.RemoteException;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.testutils.DevSdkIgnoreRule;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class CaptivePortalTest {
+ @Rule
+ public final DevSdkIgnoreRule ignoreRule = new DevSdkIgnoreRule();
+
private static final int DEFAULT_TIMEOUT_MS = 5000;
private static final String TEST_PACKAGE_NAME = "com.google.android.test";
@@ -84,6 +91,7 @@
assertEquals(result.mCode, CaptivePortal.APP_RETURN_WANTED_AS_IS);
}
+ @IgnoreUpTo(Build.VERSION_CODES.Q)
@Test
public void testReevaluateNetwork() {
final MyCaptivePortalImpl result = runCaptivePortalTest(c -> c.reevaluateNetwork());
diff --git a/tests/net/common/java/android/net/LinkAddressTest.java b/tests/net/common/java/android/net/LinkAddressTest.java
index 06c6301..c74c112 100644
--- a/tests/net/common/java/android/net/LinkAddressTest.java
+++ b/tests/net/common/java/android/net/LinkAddressTest.java
@@ -28,8 +28,8 @@
import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
import static com.android.testutils.MiscAssertsKt.assertEqualBothWays;
+import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals;
import static com.android.testutils.MiscAssertsKt.assertNotEqualEitherWay;
-import static com.android.testutils.ParcelUtilsKt.assertParcelSane;
import static com.android.testutils.ParcelUtilsKt.assertParcelingIsLossless;
import static org.junit.Assert.assertEquals;
@@ -38,11 +38,17 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import android.os.Build;
import android.os.SystemClock;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
+import com.android.testutils.DevSdkIgnoreRule;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
+
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -57,6 +63,8 @@
@RunWith(AndroidJUnit4.class)
@SmallTest
public class LinkAddressTest {
+ @Rule
+ public final DevSdkIgnoreRule ignoreRule = new DevSdkIgnoreRule();
private static final String V4 = "192.0.2.1";
private static final String V6 = "2001:db8::1";
@@ -318,15 +326,29 @@
l = new LinkAddress(V6_ADDRESS, 64, 123, 456);
assertParcelingIsLossless(l);
- l = new LinkAddress(V6_ADDRESS, 64, 123, 456,
- 1L, 3600000L);
- assertParcelingIsLossless(l);
l = new LinkAddress(V4 + "/28", IFA_F_PERMANENT, RT_SCOPE_LINK);
- assertParcelSane(l, 6);
+ assertParcelingIsLossless(l);
}
- @Test
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ public void testLifetimeParceling() {
+ final LinkAddress l = new LinkAddress(V6_ADDRESS, 64, 123, 456, 1L, 3600000L);
+ assertParcelingIsLossless(l);
+ }
+
+ @Test @IgnoreAfter(Build.VERSION_CODES.Q)
+ public void testFieldCount_Q() {
+ assertFieldCountEquals(4, LinkAddress.class);
+ }
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ public void testFieldCount() {
+ // Make sure any new field is covered by the above parceling tests when changing this number
+ assertFieldCountEquals(6, LinkAddress.class);
+ }
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
public void testDeprecationTime() {
try {
new LinkAddress(V6_ADDRESS, 64, 0, 456,
@@ -345,9 +367,12 @@
-2, 100000L);
fail("negative deprecation time should cause exception");
} catch (IllegalArgumentException expected) { }
+
+ LinkAddress addr = new LinkAddress(V6_ADDRESS, 64, 0, 456, 100000L, 200000L);
+ assertEquals(100000L, addr.getDeprecationTime());
}
- @Test
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
public void testExpirationTime() {
try {
new LinkAddress(V6_ADDRESS, 64, 0, 456,
@@ -360,16 +385,22 @@
100000L, -2);
fail("negative expiration time should cause exception");
} catch (IllegalArgumentException expected) { }
+
+ LinkAddress addr = new LinkAddress(V6_ADDRESS, 64, 0, 456, 100000L, 200000L);
+ assertEquals(200000L, addr.getExpirationTime());
}
@Test
public void testGetFlags() {
LinkAddress l = new LinkAddress(V6_ADDRESS, 64, 123, RT_SCOPE_HOST);
assertEquals(123, l.getFlags());
+ }
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ public void testGetFlags_Deprecation() {
// Test if deprecated bit was added/remove automatically based on the provided deprecation
// time
- l = new LinkAddress(V6_ADDRESS, 64, 0, RT_SCOPE_HOST,
+ LinkAddress l = new LinkAddress(V6_ADDRESS, 64, 0, RT_SCOPE_HOST,
1L, LinkAddress.LIFETIME_PERMANENT);
// Check if the flag is added automatically.
assertTrue((l.getFlags() & IFA_F_DEPRECATED) != 0);
@@ -458,8 +489,11 @@
(IFA_F_TEMPORARY|IFA_F_TENTATIVE|IFA_F_OPTIMISTIC),
RT_SCOPE_UNIVERSE);
assertGlobalPreferred(l, "v6,global,tempaddr+optimistic");
+ }
- l = new LinkAddress(V6_ADDRESS, 64, IFA_F_DEPRECATED,
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ public void testIsGlobalPreferred_DeprecatedInFuture() {
+ final LinkAddress l = new LinkAddress(V6_ADDRESS, 64, IFA_F_DEPRECATED,
RT_SCOPE_UNIVERSE, SystemClock.elapsedRealtime() + 100000,
SystemClock.elapsedRealtime() + 200000);
// Although the deprecated bit is set, but the deprecation time is in the future, test
diff --git a/tests/net/common/java/android/net/LinkPropertiesTest.java b/tests/net/common/java/android/net/LinkPropertiesTest.java
index f25fd4d..48b65e5 100644
--- a/tests/net/common/java/android/net/LinkPropertiesTest.java
+++ b/tests/net/common/java/android/net/LinkPropertiesTest.java
@@ -315,7 +315,7 @@
source.addDnsServer(DNS1);
source.addDnsServer(DNS2);
// set 2 gateways
- source.addRoute(new RouteInfo(GATEWAY1));
+ source.addRoute(new RouteInfo(LINKADDRV4, GATEWAY1));
source.addRoute(new RouteInfo(GATEWAY2));
source.setMtu(MTU);
@@ -327,7 +327,7 @@
target.addDnsServer(DNS2);
target.addDnsServer(DNS1);
target.addRoute(new RouteInfo(GATEWAY2));
- target.addRoute(new RouteInfo(GATEWAY1));
+ target.addRoute(new RouteInfo(LINKADDRV4, GATEWAY1));
target.setMtu(MTU);
assertLinkPropertiesEqual(source, target);
@@ -364,12 +364,13 @@
@Test
public void testRouteInterfaces() {
- LinkAddress prefix = new LinkAddress(address("2001:db8::"), 32);
+ LinkAddress prefix1 = new LinkAddress(address("2001:db8:1::"), 48);
+ LinkAddress prefix2 = new LinkAddress(address("2001:db8:2::"), 48);
InetAddress address = ADDRV6;
// Add a route with no interface to a LinkProperties with no interface. No errors.
LinkProperties lp = new LinkProperties();
- RouteInfo r = new RouteInfo(prefix, address, null);
+ RouteInfo r = new RouteInfo(prefix1, address, null);
assertTrue(lp.addRoute(r));
assertEquals(1, lp.getRoutes().size());
assertAllRoutesHaveInterface(null, lp);
@@ -379,7 +380,7 @@
assertEquals(1, lp.getRoutes().size());
// Add a route with an interface. Expect an exception.
- r = new RouteInfo(prefix, address, "wlan0");
+ r = new RouteInfo(prefix2, address, "wlan0");
try {
lp.addRoute(r);
fail("Adding wlan0 route to LP with no interface, expect exception");
@@ -398,7 +399,7 @@
} catch (IllegalArgumentException expected) {}
// If the interface name matches, the route is added.
- r = new RouteInfo(prefix, null, "wlan0");
+ r = new RouteInfo(prefix2, null, "wlan0");
lp.setInterfaceName("wlan0");
lp.addRoute(r);
assertEquals(2, lp.getRoutes().size());
@@ -423,10 +424,12 @@
assertEquals(3, lp.compareAllRoutes(lp2).added.size());
assertEquals(3, lp.compareAllRoutes(lp2).removed.size());
- // Check remove works
- lp.removeRoute(new RouteInfo(prefix, address, null));
+ // Remove route with incorrect interface, no route removed.
+ lp.removeRoute(new RouteInfo(prefix2, null, null));
assertEquals(3, lp.getRoutes().size());
- lp.removeRoute(new RouteInfo(prefix, address, "wlan0"));
+
+ // Check remove works when interface is correct.
+ lp.removeRoute(new RouteInfo(prefix2, null, "wlan0"));
assertEquals(2, lp.getRoutes().size());
assertAllRoutesHaveInterface("wlan0", lp);
assertAllRoutesNotHaveInterface("p2p0", lp);
diff --git a/tests/net/common/java/android/net/NetworkAgentConfigTest.kt b/tests/net/common/java/android/net/NetworkAgentConfigTest.kt
index d250ad3..de65ba2 100644
--- a/tests/net/common/java/android/net/NetworkAgentConfigTest.kt
+++ b/tests/net/common/java/android/net/NetworkAgentConfigTest.kt
@@ -16,16 +16,26 @@
package android.net
+import android.os.Build
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
+import com.android.testutils.DevSdkIgnoreRule
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
import com.android.testutils.assertParcelSane
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class NetworkAgentConfigTest {
- @Test
+ @Rule @JvmField
+ val ignoreRule = DevSdkIgnoreRule()
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
fun testParcelNetworkAgentConfig() {
val config = NetworkAgentConfig.Builder().apply {
setExplicitlySelected(true)
@@ -36,4 +46,27 @@
}.build()
assertParcelSane(config, 9)
}
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ fun testBuilder() {
+ val config = NetworkAgentConfig.Builder().apply {
+ setExplicitlySelected(true)
+ setLegacyType(ConnectivityManager.TYPE_ETHERNET)
+ setSubscriberId("MySubId")
+ setPartialConnectivityAcceptable(false)
+ setUnvalidatedConnectivityAcceptable(true)
+ setLegacyTypeName("TEST_NETWORK")
+ disableNat64Detection()
+ disableProvisioningNotification()
+ }.build()
+
+ assertTrue(config.isExplicitlySelected())
+ assertEquals(ConnectivityManager.TYPE_ETHERNET, config.getLegacyType())
+ assertEquals("MySubId", config.getSubscriberId())
+ assertFalse(config.isPartialConnectivityAcceptable())
+ assertTrue(config.isUnvalidatedConnectivityAcceptable())
+ assertEquals("TEST_NETWORK", config.getLegacyTypeName())
+ assertFalse(config.isNat64DetectionEnabled())
+ assertFalse(config.isProvisioningNotificationEnabled())
+ }
}
diff --git a/tests/net/common/java/android/net/NetworkScoreTest.kt b/tests/net/common/java/android/net/NetworkScoreTest.kt
deleted file mode 100644
index 30836b7..0000000
--- a/tests/net/common/java/android/net/NetworkScoreTest.kt
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2019 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.net
-
-import android.os.Parcelable
-import androidx.test.filters.SmallTest
-import androidx.test.runner.AndroidJUnit4
-import com.android.testutils.assertParcelSane
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertNotEquals
-import org.junit.Assert.assertTrue
-import org.junit.Test
-import org.junit.runner.RunWith
-
-private const val TEST_SCORE = 80
-private const val KEY_DEFAULT_CAPABILITIES = "DEFAULT_CAPABILITIES"
-
-@RunWith(AndroidJUnit4::class)
-@SmallTest
-class NetworkScoreTest {
- @Test
- fun testParcelNetworkScore() {
- val networkScore = NetworkScore()
- val defaultCap = NetworkCapabilities()
- networkScore.putExtension(KEY_DEFAULT_CAPABILITIES, defaultCap)
- assertEquals(defaultCap, networkScore.getExtension(KEY_DEFAULT_CAPABILITIES))
- networkScore.putIntExtension(NetworkScore.LEGACY_SCORE, TEST_SCORE)
- assertEquals(TEST_SCORE, networkScore.getIntExtension(NetworkScore.LEGACY_SCORE))
- assertParcelSane(networkScore, 1)
- }
-
- @Test
- fun testNullKeyAndValue() {
- val networkScore = NetworkScore()
- val defaultCap = NetworkCapabilities()
- networkScore.putIntExtension(null, TEST_SCORE)
- assertEquals(TEST_SCORE, networkScore.getIntExtension(null))
- networkScore.putExtension(null, defaultCap)
- assertEquals(defaultCap, networkScore.getExtension(null))
- networkScore.putExtension(null, null)
- val result: Parcelable? = networkScore.getExtension(null)
- assertEquals(null, result)
- }
-
- @Test
- fun testRemoveExtension() {
- val networkScore = NetworkScore()
- val defaultCap = NetworkCapabilities()
- networkScore.putExtension(KEY_DEFAULT_CAPABILITIES, defaultCap)
- networkScore.putIntExtension(NetworkScore.LEGACY_SCORE, TEST_SCORE)
- assertEquals(defaultCap, networkScore.getExtension(KEY_DEFAULT_CAPABILITIES))
- assertEquals(TEST_SCORE, networkScore.getIntExtension(NetworkScore.LEGACY_SCORE))
- networkScore.removeExtension(KEY_DEFAULT_CAPABILITIES)
- networkScore.removeExtension(NetworkScore.LEGACY_SCORE)
- val result: Parcelable? = networkScore.getExtension(KEY_DEFAULT_CAPABILITIES)
- assertEquals(null, result)
- assertEquals(0, networkScore.getIntExtension(NetworkScore.LEGACY_SCORE))
- }
-
- @Test
- fun testEqualsNetworkScore() {
- val ns1 = NetworkScore()
- val ns2 = NetworkScore()
- assertTrue(ns1.equals(ns2))
- assertEquals(ns1.hashCode(), ns2.hashCode())
-
- ns1.putIntExtension(NetworkScore.LEGACY_SCORE, TEST_SCORE)
- assertFalse(ns1.equals(ns2))
- assertNotEquals(ns1.hashCode(), ns2.hashCode())
- ns2.putIntExtension(NetworkScore.LEGACY_SCORE, TEST_SCORE)
- assertTrue(ns1.equals(ns2))
- assertEquals(ns1.hashCode(), ns2.hashCode())
-
- val defaultCap = NetworkCapabilities()
- ns1.putExtension(KEY_DEFAULT_CAPABILITIES, defaultCap)
- assertFalse(ns1.equals(ns2))
- assertNotEquals(ns1.hashCode(), ns2.hashCode())
- ns2.putExtension(KEY_DEFAULT_CAPABILITIES, defaultCap)
- assertTrue(ns1.equals(ns2))
- assertEquals(ns1.hashCode(), ns2.hashCode())
-
- ns1.putIntExtension(null, 10)
- assertFalse(ns1.equals(ns2))
- assertNotEquals(ns1.hashCode(), ns2.hashCode())
- ns2.putIntExtension(null, 10)
- assertTrue(ns1.equals(ns2))
- assertEquals(ns1.hashCode(), ns2.hashCode())
- }
-}
diff --git a/tests/net/common/java/android/net/RouteInfoTest.java b/tests/net/common/java/android/net/RouteInfoTest.java
index fe51b3a..1658262 100644
--- a/tests/net/common/java/android/net/RouteInfoTest.java
+++ b/tests/net/common/java/android/net/RouteInfoTest.java
@@ -19,19 +19,40 @@
import static android.net.RouteInfo.RTN_UNREACHABLE;
import static com.android.testutils.MiscAssertsKt.assertEqualBothWays;
+import static com.android.testutils.MiscAssertsKt.assertFieldCountEquals;
import static com.android.testutils.MiscAssertsKt.assertNotEqualEitherWay;
-import static com.android.testutils.ParcelUtilsKt.assertParcelSane;
import static com.android.testutils.ParcelUtilsKt.assertParcelingIsLossless;
-import android.test.suitebuilder.annotation.SmallTest;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
-import junit.framework.TestCase;
+import android.os.Build;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.testutils.DevSdkIgnoreRule;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
-public class RouteInfoTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class RouteInfoTest {
+ @Rule
+ public final DevSdkIgnoreRule ignoreRule = new DevSdkIgnoreRule();
+
+ private static final int INVALID_ROUTE_TYPE = -1;
private InetAddress Address(String addr) {
return InetAddress.parseNumericAddress(addr);
@@ -41,15 +62,32 @@
return new IpPrefix(prefix);
}
- @SmallTest
+ @Test
public void testConstructor() {
RouteInfo r;
-
// Invalid input.
try {
r = new RouteInfo((IpPrefix) null, null, "rmnet0");
fail("Expected RuntimeException: destination and gateway null");
- } catch(RuntimeException e) {}
+ } catch (RuntimeException e) { }
+
+ try {
+ r = new RouteInfo(Prefix("2001:db8:ace::/49"), Address("2001:db8::1"), "rmnet0",
+ INVALID_ROUTE_TYPE);
+ fail("Invalid route type should cause exception");
+ } catch (IllegalArgumentException e) { }
+
+ try {
+ r = new RouteInfo(Prefix("2001:db8:ace::/49"), Address("192.0.2.1"), "rmnet0",
+ RTN_UNREACHABLE);
+ fail("Address family mismatch should cause exception");
+ } catch (IllegalArgumentException e) { }
+
+ try {
+ r = new RouteInfo(Prefix("0.0.0.0/0"), Address("2001:db8::1"), "rmnet0",
+ RTN_UNREACHABLE);
+ fail("Address family mismatch should cause exception");
+ } catch (IllegalArgumentException e) { }
// Null destination is default route.
r = new RouteInfo((IpPrefix) null, Address("2001:db8::1"), null);
@@ -74,6 +112,7 @@
assertNull(r.getInterface());
}
+ @Test
public void testMatches() {
class PatchedRouteInfo {
private final RouteInfo mRouteInfo;
@@ -113,6 +152,7 @@
assertFalse(ipv4Default.matches(Address("2001:db8::f00")));
}
+ @Test
public void testEquals() {
// IPv4
RouteInfo r1 = new RouteInfo(Prefix("2001:db8:ace::/48"), Address("2001:db8::1"), "wlan0");
@@ -146,6 +186,7 @@
assertNotEqualEitherWay(r1, r3);
}
+ @Test
public void testHostAndDefaultRoutes() {
RouteInfo r;
@@ -228,6 +269,7 @@
assertFalse(r.isIPv6Default());
}
+ @Test
public void testTruncation() {
LinkAddress l;
RouteInfo r;
@@ -244,6 +286,7 @@
// Make sure that creating routes to multicast addresses doesn't throw an exception. Even though
// there's nothing we can do with them, we don't want to crash if, e.g., someone calls
// requestRouteToHostAddress("230.0.0.0", MOBILE_HIPRI);
+ @Test
public void testMulticastRoute() {
RouteInfo r;
r = new RouteInfo(Prefix("230.0.0.0/32"), Address("192.0.2.1"), "wlan0");
@@ -251,16 +294,36 @@
// No exceptions? Good.
}
+ @Test
public void testParceling() {
RouteInfo r;
-
- r = new RouteInfo(Prefix("::/0"), Address("2001:db8::"), null);
+ r = new RouteInfo(Prefix("192.0.2.0/24"), Address("192.0.2.1"), null);
assertParcelingIsLossless(r);
-
r = new RouteInfo(Prefix("192.0.2.0/24"), null, "wlan0");
- assertParcelSane(r, 7);
+ assertParcelingIsLossless(r);
+ r = new RouteInfo(Prefix("192.0.2.0/24"), Address("192.0.2.1"), "wlan0", RTN_UNREACHABLE);
+ assertParcelingIsLossless(r);
}
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ public void testMtuParceling() {
+ final RouteInfo r = new RouteInfo(Prefix("ff02::1/128"), Address("2001:db8::"), "testiface",
+ RTN_UNREACHABLE, 1450 /* mtu */);
+ assertParcelingIsLossless(r);
+ }
+
+ @Test @IgnoreAfter(Build.VERSION_CODES.Q)
+ public void testFieldCount_Q() {
+ assertFieldCountEquals(6, RouteInfo.class);
+ }
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ public void testFieldCount() {
+ // Make sure any new field is covered by the above parceling tests when changing this number
+ assertFieldCountEquals(7, RouteInfo.class);
+ }
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
public void testMtu() {
RouteInfo r;
r = new RouteInfo(Prefix("0.0.0.0/0"), Address("0.0.0.0"), "wlan0",
diff --git a/tests/net/common/java/android/net/util/SocketUtilsTest.kt b/tests/net/common/java/android/net/util/SocketUtilsTest.kt
index 9c7cfb0..aaf97f3 100644
--- a/tests/net/common/java/android/net/util/SocketUtilsTest.kt
+++ b/tests/net/common/java/android/net/util/SocketUtilsTest.kt
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-package android.net.util;
+package android.net.util
+import android.os.Build
import android.system.NetlinkSocketAddress
import android.system.Os
import android.system.OsConstants.AF_INET
@@ -26,18 +27,26 @@
import android.system.PacketSocketAddress
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
+import com.android.testutils.DevSdkIgnoreRule
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
+import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
private const val TEST_INDEX = 123
private const val TEST_PORT = 555
+private const val FF_BYTE = 0xff.toByte()
+
@RunWith(AndroidJUnit4::class)
@SmallTest
class SocketUtilsTest {
+ @Rule @JvmField
+ val ignoreRule = DevSdkIgnoreRule()
+
@Test
fun testMakeNetlinkSocketAddress() {
val nlAddress = SocketUtils.makeNetlinkSocketAddress(TEST_PORT, RTMGRP_NEIGH)
@@ -50,16 +59,21 @@
}
@Test
- fun testMakePacketSocketAddress() {
+ fun testMakePacketSocketAddress_Q() {
val pkAddress = SocketUtils.makePacketSocketAddress(ETH_P_ALL, TEST_INDEX)
assertTrue("Not PacketSocketAddress object", pkAddress is PacketSocketAddress)
- val ff = 0xff.toByte()
- val pkAddress2 = SocketUtils.makePacketSocketAddress(TEST_INDEX,
- byteArrayOf(ff, ff, ff, ff, ff, ff))
+ val pkAddress2 = SocketUtils.makePacketSocketAddress(TEST_INDEX, ByteArray(6) { FF_BYTE })
assertTrue("Not PacketSocketAddress object", pkAddress2 is PacketSocketAddress)
}
+ @Test @IgnoreUpTo(Build.VERSION_CODES.Q)
+ fun testMakePacketSocketAddress() {
+ val pkAddress = SocketUtils.makePacketSocketAddress(
+ ETH_P_ALL, TEST_INDEX, ByteArray(6) { FF_BYTE })
+ assertTrue("Not PacketSocketAddress object", pkAddress is PacketSocketAddress)
+ }
+
@Test
fun testCloseSocket() {
// Expect no exception happening with null object.
diff --git a/tests/net/java/android/net/IpMemoryStoreTest.java b/tests/net/java/android/net/IpMemoryStoreTest.java
index b81ca36..442ac56 100644
--- a/tests/net/java/android/net/IpMemoryStoreTest.java
+++ b/tests/net/java/android/net/IpMemoryStoreTest.java
@@ -35,6 +35,7 @@
import android.net.ipmemorystore.NetworkAttributes;
import android.net.ipmemorystore.NetworkAttributesParcelable;
import android.net.ipmemorystore.Status;
+import android.net.networkstack.ModuleNetworkStackClient;
import android.os.RemoteException;
import androidx.test.filters.SmallTest;
@@ -67,7 +68,7 @@
@Mock
Context mMockContext;
@Mock
- NetworkStackClient mNetworkStackClient;
+ ModuleNetworkStackClient mModuleNetworkStackClient;
@Mock
IIpMemoryStore mMockService;
@Mock
@@ -90,14 +91,14 @@
((IIpMemoryStoreCallbacks) invocation.getArgument(0))
.onIpMemoryStoreFetched(mMockService);
return null;
- }).when(mNetworkStackClient).fetchIpMemoryStore(any());
+ }).when(mModuleNetworkStackClient).fetchIpMemoryStore(any());
} else {
- doNothing().when(mNetworkStackClient).fetchIpMemoryStore(mCbCaptor.capture());
+ doNothing().when(mModuleNetworkStackClient).fetchIpMemoryStore(mCbCaptor.capture());
}
mStore = new IpMemoryStore(mMockContext) {
@Override
- protected NetworkStackClient getNetworkStackClient() {
- return mNetworkStackClient;
+ protected ModuleNetworkStackClient getModuleNetworkStackClient(Context ctx) {
+ return mModuleNetworkStackClient;
}
};
}
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index 4e75f2a2..671c564 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -23,8 +23,6 @@
import static android.content.pm.PackageManager.MATCH_ANY_USER;
import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
-import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
-import static android.net.ConnectivityDiagnosticsManager.DataStallReport;
import static android.net.ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN;
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_SUPL;
@@ -100,6 +98,7 @@
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Matchers.anyInt;
@@ -2426,7 +2425,7 @@
assertEquals(expectedRequestCount, testFactory.getMyRequestCount());
assertTrue(testFactory.getMyStartRequested());
- testFactory.unregister();
+ testFactory.terminate();
if (networkCallback != null) mCm.unregisterNetworkCallback(networkCallback);
handlerThread.quit();
}
@@ -2452,6 +2451,38 @@
}
@Test
+ public void testNetworkFactoryUnregister() throws Exception {
+ final NetworkCapabilities filter = new NetworkCapabilities();
+ filter.clearAll();
+
+ final HandlerThread handlerThread = new HandlerThread("testNetworkFactoryRequests");
+ handlerThread.start();
+
+ // Checks that calling setScoreFilter on a NetworkFactory immediately before closing it
+ // does not crash.
+ for (int i = 0; i < 100; i++) {
+ final MockNetworkFactory testFactory = new MockNetworkFactory(handlerThread.getLooper(),
+ mServiceContext, "testFactory", filter);
+ // Register the factory and don't be surprised when the default request arrives.
+ testFactory.register();
+ testFactory.expectAddRequestsWithScores(0);
+ testFactory.waitForNetworkRequests(1);
+
+ testFactory.setScoreFilter(42);
+ testFactory.terminate();
+
+ if (i % 2 == 0) {
+ try {
+ testFactory.register();
+ fail("Re-registering terminated NetworkFactory should throw");
+ } catch (IllegalStateException expected) {
+ }
+ }
+ }
+ handlerThread.quit();
+ }
+
+ @Test
public void testNoMutableNetworkRequests() throws Exception {
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent("a"), 0);
NetworkRequest request1 = new NetworkRequest.Builder()
@@ -2751,9 +2782,6 @@
// Expect NET_CAPABILITY_VALIDATED onAvailable callback.
validatedCallback.expectAvailableDoubleValidatedCallbacks(mWiFiNetworkAgent);
- // Expect no notification to be shown when captive portal disappears by itself
- verify(mNotificationManager, never()).notifyAsUser(
- anyString(), eq(NotificationType.LOGGED_IN.eventId), any(), any());
// Break network connectivity.
// Expect NET_CAPABILITY_VALIDATED onLost callback.
@@ -2815,8 +2843,6 @@
mWiFiNetworkAgent.mNetworkMonitor.forceReevaluation(Process.myUid());
validatedCallback.expectAvailableCallbacksValidated(mWiFiNetworkAgent);
captivePortalCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
- verify(mNotificationManager, times(1)).notifyAsUser(anyString(),
- eq(NotificationType.LOGGED_IN.eventId), any(), eq(UserHandle.ALL));
mCm.unregisterNetworkCallback(validatedCallback);
mCm.unregisterNetworkCallback(captivePortalCallback);
@@ -3488,7 +3514,7 @@
cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
assertLength(1, mCm.getAllNetworks());
- testFactory.unregister();
+ testFactory.terminate();
mCm.unregisterNetworkCallback(cellNetworkCallback);
handlerThread.quit();
}
@@ -3729,7 +3755,7 @@
mCm.requestNetwork(nr, networkCallback, timeoutMs);
// pass timeout and validate that UNAVAILABLE is called
- networkCallback.expectCallback(CallbackEntry.UNAVAILABLE, null);
+ networkCallback.expectCallback(CallbackEntry.UNAVAILABLE, (Network) null);
// create a network satisfying request - validate that request not triggered
mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
@@ -3820,7 +3846,7 @@
// Simulate the factory releasing the request as unfulfillable and expect onUnavailable!
testFactory.triggerUnfulfillable(requests.get(newRequestId));
- networkCallback.expectCallback(CallbackEntry.UNAVAILABLE, null);
+ networkCallback.expectCallback(CallbackEntry.UNAVAILABLE, (Network) null);
testFactory.waitForRequests();
// unregister network callback - a no-op (since already freed by the
@@ -3828,7 +3854,7 @@
mCm.unregisterNetworkCallback(networkCallback);
}
- testFactory.unregister();
+ testFactory.terminate();
handlerThread.quit();
}
@@ -5927,6 +5953,12 @@
final LinkAddress myIpv6 = new LinkAddress("2001:db8:1::1/64");
final String kNat64PrefixString = "2001:db8:64:64:64:64::";
final IpPrefix kNat64Prefix = new IpPrefix(InetAddress.getByName(kNat64PrefixString), 96);
+ final RouteInfo defaultRoute = new RouteInfo((IpPrefix) null, myIpv6.getAddress(),
+ MOBILE_IFNAME);
+ final RouteInfo ipv6Subnet = new RouteInfo(myIpv6, null, MOBILE_IFNAME);
+ final RouteInfo ipv4Subnet = new RouteInfo(myIpv4, null, MOBILE_IFNAME);
+ final RouteInfo stackedDefault = new RouteInfo((IpPrefix) null, myIpv4.getAddress(),
+ CLAT_PREFIX + MOBILE_IFNAME);
final NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(TRANSPORT_CELLULAR)
@@ -5939,15 +5971,13 @@
final LinkProperties cellLp = new LinkProperties();
cellLp.setInterfaceName(MOBILE_IFNAME);
cellLp.addLinkAddress(myIpv6);
- cellLp.addRoute(new RouteInfo((IpPrefix) null, myIpv6.getAddress(), MOBILE_IFNAME));
- cellLp.addRoute(new RouteInfo(myIpv6, null, MOBILE_IFNAME));
+ cellLp.addRoute(defaultRoute);
+ cellLp.addRoute(ipv6Subnet);
mCellNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_CELLULAR, cellLp);
reset(mNetworkManagementService);
reset(mMockDnsResolver);
reset(mMockNetd);
reset(mBatteryStatsService);
- when(mNetworkManagementService.getInterfaceConfig(CLAT_PREFIX + MOBILE_IFNAME))
- .thenReturn(getClatInterfaceConfig(myIpv4));
// Connect with ipv6 link properties. Expect prefix discovery to be started.
mCellNetworkAgent.connect(true);
@@ -5955,6 +5985,7 @@
waitForIdle();
verify(mMockNetd, times(1)).networkCreatePhysical(eq(cellNetId), anyInt());
+ assertRoutesAdded(cellNetId, ipv6Subnet, defaultRoute);
verify(mMockDnsResolver, times(1)).createNetworkCache(eq(cellNetId));
verify(mBatteryStatsService).noteNetworkInterfaceType(cellLp.getInterfaceName(),
TYPE_MOBILE);
@@ -5970,6 +6001,7 @@
cellLp.addLinkAddress(myIpv4);
mCellNetworkAgent.sendLinkProperties(cellLp);
networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+ assertRoutesAdded(cellNetId, ipv4Subnet);
verify(mMockDnsResolver, times(1)).stopPrefix64Discovery(cellNetId);
verify(mMockDnsResolver, atLeastOnce()).setResolverConfiguration(any());
@@ -5980,15 +6012,18 @@
verifyNoMoreInteractions(mMockNetd);
verifyNoMoreInteractions(mMockDnsResolver);
+ reset(mNetworkManagementService);
reset(mMockNetd);
reset(mMockDnsResolver);
+ when(mNetworkManagementService.getInterfaceConfig(CLAT_PREFIX + MOBILE_IFNAME))
+ .thenReturn(getClatInterfaceConfig(myIpv4));
// Remove IPv4 address. Expect prefix discovery to be started again.
cellLp.removeLinkAddress(myIpv4);
- cellLp.removeRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
mCellNetworkAgent.sendLinkProperties(cellLp);
networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
verify(mMockDnsResolver, times(1)).startPrefix64Discovery(cellNetId);
+ assertRoutesRemoved(cellNetId, ipv4Subnet);
// When NAT64 prefix discovery succeeds, LinkProperties are updated and clatd is started.
Nat464Xlat clat = getNat464Xlat(mCellNetworkAgent);
@@ -6007,6 +6042,7 @@
List<LinkProperties> stackedLps = mCm.getLinkProperties(mCellNetworkAgent.getNetwork())
.getStackedLinks();
assertEquals(makeClatLinkProperties(myIpv4), stackedLps.get(0));
+ assertRoutesAdded(cellNetId, stackedDefault);
// Change trivial linkproperties and see if stacked link is preserved.
cellLp.addDnsServer(InetAddress.getByName("8.8.8.8"));
@@ -6032,9 +6068,10 @@
// Add ipv4 address, expect that clatd and prefix discovery are stopped and stacked
// linkproperties are cleaned up.
cellLp.addLinkAddress(myIpv4);
- cellLp.addRoute(new RouteInfo(myIpv4, null, MOBILE_IFNAME));
+ cellLp.addRoute(ipv4Subnet);
mCellNetworkAgent.sendLinkProperties(cellLp);
networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+ assertRoutesAdded(cellNetId, ipv4Subnet);
verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
verify(mMockDnsResolver, times(1)).stopPrefix64Discovery(cellNetId);
@@ -6045,6 +6082,7 @@
expected.setNat64Prefix(kNat64Prefix);
assertEquals(expected, actualLpAfterIpv4);
assertEquals(0, actualLpAfterIpv4.getStackedLinks().size());
+ assertRoutesRemoved(cellNetId, stackedDefault);
// The interface removed callback happens but has no effect after stop is called.
clat.interfaceRemoved(CLAT_PREFIX + MOBILE_IFNAME);
@@ -6052,8 +6090,11 @@
verifyNoMoreInteractions(mMockNetd);
verifyNoMoreInteractions(mMockDnsResolver);
+ reset(mNetworkManagementService);
reset(mMockNetd);
reset(mMockDnsResolver);
+ when(mNetworkManagementService.getInterfaceConfig(CLAT_PREFIX + MOBILE_IFNAME))
+ .thenReturn(getClatInterfaceConfig(myIpv4));
// Stopping prefix discovery causes netd to tell us that the NAT64 prefix is gone.
mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, false /* added */,
@@ -6067,6 +6108,7 @@
cellLp.removeDnsServer(InetAddress.getByName("8.8.8.8"));
mCellNetworkAgent.sendLinkProperties(cellLp);
networkCallback.expectCallback(CallbackEntry.LINK_PROPERTIES_CHANGED, mCellNetworkAgent);
+ assertRoutesRemoved(cellNetId, ipv4Subnet); // Directly-connected routes auto-added.
verify(mMockDnsResolver, times(1)).startPrefix64Discovery(cellNetId);
mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, true /* added */,
kNat64PrefixString, 96);
@@ -6078,15 +6120,20 @@
clat.interfaceLinkStateChanged(CLAT_PREFIX + MOBILE_IFNAME, true);
networkCallback.expectLinkPropertiesThat(mCellNetworkAgent,
(lp) -> lp.getStackedLinks().size() == 1 && lp.getNat64Prefix() != null);
+ assertRoutesAdded(cellNetId, stackedDefault);
// NAT64 prefix is removed. Expect that clat is stopped.
mService.mNetdEventCallback.onNat64PrefixEvent(cellNetId, false /* added */,
kNat64PrefixString, 96);
networkCallback.expectLinkPropertiesThat(mCellNetworkAgent,
(lp) -> lp.getStackedLinks().size() == 0 && lp.getNat64Prefix() == null);
+ assertRoutesRemoved(cellNetId, ipv4Subnet, stackedDefault);
+
+ // Stop has no effect because clat is already stopped.
verify(mMockNetd, times(1)).clatdStop(MOBILE_IFNAME);
networkCallback.expectLinkPropertiesThat(mCellNetworkAgent,
(lp) -> lp.getStackedLinks().size() == 0);
+ verifyNoMoreInteractions(mMockNetd);
// Clean up.
mCellNetworkAgent.disconnect();
@@ -6654,6 +6701,20 @@
}
}
+ private void assertRoutesAdded(int netId, RouteInfo... routes) throws Exception {
+ InOrder inOrder = inOrder(mNetworkManagementService);
+ for (int i = 0; i < routes.length; i++) {
+ inOrder.verify(mNetworkManagementService).addRoute(eq(netId), eq(routes[i]));
+ }
+ }
+
+ private void assertRoutesRemoved(int netId, RouteInfo... routes) throws Exception {
+ InOrder inOrder = inOrder(mNetworkManagementService);
+ for (int i = 0; i < routes.length; i++) {
+ inOrder.verify(mNetworkManagementService).removeRoute(eq(netId), eq(routes[i]));
+ }
+ }
+
@Test
public void testRegisterUnregisterConnectivityDiagnosticsCallback() throws Exception {
final NetworkRequest wifiRequest =
@@ -6715,7 +6776,7 @@
public void testCheckConnectivityDiagnosticsPermissionsNetworkStack() throws Exception {
final NetworkAgentInfo naiWithoutUid =
new NetworkAgentInfo(
- null, null, null, null, null, new NetworkCapabilities(), null,
+ null, null, null, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0);
mServiceContext.setPermission(
@@ -6731,7 +6792,7 @@
public void testCheckConnectivityDiagnosticsPermissionsNoLocationPermission() throws Exception {
final NetworkAgentInfo naiWithoutUid =
new NetworkAgentInfo(
- null, null, null, null, null, new NetworkCapabilities(), null,
+ null, null, null, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0);
mServiceContext.setPermission(android.Manifest.permission.NETWORK_STACK, PERMISSION_DENIED);
@@ -6747,7 +6808,7 @@
public void testCheckConnectivityDiagnosticsPermissionsActiveVpn() throws Exception {
final NetworkAgentInfo naiWithoutUid =
new NetworkAgentInfo(
- null, null, null, null, null, new NetworkCapabilities(), null,
+ null, null, null, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0);
setupLocationPermissions(Build.VERSION_CODES.Q, true, AppOpsManager.OPSTR_FINE_LOCATION,
@@ -6773,7 +6834,7 @@
nc.setAdministratorUids(Arrays.asList(Process.myUid()));
final NetworkAgentInfo naiWithUid =
new NetworkAgentInfo(
- null, null, null, null, null, nc, null, mServiceContext, null, null,
+ null, null, null, null, null, nc, 0, mServiceContext, null, null,
mService, null, null, null, 0);
setupLocationPermissions(Build.VERSION_CODES.Q, true, AppOpsManager.OPSTR_FINE_LOCATION,
@@ -6795,7 +6856,7 @@
nc.setAdministratorUids(Arrays.asList(Process.myUid()));
final NetworkAgentInfo naiWithUid =
new NetworkAgentInfo(
- null, null, null, null, null, nc, null, mServiceContext, null, null,
+ null, null, null, null, null, nc, 0, mServiceContext, null, null,
mService, null, null, null, 0);
setupLocationPermissions(Build.VERSION_CODES.Q, true, AppOpsManager.OPSTR_FINE_LOCATION,
@@ -6840,8 +6901,13 @@
HandlerUtilsKt.waitForIdle(mCsHandlerThread, TIMEOUT_MS);
// Verify onConnectivityReport fired
- verify(mConnectivityDiagnosticsCallback)
- .onConnectivityReport(any(ConnectivityReport.class));
+ verify(mConnectivityDiagnosticsCallback).onConnectivityReport(
+ argThat(report -> {
+ final NetworkCapabilities nc = report.getNetworkCapabilities();
+ return nc.getUids() == null
+ && nc.getAdministratorUids().isEmpty()
+ && nc.getOwnerUid() == Process.INVALID_UID;
+ }));
}
@Test
@@ -6856,7 +6922,13 @@
HandlerUtilsKt.waitForIdle(mCsHandlerThread, TIMEOUT_MS);
// Verify onDataStallSuspected fired
- verify(mConnectivityDiagnosticsCallback).onDataStallSuspected(any(DataStallReport.class));
+ verify(mConnectivityDiagnosticsCallback).onDataStallSuspected(
+ argThat(report -> {
+ final NetworkCapabilities nc = report.getNetworkCapabilities();
+ return nc.getUids() == null
+ && nc.getAdministratorUids().isEmpty()
+ && nc.getOwnerUid() == Process.INVALID_UID;
+ }));
}
@Test
diff --git a/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java b/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
index e863266..24a8717 100644
--- a/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
@@ -38,7 +38,6 @@
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkProvider;
-import android.net.NetworkScore;
import android.os.INetworkManagementService;
import android.text.format.DateUtils;
@@ -353,10 +352,8 @@
NetworkCapabilities caps = new NetworkCapabilities();
caps.addCapability(0);
caps.addTransportType(transport);
- NetworkScore ns = new NetworkScore();
- ns.putIntExtension(NetworkScore.LEGACY_SCORE, 50);
NetworkAgentInfo nai = new NetworkAgentInfo(null, null, new Network(netId), info, null,
- caps, ns, mCtx, null, null /* config */, mConnService, mNetd, mDnsResolver, mNMS,
+ caps, 50, mCtx, null, null /* config */, mConnService, mNetd, mDnsResolver, mNMS,
NetworkProvider.ID_NONE);
nai.everValidated = true;
return nai;
diff --git a/tests/net/java/com/android/server/connectivity/NetworkNotificationManagerTest.java b/tests/net/java/com/android/server/connectivity/NetworkNotificationManagerTest.java
index d57f225..47db5d4 100644
--- a/tests/net/java/com/android/server/connectivity/NetworkNotificationManagerTest.java
+++ b/tests/net/java/com/android/server/connectivity/NetworkNotificationManagerTest.java
@@ -238,20 +238,6 @@
}
@Test
- public void testSameLevelNotifications() {
- final int id = 101;
- final String tag = NetworkNotificationManager.tagFor(id);
-
- mManager.showNotification(id, LOGGED_IN, mWifiNai, mCellNai, null, false);
- verify(mNotificationManager, times(1))
- .notifyAsUser(eq(tag), eq(LOGGED_IN.eventId), any(), any());
-
- mManager.showNotification(id, LOST_INTERNET, mWifiNai, mCellNai, null, false);
- verify(mNotificationManager, times(1))
- .notifyAsUser(eq(tag), eq(LOST_INTERNET.eventId), any(), any());
- }
-
- @Test
public void testClearNotificationByType() {
final int id = 101;
final String tag = NetworkNotificationManager.tagFor(id);
@@ -259,31 +245,25 @@
// clearNotification(int id, NotificationType notifyType) will check if given type is equal
// to previous type or not. If they are equal then clear the notification; if they are not
// equal then return.
-
- mManager.showNotification(id, LOGGED_IN, mWifiNai, mCellNai, null, false);
+ mManager.showNotification(id, NO_INTERNET, mWifiNai, mCellNai, null, false);
verify(mNotificationManager, times(1))
- .notifyAsUser(eq(tag), eq(LOGGED_IN.eventId), any(), any());
+ .notifyAsUser(eq(tag), eq(NO_INTERNET.eventId), any(), any());
- // Previous notification is LOGGED_IN and given type is LOGGED_IN too. The notification
+ // Previous notification is NO_INTERNET and given type is NO_INTERNET too. The notification
// should be cleared.
- mManager.clearNotification(id, LOGGED_IN);
+ mManager.clearNotification(id, NO_INTERNET);
verify(mNotificationManager, times(1))
- .cancelAsUser(eq(tag), eq(LOGGED_IN.eventId), any());
+ .cancelAsUser(eq(tag), eq(NO_INTERNET.eventId), any());
- mManager.showNotification(id, LOGGED_IN, mWifiNai, mCellNai, null, false);
- verify(mNotificationManager, times(2))
- .notifyAsUser(eq(tag), eq(LOGGED_IN.eventId), any(), any());
-
- // LOST_INTERNET notification popup after LOGGED_IN notification.
- mManager.showNotification(id, LOST_INTERNET, mWifiNai, mCellNai, null, false);
+ // SIGN_IN is popped-up.
+ mManager.showNotification(id, SIGN_IN, mWifiNai, mCellNai, null, false);
verify(mNotificationManager, times(1))
- .notifyAsUser(eq(tag), eq(LOST_INTERNET.eventId), any(), any());
+ .notifyAsUser(eq(tag), eq(SIGN_IN.eventId), any(), any());
- // Previous notification is LOST_INTERNET and given type is LOGGED_IN. The notification
- // shouldn't be cleared.
- mManager.clearNotification(id, LOGGED_IN);
- // LOST_INTERNET shouldn't be cleared.
+ // The notification type is not matching previous one, PARTIAL_CONNECTIVITY won't be
+ // cleared.
+ mManager.clearNotification(id, PARTIAL_CONNECTIVITY);
verify(mNotificationManager, never())
- .cancelAsUser(eq(tag), eq(LOST_INTERNET.eventId), any());
+ .cancelAsUser(eq(tag), eq(PARTIAL_CONNECTIVITY.eventId), any());
}
}
diff --git a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
index a9e0b9a..36deca3 100644
--- a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -64,6 +64,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.annotation.NonNull;
import android.app.AlarmManager;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
@@ -163,7 +164,6 @@
private @Mock IBinder mBinder;
private @Mock AlarmManager mAlarmManager;
private HandlerThread mHandlerThread;
- private Handler mHandler;
private NetworkStatsService mService;
private INetworkStatsSession mSession;
@@ -192,15 +192,11 @@
PowerManager.WakeLock wakeLock =
powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
- mService = new NetworkStatsService(
- mServiceContext, mNetManager, mAlarmManager, wakeLock, mClock,
- mServiceContext.getSystemService(TelephonyManager.class), mSettings,
- mStatsFactory, new NetworkStatsObservers(), mStatsDir, getBaseDir(mStatsDir));
mHandlerThread = new HandlerThread("HandlerThread");
- mHandlerThread.start();
- Handler.Callback callback = new NetworkStatsService.HandlerCallback(mService);
- mHandler = new Handler(mHandlerThread.getLooper(), callback);
- mService.setHandler(mHandler, callback);
+ final NetworkStatsService.Dependencies deps = makeDependencies();
+ mService = new NetworkStatsService(mServiceContext, mNetManager, mAlarmManager, wakeLock,
+ mClock, mServiceContext.getSystemService(TelephonyManager.class), mSettings,
+ mStatsFactory, new NetworkStatsObservers(), mStatsDir, getBaseDir(mStatsDir), deps);
mElapsedRealtime = 0L;
@@ -217,11 +213,21 @@
// catch INetworkManagementEventObserver during systemReady()
ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
- ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
+ ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
verify(mNetManager).registerObserver(networkObserver.capture());
mNetworkObserver = networkObserver.getValue();
}
+ @NonNull
+ private NetworkStatsService.Dependencies makeDependencies() {
+ return new NetworkStatsService.Dependencies() {
+ @Override
+ public HandlerThread makeHandlerThread() {
+ return mHandlerThread;
+ }
+ };
+ }
+
@After
public void tearDown() throws Exception {
IoUtils.deleteContents(mStatsDir);
@@ -234,6 +240,8 @@
mSession.close();
mService = null;
+
+ mHandlerThread.quitSafely();
}
@Test
@@ -939,9 +947,7 @@
long minThresholdInBytes = 2 * 1024 * 1024; // 2 MB
assertEquals(minThresholdInBytes, request.thresholdInBytes);
- // Send dummy message to make sure that any previous message has been handled
- mHandler.sendMessage(mHandler.obtainMessage(-1));
- HandlerUtilsKt.waitForIdle(mHandler, WAIT_TIMEOUT);
+ HandlerUtilsKt.waitForIdle(mHandlerThread, WAIT_TIMEOUT);
// Make sure that the caller binder gets connected
verify(mBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
@@ -1077,7 +1083,7 @@
// Simulates alert quota of the provider has been reached.
cb.onAlertReached();
- HandlerUtilsKt.waitForIdle(mHandler, WAIT_TIMEOUT);
+ HandlerUtilsKt.waitForIdle(mHandlerThread, WAIT_TIMEOUT);
// Verifies that polling is triggered by alert reached.
provider.expectStatsUpdate(0 /* unused */);
@@ -1294,9 +1300,7 @@
private void forcePollAndWaitForIdle() {
mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));
- // Send dummy message to make sure that any previous message has been handled
- mHandler.sendMessage(mHandler.obtainMessage(-1));
- HandlerUtilsKt.waitForIdle(mHandler, WAIT_TIMEOUT);
+ HandlerUtilsKt.waitForIdle(mHandlerThread, WAIT_TIMEOUT);
}
static class LatchedHandler extends Handler {
diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp
index 5aa32f8..bcfce66 100644
--- a/tools/aapt2/link/ManifestFixer.cpp
+++ b/tools/aapt2/link/ManifestFixer.cpp
@@ -366,8 +366,12 @@
});
manifest_action["instrumentation"]["meta-data"] = meta_data_action;
+ // TODO moltmann: Remove
manifest_action["feature"];
manifest_action["feature"]["inherit-from"];
+
+ manifest_action["attribution"];
+ manifest_action["attribution"]["inherit-from"];
manifest_action["original-package"];
manifest_action["overlay"];
manifest_action["protected-broadcast"];
diff --git a/tools/codegen/src/com/android/codegen/ClassPrinter.kt b/tools/codegen/src/com/android/codegen/ClassPrinter.kt
index c7c80ba..b90e1bb 100644
--- a/tools/codegen/src/com/android/codegen/ClassPrinter.kt
+++ b/tools/codegen/src/com/android/codegen/ClassPrinter.kt
@@ -100,7 +100,7 @@
?: emptyMap()
val internalAnnotations = setOf(ParcelWith, DataClassEnum, PluralOf, UnsupportedAppUsage,
- DataClassSuppressConstDefs)
+ DataClassSuppressConstDefs, MaySetToNull, Each, DataClass)
val knownNonValidationAnnotations = internalAnnotations + Each + Nullable
/**
diff --git a/tools/codegen/src/com/android/codegen/FieldInfo.kt b/tools/codegen/src/com/android/codegen/FieldInfo.kt
index ebfbbd8..02ebaef 100644
--- a/tools/codegen/src/com/android/codegen/FieldInfo.kt
+++ b/tools/codegen/src/com/android/codegen/FieldInfo.kt
@@ -147,9 +147,19 @@
val sParcelling by lazy { customParcellingClass?.let { "sParcellingFor$NameUpperCamel" } }
val SetterParamType = if (isArray) "$FieldInnerType..." else Type
- val annotatedTypeForSetterParam by lazy {
- (annotationsNoInternal + SetterParamType).joinToString(" ")
+ val annotationsForSetterParam by lazy {
+ buildList<String> {
+ addAll(annotationsNoInternal)
+ classPrinter {
+ if ("@$Nullable" in annotations
+ && "@$MaySetToNull" !in annotations) {
+ remove("@$Nullable")
+ add("@$NonNull")
+ }
+ }
+ }.joinToString(" ")
}
+ val annotatedTypeForSetterParam by lazy { "$annotationsForSetterParam $SetterParamType" }
// Utilities
diff --git a/tools/codegen/src/com/android/codegen/Generators.kt b/tools/codegen/src/com/android/codegen/Generators.kt
index 8fe243f..5a96cf1 100644
--- a/tools/codegen/src/com/android/codegen/Generators.kt
+++ b/tools/codegen/src/com/android/codegen/Generators.kt
@@ -315,7 +315,7 @@
generateBuilderMethod(
name = setterName,
defVisibility = visibility,
- paramAnnotations = annotationsNoInternal.joinToString(" "),
+ paramAnnotations = annotationsForSetterParam,
paramTypes = listOf(SetterParamType),
genJavadoc = { generateFieldJavadoc() }) {
+"checkNotUsed();"
diff --git a/tools/codegen/src/com/android/codegen/ImportsProvider.kt b/tools/codegen/src/com/android/codegen/ImportsProvider.kt
index c830aaa..27dd958 100644
--- a/tools/codegen/src/com/android/codegen/ImportsProvider.kt
+++ b/tools/codegen/src/com/android/codegen/ImportsProvider.kt
@@ -39,6 +39,7 @@
val ParcelWith: String get() { return classRef("com.android.internal.util.DataClass.ParcelWith") }
val PluralOf: String get() { return classRef("com.android.internal.util.DataClass.PluralOf") }
val Each: String get() { return classRef("com.android.internal.util.DataClass.Each") }
+ val MaySetToNull: String get() { return classRef("com.android.internal.util.DataClass.MaySetToNull") }
val DataClassGenerated: String get() { return classRef("com.android.internal.util.DataClass.Generated") }
val DataClassSuppressConstDefs: String get() { return classRef("com.android.internal.util.DataClass.SuppressConstDefsGeneration") }
val DataClassSuppress: String get() { return classRef("com.android.internal.util.DataClass.Suppress") }
diff --git a/tools/codegen/src/com/android/codegen/SharedConstants.kt b/tools/codegen/src/com/android/codegen/SharedConstants.kt
index 74c86f4..6f740cd6 100644
--- a/tools/codegen/src/com/android/codegen/SharedConstants.kt
+++ b/tools/codegen/src/com/android/codegen/SharedConstants.kt
@@ -1,7 +1,7 @@
package com.android.codegen
const val CODEGEN_NAME = "codegen"
-const val CODEGEN_VERSION = "1.0.14"
+const val CODEGEN_VERSION = "1.0.15"
const val CANONICAL_BUILDER_CLASS = "Builder"
const val BASE_BUILDER_CLASS = "BaseBuilder"
diff --git a/tools/stats_log_api_gen/Android.bp b/tools/stats_log_api_gen/Android.bp
index cbf6fe8..b1e2487 100644
--- a/tools/stats_log_api_gen/Android.bp
+++ b/tools/stats_log_api_gen/Android.bp
@@ -120,12 +120,6 @@
"liblog",
"libcutils",
],
- apex_available: [
- "//apex_available:platform",
- //TODO(b/149781190): Remove this once statsd no longer depends on libstatslog
- "com.android.os.statsd",
- "test_com.android.os.statsd",
- ],
target: {
android: {
shared_libs: ["libstatssocket"],
diff --git a/wifi/Android.bp b/wifi/Android.bp
index 91174d3..f4d2881 100644
--- a/wifi/Android.bp
+++ b/wifi/Android.bp
@@ -177,14 +177,14 @@
java_library {
name: "framework-wifi-stubs-publicapi",
srcs: [":framework-wifi-stubs-srcs-publicapi"],
- sdk_version: "module_current",
+ sdk_version: "current",
installable: false,
}
java_library {
name: "framework-wifi-stubs-systemapi",
srcs: [":framework-wifi-stubs-srcs-systemapi"],
- sdk_version: "module_current",
+ sdk_version: "system_current",
libs: ["framework-annotations-lib"],
installable: false,
}
diff --git a/wifi/jarjar-rules.txt b/wifi/jarjar-rules.txt
index 950361c..eeb006e 100644
--- a/wifi/jarjar-rules.txt
+++ b/wifi/jarjar-rules.txt
@@ -1,7 +1,32 @@
+# used by wifi-service
+rule android.net.DhcpResultsParcelable* @0
+rule android.net.DhcpResults* com.android.server.x.wifi.net.DhcpResults@1
rule android.net.InterfaceConfigurationParcel* @0
rule android.net.InterfaceConfiguration* com.android.server.x.wifi.net.InterfaceConfiguration@1
+rule android.net.IpMemoryStore* com.android.server.x.wifi.net.IpMemoryStore@1
+rule android.net.NetworkMonitorManager* com.android.server.x.wifi.net.NetworkMonitorManager@1
+rule android.net.TcpKeepalivePacketData* com.android.server.x.wifi.net.TcpKeepalivePacketData@1
rule android.net.NetworkFactory* com.android.server.x.wifi.net.NetworkFactory@1
+rule android.net.ip.IpClientCallbacks* com.android.server.x.wifi.net.ip.IpClientCallbacks@1
+rule android.net.ip.IpClientManager* com.android.server.x.wifi.net.ip.IpClientManager@1
+rule android.net.ip.IpClientUtil* com.android.server.x.wifi.net.ip.IpClientUtil@1
+rule android.net.shared.InetAddressUtils* com.android.server.x.wifi.net.shared.InetAddressUtils@1
+rule android.net.shared.InitialConfiguration* com.android.server.x.wifi.net.shared.InitialConfiguration@1
+rule android.net.shared.IpConfigurationParcelableUtil* com.android.server.x.wifi.net.shared.IpConfigurationParcelableUtil@1
+rule android.net.shared.LinkPropertiesParcelableUtil* com.android.server.x.wifi.net.shared.LinkPropertiesParcelableUtil@1
+rule android.net.shared.ParcelableUtil* com.android.server.x.wifi.net.shared.ParcelableUtil@1
+rule android.net.shared.NetdUtils* com.android.server.x.wifi.net.shared.NetdUtils@1
+rule android.net.shared.NetworkMonitorUtils* com.android.server.x.wifi.net.shared.NetworkMonitorUtils@1
+rule android.net.shared.ParcelableUtil* com.android.server.x.wifi.net.shared.ParcelableUtil@1
+rule android.net.shared.PrivateDnsConfig* com.android.server.x.wifi.net.shared.PrivateDnsConfig@1
+rule android.net.shared.ProvisioningConfiguration* com.android.server.x.wifi.net.shared.ProvisioningConfiguration@1
+rule android.net.shared.RouteUtils* com.android.server.x.wifi.net.shared.RouteUtils@1
+rule android.net.util.KeepalivePacketDataUtil* com.android.server.x.wifi.net.util.KeepalivePacketDataUtil@1
+rule android.net.util.NetworkConstants* com.android.server.x.wifi.net.util.NetworkConstants@1
+rule android.net.util.InterfaceParams* com.android.server.x.wifi.net.util.InterfaceParams@1
+rule android.net.util.SharedLog* com.android.server.x.wifi.net.util.SharedLog@1
rule android.net.util.NetUtils* com.android.server.x.wifi.net.util.NetUtils@1
+rule android.net.util.IpUtils* com.android.server.x.wifi.net.util.IpUtils@1
# We don't jar-jar the entire package because, we still use some classes (like
# AsyncChannel in com.android.internal.util) from these packages which are not
@@ -29,7 +54,6 @@
# Use our statically linked PlatformProperties library
rule android.sysprop.** com.android.server.x.wifi.sysprop.@1
-
# used by both framework-wifi and wifi-service
rule android.content.pm.BaseParceledListSlice* android.x.net.wifi.util.BaseParceledListSlice@1
rule android.content.pm.ParceledListSlice* android.x.net.wifi.util.ParceledListSlice@1
diff --git a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl b/wifi/java/android/net/wifi/IScoreUpdateObserver.aidl
similarity index 82%
rename from wifi/java/android/net/wifi/IScoreChangeCallback.aidl
rename to wifi/java/android/net/wifi/IScoreUpdateObserver.aidl
index d691f41..775fed7 100644
--- a/wifi/java/android/net/wifi/IScoreChangeCallback.aidl
+++ b/wifi/java/android/net/wifi/IScoreUpdateObserver.aidl
@@ -21,9 +21,9 @@
*
* @hide
*/
-oneway interface IScoreChangeCallback
+oneway interface IScoreUpdateObserver
{
- void onScoreChange(int sessionId, int score);
+ void notifyScoreUpdate(int sessionId, int score);
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
+ void triggerUpdateOfWifiUsabilityStats(int sessionId);
}
diff --git a/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl b/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl
index d9a3b01..f96d037 100644
--- a/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl
+++ b/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl
@@ -16,7 +16,7 @@
package android.net.wifi;
-import android.net.wifi.IScoreChangeCallback;
+import android.net.wifi.IScoreUpdateObserver;
/**
* Interface for Wi-Fi connected network scorer.
@@ -25,9 +25,9 @@
*/
oneway interface IWifiConnectedNetworkScorer
{
- void start(int sessionId);
+ void onStart(int sessionId);
- void stop(int sessionId);
+ void onStop(int sessionId);
- void setScoreChangeCallback(IScoreChangeCallback cbImpl);
+ void onSetScoreUpdateObserver(IScoreUpdateObserver observerImpl);
}
diff --git a/wifi/java/android/net/wifi/ScanResult.java b/wifi/java/android/net/wifi/ScanResult.java
index 9256c57..727952c 100644
--- a/wifi/java/android/net/wifi/ScanResult.java
+++ b/wifi/java/android/net/wifi/ScanResult.java
@@ -16,16 +16,15 @@
package android.net.wifi;
-import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
+import android.net.wifi.WifiAnnotations.ChannelWidth;
+import android.net.wifi.WifiAnnotations.WifiStandard;
import android.os.Parcel;
import android.os.Parcelable;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
@@ -313,17 +312,6 @@
*/
public static final int WIFI_STANDARD_11AX = 6;
- /** @hide */
- @IntDef(prefix = { "WIFI_STANDARD_" }, value = {
- WIFI_STANDARD_UNKNOWN,
- WIFI_STANDARD_LEGACY,
- WIFI_STANDARD_11N,
- WIFI_STANDARD_11AC,
- WIFI_STANDARD_11AX
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiStandard{}
-
/**
* AP wifi standard.
*/
@@ -368,7 +356,7 @@
* {@link #CHANNEL_WIDTH_80MHZ}, {@link #CHANNEL_WIDTH_160MHZ}
* or {@link #CHANNEL_WIDTH_80MHZ_PLUS_MHZ}.
*/
- public int channelWidth;
+ public @ChannelWidth int channelWidth;
/**
* Not used if the AP bandwidth is 20 MHz
@@ -707,31 +695,6 @@
*/
public AnqpInformationElement[] anqpElements;
- /**
- * Flag indicating if this AP is a carrier AP. The determination is based
- * on the AP's SSID and if AP is using EAP security.
- *
- * @hide
- */
- // TODO(b/144431927): remove once migrated to Suggestions
- public boolean isCarrierAp;
-
- /**
- * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
- *
- * @hide
- */
- // TODO(b/144431927): remove once migrated to Suggestions
- public int carrierApEapType;
-
- /**
- * The name of the carrier that's associated with this AP if it is a carrier AP.
- *
- * @hide
- */
- // TODO(b/144431927): remove once migrated to Suggestions
- public String carrierName;
-
/** {@hide} */
public ScanResult(WifiSsid wifiSsid, String BSSID, long hessid, int anqpDomainId,
byte[] osuProviders, String caps, int level, int frequency, long tsf) {
@@ -756,9 +719,6 @@
this.centerFreq0 = UNSPECIFIED;
this.centerFreq1 = UNSPECIFIED;
this.flags = 0;
- this.isCarrierAp = false;
- this.carrierApEapType = UNSPECIFIED;
- this.carrierName = null;
this.radioChainInfos = null;
this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
}
@@ -779,9 +739,6 @@
this.centerFreq0 = UNSPECIFIED;
this.centerFreq1 = UNSPECIFIED;
this.flags = 0;
- this.isCarrierAp = false;
- this.carrierApEapType = UNSPECIFIED;
- this.carrierName = null;
this.radioChainInfos = null;
this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
}
@@ -809,9 +766,6 @@
} else {
this.flags = 0;
}
- this.isCarrierAp = false;
- this.carrierApEapType = UNSPECIFIED;
- this.carrierName = null;
this.radioChainInfos = null;
this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
}
@@ -851,9 +805,6 @@
venueName = source.venueName;
operatorFriendlyName = source.operatorFriendlyName;
flags = source.flags;
- isCarrierAp = source.isCarrierAp;
- carrierApEapType = source.carrierApEapType;
- carrierName = source.carrierName;
radioChainInfos = source.radioChainInfos;
this.mWifiStandard = source.mWifiStandard;
}
@@ -893,9 +844,6 @@
sb.append(", standard: ").append(wifiStandardToString(mWifiStandard));
sb.append(", 80211mcResponder: ");
sb.append(((flags & FLAG_80211mc_RESPONDER) != 0) ? "is supported" : "is not supported");
- sb.append(", Carrier AP: ").append(isCarrierAp ? "yes" : "no");
- sb.append(", Carrier AP EAP Type: ").append(carrierApEapType);
- sb.append(", Carrier name: ").append(carrierName);
sb.append(", Radio Chain Infos: ").append(Arrays.toString(radioChainInfos));
return sb.toString();
}
@@ -966,9 +914,6 @@
} else {
dest.writeInt(0);
}
- dest.writeInt(isCarrierAp ? 1 : 0);
- dest.writeInt(carrierApEapType);
- dest.writeString(carrierName);
if (radioChainInfos != null) {
dest.writeInt(radioChainInfos.length);
@@ -1048,9 +993,6 @@
new AnqpInformationElement(vendorId, elementId, payload);
}
}
- sr.isCarrierAp = in.readInt() != 0;
- sr.carrierApEapType = in.readInt();
- sr.carrierName = in.readString();
n = in.readInt();
if (n != 0) {
sr.radioChainInfos = new RadioChainInfo[n];
diff --git a/wifi/java/android/net/wifi/SoftApConfiguration.java b/wifi/java/android/net/wifi/SoftApConfiguration.java
index 2b47623..a269e17 100644
--- a/wifi/java/android/net/wifi/SoftApConfiguration.java
+++ b/wifi/java/android/net/wifi/SoftApConfiguration.java
@@ -35,7 +35,6 @@
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import java.util.Objects;
@@ -211,7 +210,7 @@
* Delay in milliseconds before shutting down soft AP when
* there are no connected devices.
*/
- private final int mShutdownTimeoutMillis;
+ private final long mShutdownTimeoutMillis;
/**
* THe definition of security type OPEN.
@@ -247,7 +246,7 @@
private SoftApConfiguration(@Nullable String ssid, @Nullable MacAddress bssid,
@Nullable String passphrase, boolean hiddenSsid, @BandType int band, int channel,
@SecurityType int securityType, int maxNumberOfClients, boolean shutdownTimeoutEnabled,
- int shutdownTimeoutMillis, boolean clientControlByUser,
+ long shutdownTimeoutMillis, boolean clientControlByUser,
@NonNull List<MacAddress> blockedList, @NonNull List<MacAddress> allowedList) {
mSsid = ssid;
mBssid = bssid;
@@ -327,7 +326,7 @@
dest.writeInt(mSecurityType);
dest.writeInt(mMaxNumberOfClients);
dest.writeBoolean(mAutoShutdownEnabled);
- dest.writeInt(mShutdownTimeoutMillis);
+ dest.writeLong(mShutdownTimeoutMillis);
dest.writeBoolean(mClientControlByUser);
dest.writeTypedList(mBlockedClientList);
dest.writeTypedList(mAllowedClientList);
@@ -346,7 +345,7 @@
in.readString(),
in.readParcelable(MacAddress.class.getClassLoader()),
in.readString(), in.readBoolean(), in.readInt(), in.readInt(), in.readInt(),
- in.readInt(), in.readBoolean(), in.readInt(), in.readBoolean(),
+ in.readInt(), in.readBoolean(), in.readLong(), in.readBoolean(),
in.createTypedArrayList(MacAddress.CREATOR),
in.createTypedArrayList(MacAddress.CREATOR));
}
@@ -454,19 +453,19 @@
/**
* Returns the shutdown timeout in milliseconds.
* The Soft AP will shutdown when there are no devices associated to it for
- * the timeout duration. See {@link Builder#setShutdownTimeoutMillis(int)}.
+ * the timeout duration. See {@link Builder#setShutdownTimeoutMillis(long)}.
*
* @hide
*/
@SystemApi
- public int getShutdownTimeoutMillis() {
+ public long getShutdownTimeoutMillis() {
return mShutdownTimeoutMillis;
}
/**
* Returns a flag indicating whether clients need to be pre-approved by the user.
* (true: authorization required) or not (false: not required).
- * {@link Builder#enableClientControlByUser(Boolean)}.
+ * {@link Builder#setClientControlByUserEnabled(Boolean)}.
*
* @hide
*/
@@ -478,7 +477,7 @@
/**
* Returns List of clients which aren't allowed to associate to the AP.
*
- * Clients are configured using {@link Builder#setClientList(List, List)}
+ * Clients are configured using {@link Builder#setBlockedClientList(List)}
*
* @hide
*/
@@ -490,7 +489,7 @@
/**
* List of clients which are allowed to associate to the AP.
- * Clients are configured using {@link Builder#setClientList(List, List)}
+ * Clients are configured using {@link Builder#setAllowedClientList(List)}
*
* @hide
*/
@@ -575,7 +574,7 @@
private int mMaxNumberOfClients;
private int mSecurityType;
private boolean mAutoShutdownEnabled;
- private int mShutdownTimeoutMillis;
+ private long mShutdownTimeoutMillis;
private boolean mClientControlByUser;
private List<MacAddress> mBlockedClientList;
private List<MacAddress> mAllowedClientList;
@@ -627,6 +626,11 @@
*/
@NonNull
public SoftApConfiguration build() {
+ for (MacAddress client : mAllowedClientList) {
+ if (mBlockedClientList.contains(client)) {
+ throw new IllegalArgumentException("A MacAddress exist in both client list");
+ }
+ }
return new SoftApConfiguration(mSsid, mBssid, mPassphrase,
mHiddenSsid, mBand, mChannel, mSecurityType, mMaxNumberOfClients,
mAutoShutdownEnabled, mShutdownTimeoutMillis, mClientControlByUser,
@@ -835,7 +839,7 @@
* @param enable true to enable, false to disable.
* @return Builder for chaining.
*
- * @see #setShutdownTimeoutMillis(int)
+ * @see #setShutdownTimeoutMillis(long)
*/
@NonNull
public Builder setAutoShutdownEnabled(boolean enable) {
@@ -862,7 +866,7 @@
* @see #setAutoShutdownEnabled(boolean)
*/
@NonNull
- public Builder setShutdownTimeoutMillis(@IntRange(from = 0) int timeoutMillis) {
+ public Builder setShutdownTimeoutMillis(@IntRange(from = 0) long timeoutMillis) {
if (timeoutMillis < 0) {
throw new IllegalArgumentException("Invalid timeout value");
}
@@ -878,7 +882,7 @@
*
* If manual user control is enabled then clients will be accepted, rejected, or require
* a user approval based on the configuration provided by
- * {@link #setClientList(List, List)}.
+ * {@link #setBlockedClientList(List)} and {@link #setAllowedClientList(List)}.
*
* <p>
* This method requires hardware support. Hardware support can be determined using
@@ -898,26 +902,48 @@
* @return Builder for chaining.
*/
@NonNull
- public Builder enableClientControlByUser(boolean enabled) {
+ public Builder setClientControlByUserEnabled(boolean enabled) {
mClientControlByUser = enabled;
return this;
}
/**
- * This method together with {@link enableClientControlByUser(boolean)} control client
- * connections to the AP. If {@link enableClientControlByUser(false)} is configured than
+ * This method together with {@link setClientControlByUserEnabled(boolean)} control client
+ * connections to the AP. If client control by user is disabled using the above method then
* this API has no effect and clients are allowed to associate to the AP (within limit of
* max number of clients).
*
- * If {@link enableClientControlByUser(true)} is configured then this API configures
- * 2 lists:
+ * If client control by user is enabled then this API configures the list of clients
+ * which are explicitly allowed. These are auto-accepted.
+ *
+ * All other clients which attempt to associate, whose MAC addresses are on neither list,
+ * are:
* <ul>
- * <li>List of clients which are blocked. These are rejected.</li>
- * <li>List of clients which are explicitly allowed. These are auto-accepted.</li>
+ * <li>Rejected</li>
+ * <li>A callback {@link WifiManager.SoftApCallback#onBlockedClientConnecting(WifiClient)}
+ * is issued (which allows the user to add them to the allowed client list if desired).<li>
* </ul>
*
- * <p>
+ * @param allowedClientList list of clients which are allowed to associate to the AP
+ * without user pre-approval.
+ * @return Builder for chaining.
+ */
+ @NonNull
+ public Builder setAllowedClientList(@NonNull List<MacAddress> allowedClientList) {
+ mAllowedClientList = new ArrayList<>(allowedClientList);
+ return this;
+ }
+
+ /**
+ * This method together with {@link setClientControlByUserEnabled(boolean)} control client
+ * connections to the AP. If client control by user is disabled using the above method then
+ * this API has no effect and clients are allowed to associate to the AP (within limit of
+ * max number of clients).
+ *
+ * If client control by user is enabled then this API this API configures the list of
+ * clients which are blocked. These are rejected.
+ *
* All other clients which attempt to associate, whose MAC addresses are on neither list,
* are:
* <ul>
@@ -927,23 +953,11 @@
* </ul>
*
* @param blockedClientList list of clients which are not allowed to associate to the AP.
- * @param allowedClientList list of clients which are allowed to associate to the AP
- * without user pre-approval.
* @return Builder for chaining.
*/
@NonNull
- public Builder setClientList(@NonNull List<MacAddress> blockedClientList,
- @NonNull List<MacAddress> allowedClientList) {
+ public Builder setBlockedClientList(@NonNull List<MacAddress> blockedClientList) {
mBlockedClientList = new ArrayList<>(blockedClientList);
- mAllowedClientList = new ArrayList<>(allowedClientList);
- Iterator<MacAddress> iterator = mAllowedClientList.iterator();
- while (iterator.hasNext()) {
- MacAddress client = iterator.next();
- int index = mBlockedClientList.indexOf(client);
- if (index != -1) {
- throw new IllegalArgumentException("A MacAddress exist in both list");
- }
- }
return this;
}
}
diff --git a/wifi/java/android/net/wifi/WifiAnnotations.java b/wifi/java/android/net/wifi/WifiAnnotations.java
index 05e5b1d..acda7e0 100644
--- a/wifi/java/android/net/wifi/WifiAnnotations.java
+++ b/wifi/java/android/net/wifi/WifiAnnotations.java
@@ -61,6 +61,26 @@
@Retention(RetentionPolicy.SOURCE)
public @interface Bandwidth {}
+ @IntDef(prefix = { "CHANNEL_WIDTH_" }, value = {
+ ScanResult.CHANNEL_WIDTH_20MHZ,
+ ScanResult.CHANNEL_WIDTH_40MHZ,
+ ScanResult.CHANNEL_WIDTH_80MHZ,
+ ScanResult.CHANNEL_WIDTH_160MHZ,
+ ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface ChannelWidth{}
+
+ @IntDef(prefix = { "WIFI_STANDARD_" }, value = {
+ ScanResult.WIFI_STANDARD_UNKNOWN,
+ ScanResult.WIFI_STANDARD_LEGACY,
+ ScanResult.WIFI_STANDARD_11N,
+ ScanResult.WIFI_STANDARD_11AC,
+ ScanResult.WIFI_STANDARD_11AX,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface WifiStandard{}
+
@IntDef(prefix = { "PROTOCOL_" }, value = {
ScanResult.PROTOCOL_NONE,
ScanResult.PROTOCOL_WPA,
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
index 5a7bf4b..ba68d17 100644
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ b/wifi/java/android/net/wifi/WifiConfiguration.java
@@ -498,11 +498,15 @@
allowedProtocols.set(WifiConfiguration.Protocol.RSN);
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
+ allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
+ allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
requirePmf = true;
break;
case SECURITY_TYPE_EAP_SUITE_B:
allowedProtocols.set(WifiConfiguration.Protocol.RSN);
+ allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
+ allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
@@ -515,7 +519,9 @@
allowedProtocols.set(WifiConfiguration.Protocol.RSN);
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
+ allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
+ allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
requirePmf = true;
break;
case SECURITY_TYPE_WAPI_PSK:
@@ -629,13 +635,6 @@
public String preSharedKey;
/**
- * Optional SAE Password Id for use with WPA3-SAE. It is an ASCII string.
- * @hide
- */
- @SystemApi
- public @Nullable String saePasswordId;
-
- /**
* Four WEP keys. For each of the four values, provide either an ASCII
* string enclosed in double quotation marks (e.g., {@code "abcdef"}),
* a string of hex digits (e.g., {@code 0102030405}), or an empty string
@@ -2328,9 +2327,6 @@
sbuf.append('*');
}
- sbuf.append('\n').append(" SAE Password Id: ");
- sbuf.append(this.saePasswordId);
-
sbuf.append("\nEnterprise config:\n");
sbuf.append(enterpriseConfig);
@@ -2725,7 +2721,6 @@
providerFriendlyName = source.providerFriendlyName;
isHomeProviderNetwork = source.isHomeProviderNetwork;
preSharedKey = source.preSharedKey;
- saePasswordId = source.saePasswordId;
mNetworkSelectionStatus.copy(source.getNetworkSelectionStatus());
apBand = source.apBand;
@@ -2813,7 +2808,6 @@
dest.writeLong(roamingConsortiumId);
}
dest.writeString(preSharedKey);
- dest.writeString(saePasswordId);
for (String wepKey : wepKeys) {
dest.writeString(wepKey);
}
@@ -2889,7 +2883,6 @@
config.roamingConsortiumIds[i] = in.readLong();
}
config.preSharedKey = in.readString();
- config.saePasswordId = in.readString();
for (int i = 0; i < config.wepKeys.length; i++) {
config.wepKeys[i] = in.readString();
}
diff --git a/wifi/java/android/net/wifi/WifiInfo.java b/wifi/java/android/net/wifi/WifiInfo.java
index 142854a..70c5e72 100644
--- a/wifi/java/android/net/wifi/WifiInfo.java
+++ b/wifi/java/android/net/wifi/WifiInfo.java
@@ -103,7 +103,7 @@
/**
* Wi-Fi standard for the connection
*/
- private @ScanResult.WifiStandard int mWifiStandard;
+ private @WifiAnnotations.WifiStandard int mWifiStandard;
/**
* The unit in which links speeds are expressed.
@@ -518,7 +518,7 @@
* Sets the Wi-Fi standard
* @hide
*/
- public void setWifiStandard(@ScanResult.WifiStandard int wifiStandard) {
+ public void setWifiStandard(@WifiAnnotations.WifiStandard int wifiStandard) {
mWifiStandard = wifiStandard;
}
@@ -526,7 +526,7 @@
* Get connection Wi-Fi standard
* @return the connection Wi-Fi standard
*/
- public @ScanResult.WifiStandard int getWifiStandard() {
+ public @WifiAnnotations.WifiStandard int getWifiStandard() {
return mWifiStandard;
}
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 9703fa6..e1acaf8 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -727,8 +727,9 @@
/**
* If Soft Ap client is blocked, this reason code means that client doesn't exist in the
- * specified configuration {@link SoftApConfiguration.Builder#setClientList(List, List)}
- * and the {@link SoftApConfiguration.Builder#enableClientControlByUser(true)}
+ * specified configuration {@link SoftApConfiguration.Builder#setBlockedClientList(List)}
+ * and {@link SoftApConfiguration.Builder#setAllowedClientList(List)}
+ * and the {@link SoftApConfiguration.Builder#setClientControlByUserEnabled(boolean)}
* is configured as well.
* @hide
*/
@@ -1352,7 +1353,7 @@
try {
ParceledListSlice<WifiConfiguration> parceledList =
mService.getConfiguredNetworks(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
if (parceledList == null) {
return Collections.emptyList();
}
@@ -1369,7 +1370,7 @@
try {
ParceledListSlice<WifiConfiguration> parceledList =
mService.getPrivilegedConfiguredNetworks(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
if (parceledList == null) {
return Collections.emptyList();
}
@@ -1898,7 +1899,7 @@
@NonNull List<WifiNetworkSuggestion> networkSuggestions) {
try {
return mService.addNetworkSuggestions(
- networkSuggestions, mContext.getOpPackageName(), mContext.getFeatureId());
+ networkSuggestions, mContext.getOpPackageName(), mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2563,7 +2564,7 @@
* valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
* @return {@code true} if supported, {@code false} otherwise.
*/
- public boolean isWifiStandardSupported(@ScanResult.WifiStandard int standard) {
+ public boolean isWifiStandardSupported(@WifiAnnotations.WifiStandard int standard) {
try {
return mService.isWifiStandardSupported(standard);
} catch (RemoteException e) {
@@ -2680,8 +2681,8 @@
public boolean startScan(WorkSource workSource) {
try {
String packageName = mContext.getOpPackageName();
- String featureId = mContext.getFeatureId();
- return mService.startScan(packageName, featureId);
+ String attributionTag = mContext.getAttributionTag();
+ return mService.startScan(packageName, attributionTag);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2713,7 +2714,7 @@
public WifiInfo getConnectionInfo() {
try {
return mService.getConnectionInfo(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2728,35 +2729,38 @@
public List<ScanResult> getScanResults() {
try {
return mService.getScanResults(mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
- * Return the filtered ScanResults which may be authenticated by the suggested network
- * configurations.
- * @param networkSuggestions The list of {@link WifiNetworkSuggestion}
- * @param scanResults The scan results to be filtered, this is optional, if it is null or
- * empty, wifi system would use the recent scan results in the system.
- * @return The map of {@link WifiNetworkSuggestion} and the list of {@link ScanResult} which
- * may be authenticated by the corresponding network configuration.
+ * Get the filtered ScanResults which match the network configurations specified by the
+ * {@code networkSuggestionsToMatch}. Suggestions which use {@link WifiConfiguration} use
+ * SSID and the security type to match. Suggestions which use {@link PasspointConfigration}
+ * use the matching rules of Hotspot 2.0.
+ * @param networkSuggestionsToMatch The list of {@link WifiNetworkSuggestion} to match against.
+ * These may or may not be suggestions which are installed on the device.
+ * @param scanResults The scan results to be filtered. Optional - if not provided(empty list),
+ * the Wi-Fi service will use the most recent scan results which the system has.
+ * @return The map of {@link WifiNetworkSuggestion} to the list of {@link ScanResult}
+ * corresponding to networks which match them.
* @hide
*/
@SystemApi
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
@NonNull
public Map<WifiNetworkSuggestion, List<ScanResult>> getMatchingScanResults(
- @NonNull List<WifiNetworkSuggestion> networkSuggestions,
+ @NonNull List<WifiNetworkSuggestion> networkSuggestionsToMatch,
@Nullable List<ScanResult> scanResults) {
- if (networkSuggestions == null) {
+ if (networkSuggestionsToMatch == null) {
throw new IllegalArgumentException("networkSuggestions must not be null.");
}
try {
return mService.getMatchingScanResults(
- networkSuggestions, scanResults,
- mContext.getOpPackageName(), mContext.getFeatureId());
+ networkSuggestionsToMatch, scanResults,
+ mContext.getOpPackageName(), mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2826,7 +2830,7 @@
*/
@Nullable
@SystemApi
- @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
+ @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
public String getCountryCode() {
try {
return mService.getCountryCode();
@@ -3195,7 +3199,7 @@
new LocalOnlyHotspotCallbackProxy(this, executor, callback);
try {
String packageName = mContext.getOpPackageName();
- String featureId = mContext.getFeatureId();
+ String featureId = mContext.getAttributionTag();
int returnCode = mService.startLocalOnlyHotspot(proxy, packageName, featureId,
config);
if (returnCode != LocalOnlyHotspotCallback.REQUEST_REGISTERED) {
@@ -3372,7 +3376,7 @@
*/
@NonNull
@SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
+ @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
public SoftApConfiguration getSoftApConfiguration() {
try {
return mService.getSoftApConfiguration();
@@ -3406,9 +3410,10 @@
* If the API is called while the tethered soft AP is enabled, the configuration will apply to
* the current soft AP if the new configuration only includes
* {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)}
- * or {@link SoftApConfiguration.Builder#setShutdownTimeoutMillis(int)}
- * or {@link SoftApConfiguration.Builder#enableClientControlByUser(boolean)}
- * or {@link SoftApConfiguration.Builder#setClientList(List, List)}.
+ * or {@link SoftApConfiguration.Builder#setShutdownTimeoutMillis(long)}
+ * or {@link SoftApConfiguration.Builder#setClientControlByUserEnabled(boolean)}
+ * or {@link SoftApConfiguration.Builder#setBlockedClientList(List)}
+ * or {@link SoftApConfiguration.Builder#setAllowedClientList(List)}
*
* Otherwise, the configuration changes will be applied when the Soft AP is next started
* (the framework will not stop/start the AP).
@@ -4989,7 +4994,7 @@
* @hide
*/
@SystemApi
- @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL)
+ @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
public void factoryReset() {
try {
mService.factoryReset(mContext.getOpPackageName());
@@ -5886,7 +5891,7 @@
try {
mService.registerSuggestionConnectionStatusListener(new Binder(),
new SuggestionConnectionStatusListenerProxy(executor, listener),
- listener.hashCode(), mContext.getOpPackageName(), mContext.getFeatureId());
+ listener.hashCode(), mContext.getOpPackageName(), mContext.getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -5986,22 +5991,22 @@
}
/**
- * Callback interface for framework to receive network status changes and trigger of updating
+ * Callback interface for framework to receive network status updates and trigger of updating
* {@link WifiUsabilityStatsEntry}.
*
* @hide
*/
@SystemApi
- public interface ScoreChangeCallback {
+ public interface ScoreUpdateObserver {
/**
* Called by applications to indicate network status.
*
* @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#start(int)}.
+ * {@link WifiConnectedNetworkScorer#onStart(int)}.
* @param score The score representing link quality of current Wi-Fi network connection.
* Populated by connected network scorer in applications..
*/
- void onScoreChange(int sessionId, int score);
+ void notifyScoreUpdate(int sessionId, int score);
/**
* Called by applications to trigger an update of {@link WifiUsabilityStatsEntry}.
@@ -6009,36 +6014,36 @@
* {@link addOnWifiUsabilityStatsListener(Executor, OnWifiUsabilityStatsListener)}.
*
* @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#start(int)}.
+ * {@link WifiConnectedNetworkScorer#onStart(int)}.
*/
- void onTriggerUpdateOfWifiUsabilityStats(int sessionId);
+ void triggerUpdateOfWifiUsabilityStats(int sessionId);
}
/**
- * Callback proxy for {@link ScoreChangeCallback} objects.
+ * Callback proxy for {@link ScoreUpdateObserver} objects.
*
* @hide
*/
- private class ScoreChangeCallbackProxy implements ScoreChangeCallback {
- private final IScoreChangeCallback mScoreChangeCallback;
+ private class ScoreUpdateObserverProxy implements ScoreUpdateObserver {
+ private final IScoreUpdateObserver mScoreUpdateObserver;
- private ScoreChangeCallbackProxy(IScoreChangeCallback callback) {
- mScoreChangeCallback = callback;
+ private ScoreUpdateObserverProxy(IScoreUpdateObserver observer) {
+ mScoreUpdateObserver = observer;
}
@Override
- public void onScoreChange(int sessionId, int score) {
+ public void notifyScoreUpdate(int sessionId, int score) {
try {
- mScoreChangeCallback.onScoreChange(sessionId, score);
+ mScoreUpdateObserver.notifyScoreUpdate(sessionId, score);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
- public void onTriggerUpdateOfWifiUsabilityStats(int sessionId) {
+ public void triggerUpdateOfWifiUsabilityStats(int sessionId) {
try {
- mScoreChangeCallback.onTriggerUpdateOfWifiUsabilityStats(sessionId);
+ mScoreUpdateObserver.triggerUpdateOfWifiUsabilityStats(sessionId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -6058,21 +6063,21 @@
* Called by framework to indicate the start of a network connection.
* @param sessionId The ID to indicate current Wi-Fi network connection.
*/
- void start(int sessionId);
+ void onStart(int sessionId);
/**
* Called by framework to indicate the end of a network connection.
* @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#start(int)}.
+ * {@link WifiConnectedNetworkScorer#onStart(int)}.
*/
- void stop(int sessionId);
+ void onStop(int sessionId);
/**
* Framework sets callback for score change events after application sets its scorer.
- * @param cbImpl The instance for {@link WifiManager#ScoreChangeCallback}. Should be
+ * @param observerImpl The instance for {@link WifiManager#ScoreUpdateObserver}. Should be
* implemented and instantiated by framework.
*/
- void setScoreChangeCallback(@NonNull ScoreChangeCallback cbImpl);
+ void onSetScoreUpdateObserver(@NonNull ScoreUpdateObserver observerImpl);
}
/**
@@ -6090,32 +6095,32 @@
}
@Override
- public void start(int sessionId) {
+ public void onStart(int sessionId) {
if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: " + "start: sessionId=" + sessionId);
+ Log.v(TAG, "WifiConnectedNetworkScorer: " + "onStart: sessionId=" + sessionId);
}
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.start(sessionId));
+ mExecutor.execute(() -> mScorer.onStart(sessionId));
}
@Override
- public void stop(int sessionId) {
+ public void onStop(int sessionId) {
if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: " + "stop: sessionId=" + sessionId);
+ Log.v(TAG, "WifiConnectedNetworkScorer: " + "onStop: sessionId=" + sessionId);
}
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.stop(sessionId));
+ mExecutor.execute(() -> mScorer.onStop(sessionId));
}
@Override
- public void setScoreChangeCallback(IScoreChangeCallback cbImpl) {
+ public void onSetScoreUpdateObserver(IScoreUpdateObserver observerImpl) {
if (mVerboseLoggingEnabled) {
Log.v(TAG, "WifiConnectedNetworkScorer: "
- + "setScoreChangeCallback: cbImpl=" + cbImpl);
+ + "onSetScoreUpdateObserver: observerImpl=" + observerImpl);
}
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.setScoreChangeCallback(
- new ScoreChangeCallbackProxy(cbImpl)));
+ mExecutor.execute(() -> mScorer.onSetScoreUpdateObserver(
+ new ScoreUpdateObserverProxy(observerImpl)));
}
}
diff --git a/wifi/java/android/net/wifi/WifiMigration.java b/wifi/java/android/net/wifi/WifiMigration.java
index a3482d7..008b18b 100755
--- a/wifi/java/android/net/wifi/WifiMigration.java
+++ b/wifi/java/android/net/wifi/WifiMigration.java
@@ -16,8 +16,6 @@
package android.net.wifi;
-import static com.android.internal.util.Preconditions.checkNotNull;
-
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
@@ -26,8 +24,6 @@
import android.os.Parcelable;
import android.provider.Settings;
-import java.util.List;
-
/**
* Class used to provide one time hooks for existing OEM devices to migrate their config store
* data and other settings to the wifi mainline module.
@@ -39,166 +35,6 @@
private WifiMigration() { }
/**
- * Container for all the wifi config data to migrate.
- */
- public static final class ConfigStoreMigrationData implements Parcelable {
- /**
- * Builder to create instance of {@link ConfigStoreMigrationData}.
- */
- public static final class Builder {
- private List<WifiConfiguration> mUserSavedNetworkConfigurations;
- private SoftApConfiguration mUserSoftApConfiguration;
-
- public Builder() {
- mUserSavedNetworkConfigurations = null;
- mUserSoftApConfiguration = null;
- }
-
- /**
- * Sets the list of all user's saved network configurations parsed from OEM config
- * store files.
- *
- * @param userSavedNetworkConfigurations List of {@link WifiConfiguration} representing
- * the list of user's saved networks
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setUserSavedNetworkConfigurations(
- @NonNull List<WifiConfiguration> userSavedNetworkConfigurations) {
- checkNotNull(userSavedNetworkConfigurations);
- mUserSavedNetworkConfigurations = userSavedNetworkConfigurations;
- return this;
- }
-
- /**
- * Sets the user's softap configuration parsed from OEM config store files.
- *
- * @param userSoftApConfiguration {@link SoftApConfiguration} representing user's
- * SoftAp configuration
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setUserSoftApConfiguration(
- @NonNull SoftApConfiguration userSoftApConfiguration) {
- checkNotNull(userSoftApConfiguration);
- mUserSoftApConfiguration = userSoftApConfiguration;
- return this;
- }
-
- /**
- * Build an instance of {@link ConfigStoreMigrationData}.
- *
- * @return Instance of {@link ConfigStoreMigrationData}.
- */
- public @NonNull ConfigStoreMigrationData build() {
- return new ConfigStoreMigrationData(
- mUserSavedNetworkConfigurations, mUserSoftApConfiguration);
- }
- }
-
- private final List<WifiConfiguration> mUserSavedNetworkConfigurations;
- private final SoftApConfiguration mUserSoftApConfiguration;
-
- private ConfigStoreMigrationData(
- @Nullable List<WifiConfiguration> userSavedNetworkConfigurations,
- @Nullable SoftApConfiguration userSoftApConfiguration) {
- mUserSavedNetworkConfigurations = userSavedNetworkConfigurations;
- mUserSoftApConfiguration = userSoftApConfiguration;
- }
-
- public static final @NonNull Parcelable.Creator<ConfigStoreMigrationData> CREATOR =
- new Parcelable.Creator<ConfigStoreMigrationData>() {
- @Override
- public ConfigStoreMigrationData createFromParcel(Parcel in) {
- List<WifiConfiguration> userSavedNetworkConfigurations =
- in.readArrayList(null);
- SoftApConfiguration userSoftApConfiguration = in.readParcelable(null);
- return new ConfigStoreMigrationData(
- userSavedNetworkConfigurations, userSoftApConfiguration);
- }
-
- @Override
- public ConfigStoreMigrationData[] newArray(int size) {
- return new ConfigStoreMigrationData[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeList(mUserSavedNetworkConfigurations);
- dest.writeParcelable(mUserSoftApConfiguration, flags);
- }
-
- /**
- * Returns list of all user's saved network configurations.
- *
- * Note: Only to be returned if there is any format change in how OEM persisted this info.
- * @return List of {@link WifiConfiguration} representing the list of user's saved networks,
- * or null if no migration necessary.
- */
- @Nullable
- public List<WifiConfiguration> getUserSavedNetworkConfigurations() {
- return mUserSavedNetworkConfigurations;
- }
-
- /**
- * Returns user's softap configuration.
- *
- * Note: Only to be returned if there is any format change in how OEM persisted this info.
- * @return {@link SoftApConfiguration} representing user's SoftAp configuration,
- * or null if no migration necessary.
- */
- @Nullable
- public SoftApConfiguration getUserSoftApConfiguration() {
- return mUserSoftApConfiguration;
- }
- }
-
- /**
- * Load data from OEM's config store.
- * <p>
- * Note:
- * <li>OEMs need to implement {@link #loadFromConfigStore()} ()} only if their
- * existing config store format or file locations differs from the vanilla AOSP implementation.
- * </li>
- * <li>The wifi mainline module will invoke {@link #loadFromConfigStore()} method on every
- * bootup, its the responsibility of the OEM implementation to ensure that this method returns
- * non-null data only on the first bootup. Once the migration is done, the OEM can safely delete
- * their config store files when {@link #removeConfigStore()} is invoked.
- * <li>The first & only relevant invocation of {@link #loadFromConfigStore()} occurs when a
- * previously released device upgrades to the wifi mainline module from an OEM implementation
- * of the wifi stack.
- * </li>
- *
- * @return Instance of {@link ConfigStoreMigrationData} for migrating data, null if no
- * migration is necessary.
- */
- @Nullable
- public static ConfigStoreMigrationData loadFromConfigStore() {
- // Note: OEMs should add code to parse data from their config store format here!
- return null;
- }
-
- /**
- * Remove OEM's config store.
- * <p>
- * Note:
- * <li>OEMs need to implement {@link #removeConfigStore()} only if their
- * existing config store format or file locations differs from the vanilla AOSP implementation (
- * which is what the wifi mainline module understands).
- * </li>
- * <li> The wifi mainline module will invoke {@link #removeConfigStore()} after it migrates
- * all the existing data retrieved from {@link #loadFromConfigStore()}.
- * </li>
- */
- public static void removeConfigStore() {
- // Note: OEMs should remove their custom config store files here!
- }
-
- /**
* Container for all the wifi settings data to migrate.
*/
public static final class SettingsMigrationData implements Parcelable {
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
index 6dbb0bd..72ca900 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
@@ -545,6 +545,7 @@
mIsMetered ? WifiConfiguration.METERED_OVERRIDE_METERED
: WifiConfiguration.METERED_OVERRIDE_NONE;
wifiConfiguration.carrierId = mCarrierId;
+ wifiConfiguration.trusted = !mIsNetworkUntrusted;
return wifiConfiguration;
}
@@ -684,8 +685,7 @@
mIsAppInteractionRequired,
mIsUserInteractionRequired,
mIsSharedWithUser,
- mIsInitialAutojoinEnabled,
- mIsNetworkUntrusted);
+ mIsInitialAutojoinEnabled);
}
}
@@ -728,13 +728,6 @@
*/
public final boolean isInitialAutoJoinEnabled;
- /**
- * Whether this network will be brought up as untrusted (TRUSTED capability bit removed).
- * @hide
- */
- public final boolean isNetworkUntrusted;
-
-
/** @hide */
public WifiNetworkSuggestion() {
this.wifiConfiguration = new WifiConfiguration();
@@ -743,7 +736,6 @@
this.isUserInteractionRequired = false;
this.isUserAllowedToManuallyConnect = true;
this.isInitialAutoJoinEnabled = true;
- this.isNetworkUntrusted = false;
}
/** @hide */
@@ -752,8 +744,7 @@
boolean isAppInteractionRequired,
boolean isUserInteractionRequired,
boolean isUserAllowedToManuallyConnect,
- boolean isInitialAutoJoinEnabled,
- boolean isNetworkUntrusted) {
+ boolean isInitialAutoJoinEnabled) {
checkNotNull(networkConfiguration);
this.wifiConfiguration = networkConfiguration;
this.passpointConfiguration = passpointConfiguration;
@@ -762,7 +753,6 @@
this.isUserInteractionRequired = isUserInteractionRequired;
this.isUserAllowedToManuallyConnect = isUserAllowedToManuallyConnect;
this.isInitialAutoJoinEnabled = isInitialAutoJoinEnabled;
- this.isNetworkUntrusted = isNetworkUntrusted;
}
public static final @NonNull Creator<WifiNetworkSuggestion> CREATOR =
@@ -775,8 +765,7 @@
in.readBoolean(), // isAppInteractionRequired
in.readBoolean(), // isUserInteractionRequired
in.readBoolean(), // isSharedCredentialWithUser
- in.readBoolean(), // isAutojoinEnabled
- in.readBoolean()
+ in.readBoolean() // isAutojoinEnabled
);
}
@@ -799,7 +788,6 @@
dest.writeBoolean(isUserInteractionRequired);
dest.writeBoolean(isUserAllowedToManuallyConnect);
dest.writeBoolean(isInitialAutoJoinEnabled);
- dest.writeBoolean(isNetworkUntrusted);
}
@Override
@@ -842,7 +830,7 @@
.append(", isUserInteractionRequired=").append(isUserInteractionRequired)
.append(", isCredentialSharedWithUser=").append(isUserAllowedToManuallyConnect)
.append(", isInitialAutoJoinEnabled=").append(isInitialAutoJoinEnabled)
- .append(", isUnTrusted=").append(isNetworkUntrusted)
+ .append(", isUnTrusted=").append(!wifiConfiguration.trusted)
.append(" ]");
return sb.toString();
}
@@ -933,7 +921,7 @@
/** @see Builder#setUntrusted(boolean) */
public boolean isUntrusted() {
- return isNetworkUntrusted;
+ return !wifiConfiguration.trusted;
}
/**
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
index 5e48919..d299cdc 100644
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ b/wifi/java/android/net/wifi/WifiScanner.java
@@ -182,7 +182,7 @@
public List<Integer> getAvailableChannels(int band) {
try {
Bundle bundle = mService.getAvailableChannels(band, mContext.getOpPackageName(),
- mContext.getFeatureId());
+ mContext.getAttributionTag());
List<Integer> channels = bundle.getIntegerArrayList(GET_AVAILABLE_CHANNELS_EXTRA);
return channels == null ? new ArrayList<>() : channels;
} catch (RemoteException e) {
@@ -963,7 +963,7 @@
scanParams.putParcelable(SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
scanParams.putParcelable(SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getFeatureId());
+ scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
mAsyncChannel.sendMessage(CMD_START_BACKGROUND_SCAN, 0, key, scanParams);
}
@@ -984,7 +984,7 @@
validateChannel();
Bundle scanParams = new Bundle();
scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getFeatureId());
+ scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
mAsyncChannel.sendMessage(CMD_STOP_BACKGROUND_SCAN, 0, key, scanParams);
}
@@ -1001,7 +1001,7 @@
validateChannel();
Bundle scanParams = new Bundle();
scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getFeatureId());
+ scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
Message reply =
mAsyncChannel.sendMessageSynchronously(CMD_GET_SCAN_RESULTS, 0, 0, scanParams);
return reply.what == CMD_OP_SUCCEEDED;
@@ -1056,7 +1056,7 @@
scanParams.putParcelable(SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
scanParams.putParcelable(SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getFeatureId());
+ scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
mAsyncChannel.sendMessage(CMD_START_SINGLE_SCAN, 0, key, scanParams);
}
@@ -1073,7 +1073,7 @@
validateChannel();
Bundle scanParams = new Bundle();
scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getFeatureId());
+ scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
mAsyncChannel.sendMessage(CMD_STOP_SINGLE_SCAN, 0, key, scanParams);
}
@@ -1086,7 +1086,7 @@
validateChannel();
Bundle scanParams = new Bundle();
scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getFeatureId());
+ scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
Message reply = mAsyncChannel.sendMessageSynchronously(CMD_GET_SINGLE_SCAN_RESULTS, 0, 0,
scanParams);
if (reply.what == WifiScanner.CMD_OP_SUCCEEDED) {
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareManager.java b/wifi/java/android/net/wifi/aware/WifiAwareManager.java
index 2ebaa18..c2ae17c 100644
--- a/wifi/java/android/net/wifi/aware/WifiAwareManager.java
+++ b/wifi/java/android/net/wifi/aware/WifiAwareManager.java
@@ -267,7 +267,7 @@
try {
Binder binder = new Binder();
- mService.connect(binder, mContext.getOpPackageName(), mContext.getFeatureId(),
+ mService.connect(binder, mContext.getOpPackageName(), mContext.getAttributionTag(),
new WifiAwareEventCallbackProxy(this, looper, binder, attachCallback,
identityChangedListener), configRequest,
identityChangedListener != null);
@@ -298,7 +298,7 @@
}
try {
- mService.publish(mContext.getOpPackageName(), mContext.getFeatureId(), clientId,
+ mService.publish(mContext.getOpPackageName(), mContext.getAttributionTag(), clientId,
publishConfig,
new WifiAwareDiscoverySessionCallbackProxy(this, looper, true, callback,
clientId));
@@ -336,7 +336,7 @@
}
try {
- mService.subscribe(mContext.getOpPackageName(), mContext.getFeatureId(), clientId,
+ mService.subscribe(mContext.getOpPackageName(), mContext.getAttributionTag(), clientId,
subscribeConfig,
new WifiAwareDiscoverySessionCallbackProxy(this, looper, false, callback,
clientId));
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
index 65e8b3d..fa806e7 100644
--- a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
+++ b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
@@ -1037,18 +1037,7 @@
* @return a Unique identifier for a Credential object
*/
public int getUniqueId() {
- int usedCredential;
-
- // Initialize usedCredential based on the credential type of the profile
- if (mUserCredential != null) {
- usedCredential = 0;
- } else if (mCertCredential != null) {
- usedCredential = 1;
- } else {
- usedCredential = 2;
- }
-
- return Objects.hash(usedCredential, mRealm);
+ return Objects.hash(mUserCredential, mCertCredential, mSimCredential, mRealm);
}
@Override
diff --git a/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java b/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java
index a045aad..bb0cc97 100644
--- a/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java
+++ b/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java
@@ -19,6 +19,8 @@
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.net.wifi.ScanResult;
+import android.net.wifi.WifiAnnotations.ChannelWidth;
+import android.net.wifi.WifiAnnotations.WifiStandard;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
@@ -28,6 +30,9 @@
/**
* DeviceWiphyCapabilities for wificond
*
+ * Contains the WiFi physical layer attributes and capabilities of the device.
+ * It is used to collect these attributes from the device driver via wificond.
+ *
* @hide
*/
@SystemApi
@@ -61,7 +66,7 @@
* valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
* @return {@code true} if supported, {@code false} otherwise.
*/
- public boolean isWifiStandardSupported(int standard) {
+ public boolean isWifiStandardSupported(@WifiStandard int standard) {
switch (standard) {
case ScanResult.WIFI_STANDARD_LEGACY:
return true;
@@ -84,7 +89,7 @@
* valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
* @param support {@code true} if supported, {@code false} otherwise.
*/
- public void setWifiStandardSupport(int standard, boolean support) {
+ public void setWifiStandardSupport(@WifiStandard int standard, boolean support) {
switch (standard) {
case ScanResult.WIFI_STANDARD_11N:
m80211nSupported = support;
@@ -107,7 +112,7 @@
*
* @return {@code true} if supported, {@code false} otherwise.
*/
- public boolean isChannelWidthSupported(int chWidth) {
+ public boolean isChannelWidthSupported(@ChannelWidth int chWidth) {
switch (chWidth) {
case ScanResult.CHANNEL_WIDTH_20MHZ:
return true;
@@ -131,8 +136,10 @@
* @param chWidth valid values are {@link ScanResult#CHANNEL_WIDTH_160MHZ} and
* {@link ScanResult#CHANNEL_WIDTH_80MHZ_PLUS_MHZ}
* @param support {@code true} if supported, {@code false} otherwise.
+ *
+ * @hide
*/
- public void setChannelWidthSupported(int chWidth, boolean support) {
+ public void setChannelWidthSupported(@ChannelWidth int chWidth, boolean support) {
switch (chWidth) {
case ScanResult.CHANNEL_WIDTH_160MHZ:
mChannelWidth160MhzSupported = support;
@@ -159,6 +166,8 @@
* Set maximum number of transmit spatial streams
*
* @param streams number of spatial streams
+ *
+ * @hide
*/
public void setMaxNumberTxSpatialStreams(int streams) {
mMaxNumberTxSpatialStreams = streams;
@@ -177,6 +186,8 @@
* Set maximum number of receive spatial streams
*
* @param streams number of streams
+ *
+ * @hide
*/
public void setMaxNumberRxSpatialStreams(int streams) {
mMaxNumberRxSpatialStreams = streams;
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
index 9c2cad9..724ccf0 100644
--- a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
+++ b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
@@ -1180,7 +1180,7 @@
== AsyncChannel.STATUS_SUCCESSFUL) {
Bundle bundle = new Bundle();
bundle.putString(CALLING_PACKAGE, c.mContext.getOpPackageName());
- bundle.putString(CALLING_FEATURE_ID, c.mContext.getFeatureId());
+ bundle.putString(CALLING_FEATURE_ID, c.mContext.getAttributionTag());
bundle.putBinder(CALLING_BINDER, binder);
c.mAsyncChannel.sendMessage(UPDATE_CHANNEL_INFO, 0,
c.putListener(null), bundle);
@@ -1805,9 +1805,7 @@
* @hide
*/
@SystemApi
- @RequiresPermission(allOf = {
- android.Manifest.permission.CONNECTIVITY_INTERNAL,
- android.Manifest.permission.CONFIGURE_WIFI_DISPLAY})
+ @RequiresPermission(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY)
public void setMiracastMode(@MiracastMode int mode) {
try {
mService.setMiracastMode(mode);
diff --git a/wifi/java/android/net/wifi/rtt/WifiRttManager.java b/wifi/java/android/net/wifi/rtt/WifiRttManager.java
index cb0c5d4..865702a 100644
--- a/wifi/java/android/net/wifi/rtt/WifiRttManager.java
+++ b/wifi/java/android/net/wifi/rtt/WifiRttManager.java
@@ -146,8 +146,8 @@
Binder binder = new Binder();
try {
- mService.startRanging(binder, mContext.getOpPackageName(), mContext.getFeatureId(),
- workSource, request, new IRttCallback.Stub() {
+ mService.startRanging(binder, mContext.getOpPackageName(),
+ mContext.getAttributionTag(), workSource, request, new IRttCallback.Stub() {
@Override
public void onRangingFailure(int status) throws RemoteException {
clearCallingIdentity();
diff --git a/wifi/tests/AndroidTest.xml b/wifi/tests/AndroidTest.xml
index 987fee7..34e2e3a 100644
--- a/wifi/tests/AndroidTest.xml
+++ b/wifi/tests/AndroidTest.xml
@@ -25,4 +25,10 @@
<option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
<option name="hidden-api-checks" value="false"/>
</test>
+
+ <!-- Only run FrameworksWifiApiTests in MTS if the Wifi Mainline module is installed. -->
+ <object type="module_controller"
+ class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
+ <option name="mainline-module-package-name" value="com.google.android.wifi" />
+ </object>
</configuration>
diff --git a/wifi/tests/src/android/net/wifi/ScanResultTest.java b/wifi/tests/src/android/net/wifi/ScanResultTest.java
index b5c74d1..6cb8324 100644
--- a/wifi/tests/src/android/net/wifi/ScanResultTest.java
+++ b/wifi/tests/src/android/net/wifi/ScanResultTest.java
@@ -42,7 +42,7 @@
public static final int TEST_LEVEL = -56;
public static final int TEST_FREQUENCY = 2412;
public static final long TEST_TSF = 04660l;
- public static final @ScanResult.WifiStandard int TEST_WIFI_STANDARD =
+ public static final @WifiAnnotations.WifiStandard int TEST_WIFI_STANDARD =
ScanResult.WIFI_STANDARD_11AC;
/**
@@ -156,8 +156,7 @@
+ "distance: 0(cm), distanceSd: 0(cm), "
+ "passpoint: no, ChannelBandwidth: 0, centerFreq0: 0, centerFreq1: 0, "
+ "standard: 11ac, "
- + "80211mcResponder: is not supported, Carrier AP: no, "
- + "Carrier AP EAP Type: 0, Carrier name: null, "
+ + "80211mcResponder: is not supported, "
+ "Radio Chain Infos: null", scanResult.toString());
}
@@ -179,8 +178,7 @@
+ "distanceSd: 0(cm), "
+ "passpoint: no, ChannelBandwidth: 0, centerFreq0: 0, centerFreq1: 0, "
+ "standard: 11ac, "
- + "80211mcResponder: is not supported, Carrier AP: no, "
- + "Carrier AP EAP Type: 0, Carrier name: null, "
+ + "80211mcResponder: is not supported, "
+ "Radio Chain Infos: [RadioChainInfo: id=0, level=-45, "
+ "RadioChainInfo: id=1, level=-54]", scanResult.toString());
}
diff --git a/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java b/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java
index 060ddf0..1a44270 100644
--- a/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java
+++ b/wifi/tests/src/android/net/wifi/SoftApConfigurationTest.java
@@ -127,8 +127,9 @@
.setMaxNumberOfClients(10)
.setAutoShutdownEnabled(true)
.setShutdownTimeoutMillis(500000)
- .enableClientControlByUser(true)
- .setClientList(testBlockedClientList, testAllowedClientList)
+ .setClientControlByUserEnabled(true)
+ .setBlockedClientList(testBlockedClientList)
+ .setAllowedClientList(testAllowedClientList)
.build();
assertThat(original.getPassphrase()).isEqualTo("secretsecret");
assertThat(original.getSecurityType()).isEqualTo(
@@ -264,7 +265,9 @@
ArrayList<MacAddress> testBlockedClientList = new ArrayList<>();
testBlockedClientList.add(testMacAddress_1);
SoftApConfiguration.Builder configBuilder = new SoftApConfiguration.Builder();
- configBuilder.setClientList(testBlockedClientList, testAllowedClientList);
+ configBuilder.setBlockedClientList(testBlockedClientList)
+ .setAllowedClientList(testAllowedClientList)
+ .build();
}
@Test
diff --git a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
index 047a64b..e210e4f 100644
--- a/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiConfigurationTest.java
@@ -423,7 +423,9 @@
assertTrue(config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SAE));
assertTrue(config.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.CCMP));
+ assertTrue(config.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.GCMP_256));
assertTrue(config.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.CCMP));
+ assertTrue(config.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.GCMP_256));
assertTrue(config.requirePmf);
}
@@ -440,7 +442,9 @@
assertTrue(config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.OWE));
assertTrue(config.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.CCMP));
+ assertTrue(config.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.GCMP_256));
assertTrue(config.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.CCMP));
+ assertTrue(config.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.GCMP_256));
assertTrue(config.requirePmf);
}
@@ -456,6 +460,8 @@
config.setSecurityParams(SECURITY_TYPE_EAP_SUITE_B);
assertTrue(config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.SUITE_B_192));
+ assertTrue(config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP));
+ assertTrue(config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X));
assertTrue(config.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.GCMP_256));
assertTrue(config.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.GCMP_256));
assertTrue(config.allowedGroupManagementCiphers
diff --git a/wifi/tests/src/android/net/wifi/WifiManagerTest.java b/wifi/tests/src/android/net/wifi/WifiManagerTest.java
index 76ac837..90d6241 100644
--- a/wifi/tests/src/android/net/wifi/WifiManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiManagerTest.java
@@ -2349,23 +2349,24 @@
}
/**
- * Verify that Wi-Fi connected scorer receives score change callback after registeration.
+ * Verify that Wi-Fi connected scorer receives score update observer after registeration.
*/
@Test
- public void verifyScorerReceiveScoreChangeCallbackAfterRegistration() throws Exception {
+ public void verifyScorerReceiveScoreUpdateObserverAfterRegistration() throws Exception {
mExecutor = new SynchronousExecutor();
mWifiManager.setWifiConnectedNetworkScorer(mExecutor, mWifiConnectedNetworkScorer);
ArgumentCaptor<IWifiConnectedNetworkScorer.Stub> scorerCaptor =
ArgumentCaptor.forClass(IWifiConnectedNetworkScorer.Stub.class);
verify(mWifiService).setWifiConnectedNetworkScorer(any(IBinder.class),
scorerCaptor.capture());
- scorerCaptor.getValue().setScoreChangeCallback(any());
+ scorerCaptor.getValue().onSetScoreUpdateObserver(any());
mLooper.dispatchAll();
- verify(mWifiConnectedNetworkScorer).setScoreChangeCallback(any());
+ verify(mWifiConnectedNetworkScorer).onSetScoreUpdateObserver(any());
}
/**
- * Verify that Wi-Fi connected scorer receives session ID when start/stop methods are called.
+ * Verify that Wi-Fi connected scorer receives session ID when onStart/onStop methods
+ * are called.
*/
@Test
public void verifyScorerReceiveSessionIdWhenStartStopIsCalled() throws Exception {
@@ -2375,11 +2376,11 @@
ArgumentCaptor.forClass(IWifiConnectedNetworkScorer.Stub.class);
verify(mWifiService).setWifiConnectedNetworkScorer(any(IBinder.class),
callbackCaptor.capture());
- callbackCaptor.getValue().start(0);
- callbackCaptor.getValue().stop(10);
+ callbackCaptor.getValue().onStart(0);
+ callbackCaptor.getValue().onStop(10);
mLooper.dispatchAll();
- verify(mWifiConnectedNetworkScorer).start(0);
- verify(mWifiConnectedNetworkScorer).stop(10);
+ verify(mWifiConnectedNetworkScorer).onStart(0);
+ verify(mWifiConnectedNetworkScorer).onStop(10);
}
@Test
diff --git a/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java b/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
index 51bf738..01b2a8d 100644
--- a/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiNetworkSuggestionTest.java
@@ -532,7 +532,7 @@
configuration.BSSID = TEST_BSSID;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion(
- configuration, null, false, true, true, true, false);
+ configuration, null, false, true, true, true);
Parcel parcelW = Parcel.obtain();
suggestion.writeToParcel(parcelW, 0);
@@ -603,14 +603,14 @@
configuration.BSSID = TEST_BSSID;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
WifiNetworkSuggestion suggestion =
- new WifiNetworkSuggestion(configuration, null, true, false, true, true, false);
+ new WifiNetworkSuggestion(configuration, null, true, false, true, true);
WifiConfiguration configuration1 = new WifiConfiguration();
configuration1.SSID = TEST_SSID;
configuration1.BSSID = TEST_BSSID;
configuration1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
WifiNetworkSuggestion suggestion1 =
- new WifiNetworkSuggestion(configuration1, null, false, true, true, true, false);
+ new WifiNetworkSuggestion(configuration1, null, false, true, true, true);
assertEquals(suggestion, suggestion1);
assertEquals(suggestion.hashCode(), suggestion1.hashCode());
@@ -626,13 +626,13 @@
configuration.SSID = TEST_SSID;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiNetworkSuggestion suggestion =
- new WifiNetworkSuggestion(configuration, null, false, false, true, true, false);
+ new WifiNetworkSuggestion(configuration, null, false, false, true, true);
WifiConfiguration configuration1 = new WifiConfiguration();
configuration1.SSID = TEST_SSID_1;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiNetworkSuggestion suggestion1 =
- new WifiNetworkSuggestion(configuration1, null, false, false, true, true, false);
+ new WifiNetworkSuggestion(configuration1, null, false, false, true, true);
assertNotEquals(suggestion, suggestion1);
}
@@ -648,13 +648,13 @@
configuration.BSSID = TEST_BSSID;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiNetworkSuggestion suggestion =
- new WifiNetworkSuggestion(configuration, null, false, false, true, true, false);
+ new WifiNetworkSuggestion(configuration, null, false, false, true, true);
WifiConfiguration configuration1 = new WifiConfiguration();
configuration1.SSID = TEST_SSID;
configuration1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiNetworkSuggestion suggestion1 =
- new WifiNetworkSuggestion(configuration1, null, false, false, true, true, false);
+ new WifiNetworkSuggestion(configuration1, null, false, false, true, true);
assertNotEquals(suggestion, suggestion1);
}
@@ -669,13 +669,13 @@
configuration.SSID = TEST_SSID;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiNetworkSuggestion suggestion =
- new WifiNetworkSuggestion(configuration, null, false, false, true, true, false);
+ new WifiNetworkSuggestion(configuration, null, false, false, true, true);
WifiConfiguration configuration1 = new WifiConfiguration();
configuration1.SSID = TEST_SSID;
configuration1.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
WifiNetworkSuggestion suggestion1 =
- new WifiNetworkSuggestion(configuration1, null, false, false, true, true, false);
+ new WifiNetworkSuggestion(configuration1, null, false, false, true, true);
assertNotEquals(suggestion, suggestion1);
}
@@ -770,7 +770,7 @@
.setWpa2Passphrase(TEST_PRESHARED_KEY)
.setUntrusted(true)
.build();
- assertTrue(suggestion.isNetworkUntrusted);
+ assertTrue(suggestion.isUntrusted());
assertFalse(suggestion.isUserAllowedToManuallyConnect);
}
@@ -786,7 +786,7 @@
.setPasspointConfig(passpointConfiguration)
.setUntrusted(true)
.build();
- assertTrue(suggestion.isNetworkUntrusted);
+ assertTrue(suggestion.isUntrusted());
assertFalse(suggestion.isUserAllowedToManuallyConnect);
}
diff --git a/wifi/tests/src/android/net/wifi/WifiScannerTest.java b/wifi/tests/src/android/net/wifi/WifiScannerTest.java
index 0cc76b6..4881200 100644
--- a/wifi/tests/src/android/net/wifi/WifiScannerTest.java
+++ b/wifi/tests/src/android/net/wifi/WifiScannerTest.java
@@ -267,7 +267,7 @@
assertNull(messageBundle.getParcelable(WifiScanner.SCAN_PARAMS_WORK_SOURCE_KEY));
assertEquals(mContext.getOpPackageName(),
messageBundle.getParcelable(WifiScanner.REQUEST_PACKAGE_NAME_KEY));
- assertEquals(mContext.getFeatureId(),
+ assertEquals(mContext.getAttributionTag(),
messageBundle.getParcelable(WifiScanner.REQUEST_FEATURE_ID_KEY));
}
@@ -297,7 +297,7 @@
Bundle messageBundle = (Bundle) message.obj;
assertEquals(mContext.getOpPackageName(),
messageBundle.getParcelable(WifiScanner.REQUEST_PACKAGE_NAME_KEY));
- assertEquals(mContext.getFeatureId(),
+ assertEquals(mContext.getAttributionTag(),
messageBundle.getParcelable(WifiScanner.REQUEST_FEATURE_ID_KEY));
}
diff --git a/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java b/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java
index c682582..829d8f0 100644
--- a/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java
+++ b/wifi/tests/src/android/net/wifi/hotspot2/pps/CredentialTest.java
@@ -18,6 +18,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import android.net.wifi.EAPConstants;
@@ -551,4 +552,68 @@
public void validateTwoCertificateDifferent() {
assertFalse(Credential.isX509CertificateEquals(FakeKeys.CA_CERT0, FakeKeys.CA_CERT1));
}
+
+ /**
+ * Verify that unique identifiers are the same for objects with the same credentials
+ */
+ @Test
+ public void testUniqueIdSameCredentialTypes() throws Exception {
+ assertEquals(createCredentialWithSimCredential().getUniqueId(),
+ createCredentialWithSimCredential().getUniqueId());
+ assertEquals(createCredentialWithCertificateCredential().getUniqueId(),
+ createCredentialWithCertificateCredential().getUniqueId());
+ assertEquals(createCredentialWithUserCredential().getUniqueId(),
+ createCredentialWithUserCredential().getUniqueId());
+ }
+
+ /**
+ * Verify that unique identifiers are different for each credential
+ */
+ @Test
+ public void testUniqueIdDifferentForDifferentCredentialTypes() throws Exception {
+ Credential simCred = createCredentialWithSimCredential();
+ Credential certCred = createCredentialWithCertificateCredential();
+ Credential userCred = createCredentialWithUserCredential();
+
+ assertNotEquals(simCred.getUniqueId(), userCred.getUniqueId());
+ assertNotEquals(simCred.getUniqueId(), certCred.getUniqueId());
+ assertNotEquals(certCred.getUniqueId(), userCred.getUniqueId());
+ }
+
+ /**
+ * Verify that unique identifiers are different for a credential with different values
+ */
+ @Test
+ public void testUniqueIdDifferentForSimCredentialsWithDifferentValues() throws Exception {
+ Credential simCred1 = createCredentialWithSimCredential();
+ Credential simCred2 = createCredentialWithSimCredential();
+ simCred2.getSimCredential().setImsi("567890*");
+
+ assertNotEquals(simCred1.getUniqueId(), simCred2.getUniqueId());
+ }
+
+ /**
+ * Verify that unique identifiers are different for a credential with different values
+ */
+ @Test
+ public void testUniqueIdDifferentForUserCredentialsWithDifferentValues() throws Exception {
+ Credential userCred1 = createCredentialWithUserCredential();
+ Credential userCred2 = createCredentialWithUserCredential();
+ userCred2.getUserCredential().setUsername("anotheruser");
+
+ assertNotEquals(userCred1.getUniqueId(), userCred2.getUniqueId());
+ }
+
+ /**
+ * Verify that unique identifiers are different for a credential with different values
+ */
+ @Test
+ public void testUniqueIdDifferentForCertCredentialsWithDifferentValues() throws Exception {
+ Credential certCred1 = createCredentialWithCertificateCredential();
+ Credential certCred2 = createCredentialWithCertificateCredential();
+ certCred2.getCertCredential().setCertSha256Fingerprint(
+ MessageDigest.getInstance("SHA-256").digest(FakeKeys.CA_CERT0.getEncoded()));
+
+ assertNotEquals(certCred1.getUniqueId(), certCred2.getUniqueId());
+ }
}
diff --git a/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java b/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java
index a9dcde0..e6eae41 100644
--- a/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/rtt/WifiRttManagerTest.java
@@ -71,7 +71,7 @@
mMockLooperExecutor = mMockLooper.getNewExecutor();
when(mockContext.getOpPackageName()).thenReturn(packageName);
- when(mockContext.getFeatureId()).thenReturn(featureId);
+ when(mockContext.getAttributionTag()).thenReturn(featureId);
}
/**